]> git.ipfire.org Git - thirdparty/pdns.git/blame - pdns/misc.cc
Merge pull request #9070 from rgacogne/boost-173
[thirdparty/pdns.git] / pdns / misc.cc
CommitLineData
12c86877 1/*
12471842
PL
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 */
870a0fe4
AT
22#ifdef HAVE_CONFIG_H
23#include "config.h"
24#endif
705f31ae 25#include <sys/param.h>
22cf1fda 26#include <sys/socket.h>
3897b9e1 27#include <fcntl.h>
705f31ae
BH
28#include <netdb.h>
29#include <sys/time.h>
30#include <time.h>
3a8a4d68 31#include <sys/resource.h>
705f31ae 32#include <netinet/in.h>
76cb4593 33#include <sys/un.h>
705f31ae 34#include <unistd.h>
8290ad9f 35#include <fstream>
12c86877
BH
36#include "misc.hh"
37#include <vector>
38#include <sstream>
39#include <errno.h>
1258abe0 40#include <cstring>
c4bee46c 41#include <iostream>
a9b6db56 42#include <sys/types.h>
43#include <dirent.h>
705f31ae 44#include <algorithm>
6e2514e4 45#include <boost/optional.hpp>
fab091b9 46#include <poll.h>
12c86877 47#include <iomanip>
149d0144 48#include <netinet/tcp.h>
12c86877
BH
49#include <string.h>
50#include <stdlib.h>
51#include <stdio.h>
5c409fa2 52#include "pdnsexception.hh"
c6566265 53#include <sys/types.h>
040712e0 54#include <boost/algorithm/string.hpp>
65d8e171 55#include "iputils.hh"
e325f20c 56#include "dnsparser.hh"
ffb07158 57#include <sys/types.h>
58#include <pwd.h>
59#include <grp.h>
6c78a20e
R
60#ifdef __FreeBSD__
61# include <pthread_np.h>
62#endif
4d39d7f3
TIH
63#ifdef __NetBSD__
64# include <pthread.h>
65# include <sched.h>
66#endif
a61e8e59 67
a683e8bd 68size_t writen2(int fd, const void *buf, size_t count)
040712e0
BH
69{
70 const char *ptr = (char*)buf;
71 const char *eptr = ptr + count;
3ddb9247 72
a683e8bd 73 ssize_t res;
040712e0
BH
74 while(ptr != eptr) {
75 res = ::write(fd, ptr, eptr - ptr);
76 if(res < 0) {
77 if (errno == EAGAIN)
4957a608 78 throw std::runtime_error("used writen2 on non-blocking socket, got EAGAIN");
040712e0 79 else
4957a608 80 unixDie("failed in writen2");
040712e0
BH
81 }
82 else if (res == 0)
83 throw std::runtime_error("could not write all bytes, got eof in writen2");
3ddb9247 84
a683e8bd 85 ptr += (size_t) res;
040712e0 86 }
3ddb9247 87
040712e0
BH
88 return count;
89}
90
a683e8bd 91size_t readn2(int fd, void* buffer, size_t len)
36fbf590 92{
a683e8bd
RG
93 size_t pos=0;
94 ssize_t res;
36fbf590 95 for(;;) {
96 res = read(fd, (char*)buffer + pos, len - pos);
3ddb9247 97 if(res == 0)
3f6d07a4 98 throw runtime_error("EOF while reading message");
36fbf590 99 if(res < 0) {
100 if (errno == EAGAIN)
3f6d07a4 101 throw std::runtime_error("used readn2 on non-blocking socket, got EAGAIN");
36fbf590 102 else
3f6d07a4 103 unixDie("failed in readn2");
3ddb9247
PD
104 }
105
a683e8bd 106 pos+=(size_t)res;
36fbf590 107 if(pos == len)
108 break;
109 }
110 return len;
111}
112
9396d955 113size_t readn2WithTimeout(int fd, void* buffer, size_t len, int idleTimeout, int totalTimeout)
3f6d07a4
RG
114{
115 size_t pos = 0;
9396d955
RG
116 time_t start = 0;
117 int remainingTime = totalTimeout;
118 if (totalTimeout) {
119 start = time(NULL);
120 }
121
3f6d07a4
RG
122 do {
123 ssize_t got = read(fd, (char *)buffer + pos, len - pos);
124 if (got > 0) {
125 pos += (size_t) got;
126 }
127 else if (got == 0) {
128 throw runtime_error("EOF while reading message");
129 }
130 else {
131 if (errno == EAGAIN) {
9396d955 132 int res = waitForData(fd, (totalTimeout == 0 || idleTimeout <= remainingTime) ? idleTimeout : remainingTime);
3f6d07a4
RG
133 if (res > 0) {
134 /* there is data available */
135 }
136 else if (res == 0) {
137 throw runtime_error("Timeout while waiting for data to read");
138 } else {
139 throw runtime_error("Error while waiting for data to read");
140 }
141 }
142 else {
143 unixDie("failed in readn2WithTimeout");
144 }
145 }
9396d955
RG
146
147 if (totalTimeout) {
148 time_t now = time(NULL);
149 int elapsed = now - start;
150 if (elapsed >= remainingTime) {
151 throw runtime_error("Timeout while reading data");
152 }
153 start = now;
154 remainingTime -= elapsed;
155 }
3f6d07a4
RG
156 }
157 while (pos < len);
158
159 return len;
160}
161
a683e8bd 162size_t writen2WithTimeout(int fd, const void * buffer, size_t len, int timeout)
3f6d07a4
RG
163{
164 size_t pos = 0;
165 do {
166 ssize_t written = write(fd, (char *)buffer + pos, len - pos);
167
168 if (written > 0) {
169 pos += (size_t) written;
170 }
171 else if (written == 0)
172 throw runtime_error("EOF while writing message");
173 else {
174 if (errno == EAGAIN) {
175 int res = waitForRWData(fd, false, timeout, 0);
176 if (res > 0) {
177 /* there is room available */
178 }
179 else if (res == 0) {
180 throw runtime_error("Timeout while waiting to write data");
181 } else {
182 throw runtime_error("Error while waiting for room to write data");
183 }
184 }
185 else {
186 unixDie("failed in write2WithTimeout");
187 }
188 }
189 }
190 while (pos < len);
191
192 return len;
193}
12c86877 194
cc3afe25
BH
195string nowTime()
196{
74ab661c 197 time_t now = time(nullptr);
f0dbdd62
OM
198 struct tm tm;
199 localtime_r(&now, &tm);
74ab661c
CH
200 char buffer[30];
201 // YYYY-mm-dd HH:MM:SS TZOFF
f0dbdd62 202 strftime(buffer, sizeof(buffer), "%F %T %z", &tm);
74ab661c 203 buffer[sizeof(buffer)-1] = '\0';
bfbf6814 204 return string(buffer);
cc3afe25 205}
12c86877 206
092f210a 207uint16_t getShort(const unsigned char *p)
0d8612f2
BH
208{
209 return p[0] * 256 + p[1];
210}
211
212
092f210a 213uint16_t getShort(const char *p)
0d8612f2
BH
214{
215 return getShort((const unsigned char *)p);
216}
217
092f210a 218uint32_t getLong(const unsigned char* p)
b636533b
BH
219{
220 return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3];
221}
222
092f210a 223uint32_t getLong(const char* p)
b636533b
BH
224{
225 return getLong((unsigned char *)p);
226}
227
a683e8bd 228static bool ciEqual(const string& a, const string& b)
49bd5a20
BH
229{
230 if(a.size()!=b.size())
231 return false;
232
233 string::size_type pos=0, epos=a.size();
234 for(;pos < epos; ++pos)
235 if(dns_tolower(a[pos])!=dns_tolower(b[pos]))
236 return false;
237 return true;
238}
239
728485ca 240/** does domain end on suffix? Is smart about "wwwds9a.nl" "ds9a.nl" not matching */
a683e8bd 241static bool endsOn(const string &domain, const string &suffix)
728485ca 242{
49bd5a20 243 if( suffix.empty() || ciEqual(domain, suffix) )
728485ca 244 return true;
7738a23f 245
728485ca
BH
246 if(domain.size()<=suffix.size())
247 return false;
3ddb9247 248
49bd5a20 249 string::size_type dpos=domain.size()-suffix.size()-1, spos=0;
7738a23f 250
49bd5a20
BH
251 if(domain[dpos++]!='.')
252 return false;
728485ca 253
49bd5a20
BH
254 for(; dpos < domain.size(); ++dpos, ++spos)
255 if(dns_tolower(domain[dpos]) != dns_tolower(suffix[spos]))
256 return false;
257
258 return true;
259}
f2c11a48 260
a683e8bd
RG
261/** strips a domain suffix from a domain, returns true if it stripped */
262bool stripDomainSuffix(string *qname, const string &domain)
263{
264 if(!endsOn(*qname, domain))
265 return false;
266
267 if(toLower(*qname)==toLower(domain))
268 *qname="@";
269 else {
270 if((*qname)[qname->size()-domain.size()-1]!='.')
271 return false;
272
273 qname->resize(qname->size()-domain.size()-1);
274 }
275 return true;
276}
277
32252594 278static void parseService4(const string &descr, ServiceTuple &st)
12c86877
BH
279{
280 vector<string>parts;
281 stringtok(parts,descr,":");
52936200 282 if(parts.empty())
3f81d239 283 throw PDNSException("Unable to parse '"+descr+"' as a service");
12c86877
BH
284 st.host=parts[0];
285 if(parts.size()>1)
335da0ba 286 st.port=pdns_stou(parts[1]);
12c86877
BH
287}
288
32252594
BH
289static void parseService6(const string &descr, ServiceTuple &st)
290{
291 string::size_type pos=descr.find(']');
292 if(pos == string::npos)
3f81d239 293 throw PDNSException("Unable to parse '"+descr+"' as an IPv6 service");
32252594
BH
294
295 st.host=descr.substr(1, pos-1);
296 if(pos + 2 < descr.length())
335da0ba 297 st.port=pdns_stou(descr.substr(pos+2));
32252594
BH
298}
299
300
301void parseService(const string &descr, ServiceTuple &st)
302{
303 if(descr.empty())
3f81d239 304 throw PDNSException("Unable to parse '"+descr+"' as a service");
32252594
BH
305
306 vector<string> parts;
307 stringtok(parts, descr, ":");
308
309 if(descr[0]=='[') {
310 parseService6(descr, st);
311 }
312 else if(descr[0]==':' || parts.size() > 2 || descr.find("::") != string::npos) {
313 st.host=descr;
314 }
315 else {
316 parseService4(descr, st);
317 }
318}
12c86877 319
1fb3f0fc 320// returns -1 in case if error, 0 if no data is available, 1 if there is. In the first two cases, errno is set
a7d50153 321int waitForData(int fd, int seconds, int useconds)
649a88df
BH
322{
323 return waitForRWData(fd, true, seconds, useconds);
324}
325
51959320 326int waitForRWData(int fd, bool waitForRead, int seconds, int useconds, bool* error, bool* disconnected)
12c86877 327{
1258abe0
BH
328 int ret;
329
fab091b9
BH
330 struct pollfd pfd;
331 memset(&pfd, 0, sizeof(pfd));
332 pfd.fd = fd;
3ddb9247 333
649a88df 334 if(waitForRead)
fab091b9 335 pfd.events=POLLIN;
649a88df 336 else
fab091b9 337 pfd.events=POLLOUT;
1258abe0 338
6b3d4330 339 ret = poll(&pfd, 1, seconds * 1000 + useconds/1000);
e07c3801 340 if (ret > 0) {
51959320
RG
341 if (error && (pfd.revents & POLLERR)) {
342 *error = true;
343 }
344 if (disconnected && (pfd.revents & POLLHUP)) {
345 *disconnected = true;
346 }
347 }
1258abe0 348
12c86877
BH
349 return ret;
350}
351
a71bee29 352// returns -1 in case of error, 0 if no data is available, 1 if there is. In the first two cases, errno is set
dc058f65 353int waitForMultiData(const set<int>& fds, const int seconds, const int useconds, int* fdOut) {
d529011f
PL
354 set<int> realFDs;
355 for (const auto& fd : fds) {
356 if (fd >= 0 && realFDs.count(fd) == 0) {
357 realFDs.insert(fd);
358 }
359 }
360
dcc0e65d 361 std::vector<struct pollfd> pfds(realFDs.size());
c2a16005 362 memset(pfds.data(), 0, realFDs.size()*sizeof(struct pollfd));
d529011f
PL
363 int ctr = 0;
364 for (const auto& fd : realFDs) {
365 pfds[ctr].fd = fd;
366 pfds[ctr].events = POLLIN;
367 ctr++;
368 }
369
370 int ret;
371 if(seconds >= 0)
c2a16005 372 ret = poll(pfds.data(), realFDs.size(), seconds * 1000 + useconds/1000);
d529011f 373 else
c2a16005 374 ret = poll(pfds.data(), realFDs.size(), -1);
d529011f
PL
375 if(ret <= 0)
376 return ret;
377
378 set<int> pollinFDs;
aca9c605
PL
379 for (const auto& pfd : pfds) {
380 if (pfd.revents & POLLIN) {
381 pollinFDs.insert(pfd.fd);
d529011f 382 }
d529011f
PL
383 }
384 set<int>::const_iterator it(pollinFDs.begin());
385 advance(it, random() % pollinFDs.size());
dc058f65 386 *fdOut = *it;
d529011f
PL
387 return 1;
388}
389
a71bee29 390// returns -1 in case of error, 0 if no data is available, 1 if there is. In the first two cases, errno is set
f4ff5929
BH
391int waitFor2Data(int fd1, int fd2, int seconds, int useconds, int*fd)
392{
393 int ret;
394
395 struct pollfd pfds[2];
396 memset(&pfds[0], 0, 2*sizeof(struct pollfd));
397 pfds[0].fd = fd1;
398 pfds[1].fd = fd2;
3ddb9247 399
f4ff5929
BH
400 pfds[0].events= pfds[1].events = POLLIN;
401
402 int nsocks = 1 + (fd2 >= 0); // fd2 can optionally be -1
403
404 if(seconds >= 0)
405 ret = poll(pfds, nsocks, seconds * 1000 + useconds/1000);
406 else
407 ret = poll(pfds, nsocks, -1);
408 if(!ret || ret < 0)
409 return ret;
3ddb9247 410
f4ff5929
BH
411 if((pfds[0].revents & POLLIN) && !(pfds[1].revents & POLLIN))
412 *fd = pfds[0].fd;
413 else if((pfds[1].revents & POLLIN) && !(pfds[0].revents & POLLIN))
414 *fd = pfds[1].fd;
415 else if(ret == 2) {
416 *fd = pfds[random()%2].fd;
417 }
418 else
419 *fd = -1; // should never happen
3ddb9247 420
f4ff5929
BH
421 return 1;
422}
423
12c86877
BH
424
425string humanDuration(time_t passed)
426{
427 ostringstream ret;
428 if(passed<60)
429 ret<<passed<<" seconds";
430 else if(passed<3600)
9e04108d 431 ret<<std::setprecision(2)<<passed/60.0<<" minutes";
12c86877 432 else if(passed<86400)
9e04108d 433 ret<<std::setprecision(3)<<passed/3600.0<<" hours";
12c86877 434 else if(passed<(86400*30.41))
9e04108d 435 ret<<std::setprecision(3)<<passed/86400.0<<" days";
12c86877 436 else
9e04108d 437 ret<<std::setprecision(3)<<passed/(86400*30.41)<<" months";
12c86877
BH
438
439 return ret.str();
440}
441
442DTime::DTime()
443{
eefd15f9 444// set(); // saves lots of gettimeofday calls
55b6512d 445 d_set.tv_sec=d_set.tv_usec=0;
12c86877
BH
446}
447
12c86877
BH
448time_t DTime::time()
449{
450 return d_set.tv_sec;
451}
452
1d329048
BH
453const string unquotify(const string &item)
454{
455 if(item.size()<2)
456 return item;
457
458 string::size_type bpos=0, epos=item.size();
12c86877 459
3ddb9247 460 if(item[0]=='"')
1d329048 461 bpos=1;
c4bee46c 462
1d329048
BH
463 if(item[epos-1]=='"')
464 epos-=1;
465
c4bee46c 466 return item.substr(bpos,epos-bpos);
1d329048 467}
12c86877
BH
468
469void stripLine(string &line)
470{
bdf40704 471 string::size_type pos=line.find_first_of("\r\n");
12c86877
BH
472 if(pos!=string::npos) {
473 line.resize(pos);
474 }
475}
476
477string urlEncode(const string &text)
478{
479 string ret;
480 for(string::const_iterator i=text.begin();i!=text.end();++i)
481 if(*i==' ')ret.append("%20");
482 else ret.append(1,*i);
483 return ret;
484}
485
486string getHostname()
487{
0db70140 488#ifndef MAXHOSTNAMELEN
76473b92 489#define MAXHOSTNAMELEN 255
0db70140 490#endif
ac2bb9e7 491
12c86877
BH
492 char tmp[MAXHOSTNAMELEN];
493 if(gethostname(tmp, MAXHOSTNAMELEN))
494 return "UNKNOWN";
495
bfbf6814 496 return string(tmp);
12c86877
BH
497}
498
499string itoa(int i)
500{
501 ostringstream o;
502 o<<i;
503 return o.str();
504}
505
22c9c86a
BH
506string uitoa(unsigned int i) // MSVC 6 doesn't grok overloading (un)signed
507{
508 ostringstream o;
509 o<<i;
510 return o.str();
511}
512
d88babea
KM
513string bitFlip(const string &str)
514{
515 string::size_type pos=0, epos=str.size();
516 string ret;
517 ret.reserve(epos);
518 for(;pos < epos; ++pos)
519 ret.append(1, ~str[pos]);
520 return ret;
521}
22c9c86a 522
a2a81d42 523string stringerror(int err)
12c86877 524{
a2a81d42 525 return strerror(err);
12c86877
BH
526}
527
a2a81d42 528string stringerror()
d3b4137e 529{
a2a81d42 530 return strerror(errno);
d3b4137e 531}
d3b4137e 532
12c86877
BH
533void cleanSlashes(string &str)
534{
535 string::const_iterator i;
536 string out;
537 for(i=str.begin();i!=str.end();++i) {
538 if(*i=='/' && i!=str.begin() && *(i-1)=='/')
539 continue;
540 out.append(1,*i);
541 }
542 str=out;
543}
544
7b35aa49 545
092f210a 546bool IpToU32(const string &str, uint32_t *ip)
525b8a7c 547{
4cf26303
BH
548 if(str.empty()) {
549 *ip=0;
550 return true;
551 }
3ddb9247 552
092c9cc4 553 struct in_addr inp;
3897b9e1 554 if(inet_aton(str.c_str(), &inp)) {
092c9cc4
BH
555 *ip=inp.s_addr;
556 return true;
557 }
558 return false;
525b8a7c
BH
559}
560
5730f30c
BH
561string U32ToIP(uint32_t val)
562{
563 char tmp[17];
9b2244e1 564 snprintf(tmp, sizeof(tmp), "%u.%u.%u.%u",
4957a608
BH
565 (val >> 24)&0xff,
566 (val >> 16)&0xff,
567 (val >> 8)&0xff,
568 (val )&0xff);
bfbf6814 569 return string(tmp);
5730f30c
BH
570}
571
37d3f960 572
2db9c30e
BH
573string makeHexDump(const string& str)
574{
575 char tmp[5];
576 string ret;
ea634573 577 ret.reserve((int)(str.size()*2.2));
2db9c30e
BH
578
579 for(string::size_type n=0;n<str.size();++n) {
385b86f6 580 snprintf(tmp, sizeof(tmp), "%02x ", (unsigned char)str[n]);
2db9c30e
BH
581 ret+=tmp;
582 }
583 return ret;
584}
585
88358c9b
BH
586void normalizeTV(struct timeval& tv)
587{
588 if(tv.tv_usec > 1000000) {
589 ++tv.tv_sec;
590 tv.tv_usec-=1000000;
591 }
592 else if(tv.tv_usec < 0) {
593 --tv.tv_sec;
594 tv.tv_usec+=1000000;
595 }
596}
597
598const struct timeval operator+(const struct timeval& lhs, const struct timeval& rhs)
599{
600 struct timeval ret;
601 ret.tv_sec=lhs.tv_sec + rhs.tv_sec;
602 ret.tv_usec=lhs.tv_usec + rhs.tv_usec;
603 normalizeTV(ret);
604 return ret;
605}
606
607const struct timeval operator-(const struct timeval& lhs, const struct timeval& rhs)
608{
609 struct timeval ret;
610 ret.tv_sec=lhs.tv_sec - rhs.tv_sec;
611 ret.tv_usec=lhs.tv_usec - rhs.tv_usec;
612 normalizeTV(ret);
613 return ret;
614}
50c79a76
BH
615
616pair<string, string> splitField(const string& inp, char sepa)
617{
618 pair<string, string> ret;
619 string::size_type cpos=inp.find(sepa);
620 if(cpos==string::npos)
621 ret.first=inp;
622 else {
623 ret.first=inp.substr(0, cpos);
624 ret.second=inp.substr(cpos+1);
625 }
626 return ret;
627}
6e2514e4 628
f8499e52 629int logFacilityToLOG(unsigned int facility)
6e2514e4 630{
6e2514e4
BH
631 switch(facility) {
632 case 0:
633 return LOG_LOCAL0;
634 case 1:
635 return(LOG_LOCAL1);
636 case 2:
637 return(LOG_LOCAL2);
638 case 3:
639 return(LOG_LOCAL3);
640 case 4:
641 return(LOG_LOCAL4);
642 case 5:
643 return(LOG_LOCAL5);
644 case 6:
645 return(LOG_LOCAL6);
646 case 7:
647 return(LOG_LOCAL7);
648 default:
f8499e52 649 return -1;
6e2514e4
BH
650 }
651}
da042e6e
BH
652
653string stripDot(const string& dom)
654{
655 if(dom.empty())
656 return dom;
657
658 if(dom[dom.size()-1]!='.')
659 return dom;
660
661 return dom.substr(0,dom.size()-1);
662}
4dadd22f
BH
663
664
f71bc087
BH
665
666int makeIPv6sockaddr(const std::string& addr, struct sockaddr_in6* ret)
667{
85db02c5
BH
668 if(addr.empty())
669 return -1;
670 string ourAddr(addr);
6cbfa73b
RG
671 bool portSet = false;
672 unsigned int port;
85db02c5
BH
673 if(addr[0]=='[') { // [::]:53 style address
674 string::size_type pos = addr.find(']');
0047d734 675 if(pos == string::npos)
85db02c5
BH
676 return -1;
677 ourAddr.assign(addr.c_str() + 1, pos-1);
ed2ff96e 678 if (pos + 1 != addr.size()) { // complete after ], no port specified
0047d734
CH
679 if (pos + 2 > addr.size() || addr[pos+1]!=':')
680 return -1;
681 try {
682 port = pdns_stou(addr.substr(pos+2));
683 portSet = true;
684 }
d38e2ba9 685 catch(const std::out_of_range&) {
0047d734
CH
686 return -1;
687 }
5b4ed369 688 }
85db02c5 689 }
39d2d9b2 690 ret->sin6_scope_id=0;
691 ret->sin6_family=AF_INET6;
692
0c9de4fc 693 if(inet_pton(AF_INET6, ourAddr.c_str(), (void*)&ret->sin6_addr) != 1) {
694 struct addrinfo* res;
695 struct addrinfo hints;
696 memset(&hints, 0, sizeof(hints));
3ddb9247 697
0c9de4fc 698 hints.ai_family = AF_INET6;
699 hints.ai_flags = AI_NUMERICHOST;
3ddb9247 700
1746e9bb 701 // getaddrinfo has anomalous return codes, anything nonzero is an error, positive or negative
a5d2c081 702 if (getaddrinfo(ourAddr.c_str(), 0, &hints, &res) != 0) {
0c9de4fc 703 return -1;
704 }
3ddb9247 705
0c9de4fc 706 memcpy(ret, res->ai_addr, res->ai_addrlen);
707 freeaddrinfo(res);
f71bc087 708 }
0c9de4fc 709
6cbfa73b
RG
710 if(portSet) {
711 if(port > 65535)
712 return -1;
5b4ed369 713
85db02c5 714 ret->sin6_port = htons(port);
6cbfa73b 715 }
0c9de4fc 716
f71bc087
BH
717 return 0;
718}
834942f1 719
76cb4593 720int makeIPv4sockaddr(const std::string& str, struct sockaddr_in* ret)
85db02c5
BH
721{
722 if(str.empty()) {
723 return -1;
724 }
725 struct in_addr inp;
3ddb9247 726
85db02c5
BH
727 string::size_type pos = str.find(':');
728 if(pos == string::npos) { // no port specified, not touching the port
3897b9e1 729 if(inet_aton(str.c_str(), &inp)) {
85db02c5
BH
730 ret->sin_addr.s_addr=inp.s_addr;
731 return 0;
732 }
733 return -1;
734 }
735 if(!*(str.c_str() + pos + 1)) // trailing :
3ddb9247
PD
736 return -1;
737
85db02c5
BH
738 char *eptr = (char*)str.c_str() + str.size();
739 int port = strtol(str.c_str() + pos + 1, &eptr, 10);
5b4ed369
PL
740 if (port < 0 || port > 65535)
741 return -1;
742
85db02c5
BH
743 if(*eptr)
744 return -1;
3ddb9247 745
85db02c5 746 ret->sin_port = htons(port);
3897b9e1 747 if(inet_aton(str.substr(0, pos).c_str(), &inp)) {
85db02c5
BH
748 ret->sin_addr.s_addr=inp.s_addr;
749 return 0;
750 }
751 return -1;
752}
753
76cb4593
CH
754int makeUNsockaddr(const std::string& path, struct sockaddr_un* ret)
755{
756 if (path.empty())
757 return -1;
758
759 memset(ret, 0, sizeof(struct sockaddr_un));
760 ret->sun_family = AF_UNIX;
761 if (path.length() >= sizeof(ret->sun_path))
762 return -1;
763
764 path.copy(ret->sun_path, sizeof(ret->sun_path), 0);
765 return 0;
766}
85db02c5 767
834942f1
BH
768//! read a line of text from a FILE* to a std::string, returns false on 'no data'
769bool stringfgets(FILE* fp, std::string& line)
770{
771 char buffer[1024];
772 line.clear();
3ddb9247 773
834942f1
BH
774 do {
775 if(!fgets(buffer, sizeof(buffer), fp))
776 return !line.empty();
3ddb9247
PD
777
778 line.append(buffer);
834942f1
BH
779 } while(!strchr(buffer, '\n'));
780 return true;
781}
e611a06c 782
4e9a20e6 783bool readFileIfThere(const char* fname, std::string* line)
784{
785 line->clear();
5e1f23ca 786 auto fp = std::unique_ptr<FILE, int(*)(FILE*)>(fopen(fname, "r"), fclose);
4e9a20e6 787 if(!fp)
788 return false;
5e1f23ca
RG
789 stringfgets(fp.get(), *line);
790 fp.reset();
791
4e9a20e6 792 return true;
793}
794
3ee84c3f
BH
795Regex::Regex(const string &expr)
796{
797 if(regcomp(&d_preg, expr.c_str(), REG_ICASE|REG_NOSUB|REG_EXTENDED))
3f81d239 798 throw PDNSException("Regular expression did not compile");
3ee84c3f 799}
65d8e171 800
25ba7344
PD
801// if you end up here because valgrind told you were are doing something wrong
802// with msgh->msg_controllen, please refer to https://github.com/PowerDNS/pdns/pull/3962
803// first.
7bec330a 804// Note that cmsgbuf should be aligned the same as a struct cmsghdr
7bec330a 805void addCMsgSrcAddr(struct msghdr* msgh, cmsgbuf_aligned* cmsgbuf, const ComboAddress* source, int itfIndex)
65d8e171 806{
ecc8571f 807 struct cmsghdr *cmsg = NULL;
65d8e171
KN
808
809 if(source->sin4.sin_family == AF_INET6) {
810 struct in6_pktinfo *pkt;
811
812 msgh->msg_control = cmsgbuf;
aeb011b7
RG
813#if !defined( __APPLE__ )
814 /* CMSG_SPACE is not a constexpr on macOS */
7f818542 815 static_assert(CMSG_SPACE(sizeof(*pkt)) <= sizeof(*cmsgbuf), "Buffer is too small for in6_pktinfo");
aeb011b7
RG
816#else /* __APPLE__ */
817 if (CMSG_SPACE(sizeof(*pkt)) > sizeof(*cmsgbuf)) {
818 throw std::runtime_error("Buffer is too small for in6_pktinfo");
819 }
820#endif /* __APPLE__ */
65d8e171
KN
821 msgh->msg_controllen = CMSG_SPACE(sizeof(*pkt));
822
823 cmsg = CMSG_FIRSTHDR(msgh);
824 cmsg->cmsg_level = IPPROTO_IPV6;
825 cmsg->cmsg_type = IPV6_PKTINFO;
826 cmsg->cmsg_len = CMSG_LEN(sizeof(*pkt));
827
828 pkt = (struct in6_pktinfo *) CMSG_DATA(cmsg);
20b22895
OM
829 // Include the padding to stop valgrind complaining about passing uninitialized data
830 memset(pkt, 0, CMSG_SPACE(sizeof(*pkt)));
65d8e171 831 pkt->ipi6_addr = source->sin6.sin6_addr;
fbe2a2e0 832 pkt->ipi6_ifindex = itfIndex;
65d8e171
KN
833 }
834 else {
4d39d7f3 835#if defined(IP_PKTINFO)
65d8e171
KN
836 struct in_pktinfo *pkt;
837
838 msgh->msg_control = cmsgbuf;
aeb011b7
RG
839#if !defined( __APPLE__ )
840 /* CMSG_SPACE is not a constexpr on macOS */
7f818542 841 static_assert(CMSG_SPACE(sizeof(*pkt)) <= sizeof(*cmsgbuf), "Buffer is too small for in_pktinfo");
aeb011b7
RG
842#else /* __APPLE__ */
843 if (CMSG_SPACE(sizeof(*pkt)) > sizeof(*cmsgbuf)) {
844 throw std::runtime_error("Buffer is too small for in_pktinfo");
845 }
846#endif /* __APPLE__ */
65d8e171
KN
847 msgh->msg_controllen = CMSG_SPACE(sizeof(*pkt));
848
849 cmsg = CMSG_FIRSTHDR(msgh);
850 cmsg->cmsg_level = IPPROTO_IP;
851 cmsg->cmsg_type = IP_PKTINFO;
852 cmsg->cmsg_len = CMSG_LEN(sizeof(*pkt));
853
854 pkt = (struct in_pktinfo *) CMSG_DATA(cmsg);
20b22895
OM
855 // Include the padding to stop valgrind complaining about passing uninitialized data
856 memset(pkt, 0, CMSG_SPACE(sizeof(*pkt)));
65d8e171 857 pkt->ipi_spec_dst = source->sin4.sin_addr;
fbe2a2e0 858 pkt->ipi_ifindex = itfIndex;
4d39d7f3 859#elif defined(IP_SENDSRCADDR)
65d8e171
KN
860 struct in_addr *in;
861
862 msgh->msg_control = cmsgbuf;
aeb011b7 863#if !defined( __APPLE__ )
7f818542 864 static_assert(CMSG_SPACE(sizeof(*in)) <= sizeof(*cmsgbuf), "Buffer is too small for in_addr");
aeb011b7
RG
865#else /* __APPLE__ */
866 if (CMSG_SPACE(sizeof(*in)) > sizeof(*cmsgbuf)) {
867 throw std::runtime_error("Buffer is too small for in_addr");
868 }
869#endif /* __APPLE__ */
65d8e171
KN
870 msgh->msg_controllen = CMSG_SPACE(sizeof(*in));
871
872 cmsg = CMSG_FIRSTHDR(msgh);
873 cmsg->cmsg_level = IPPROTO_IP;
874 cmsg->cmsg_type = IP_SENDSRCADDR;
875 cmsg->cmsg_len = CMSG_LEN(sizeof(*in));
876
20b22895 877 // Include the padding to stop valgrind complaining about passing uninitialized data
65d8e171 878 in = (struct in_addr *) CMSG_DATA(cmsg);
20b22895 879 memset(in, 0, CMSG_SPACE(sizeof(*in)));
65d8e171 880 *in = source->sin4.sin_addr;
ecc8571f 881#endif
65d8e171
KN
882 }
883}
3a8a4d68 884
885unsigned int getFilenumLimit(bool hardOrSoft)
886{
887 struct rlimit rlim;
888 if(getrlimit(RLIMIT_NOFILE, &rlim) < 0)
889 unixDie("Requesting number of available file descriptors");
890 return hardOrSoft ? rlim.rlim_max : rlim.rlim_cur;
891}
892
893void setFilenumLimit(unsigned int lim)
894{
895 struct rlimit rlim;
896
897 if(getrlimit(RLIMIT_NOFILE, &rlim) < 0)
898 unixDie("Requesting number of available file descriptors");
899 rlim.rlim_cur=lim;
900 if(setrlimit(RLIMIT_NOFILE, &rlim) < 0)
901 unixDie("Setting number of available file descriptors");
902}
06ea9015 903
904#define burtlemix(a,b,c) \
905{ \
906 a -= b; a -= c; a ^= (c>>13); \
907 b -= c; b -= a; b ^= (a<<8); \
908 c -= a; c -= b; c ^= (b>>13); \
909 a -= b; a -= c; a ^= (c>>12); \
910 b -= c; b -= a; b ^= (a<<16); \
911 c -= a; c -= b; c ^= (b>>5); \
912 a -= b; a -= c; a ^= (c>>3); \
913 b -= c; b -= a; b ^= (a<<10); \
914 c -= a; c -= b; c ^= (b>>15); \
915}
916
917uint32_t burtle(const unsigned char* k, uint32_t length, uint32_t initval)
918{
919 uint32_t a,b,c,len;
920
921 /* Set up the internal state */
922 len = length;
923 a = b = 0x9e3779b9; /* the golden ratio; an arbitrary value */
924 c = initval; /* the previous hash value */
925
926 /*---------------------------------------- handle most of the key */
927 while (len >= 12) {
928 a += (k[0] +((uint32_t)k[1]<<8) +((uint32_t)k[2]<<16) +((uint32_t)k[3]<<24));
929 b += (k[4] +((uint32_t)k[5]<<8) +((uint32_t)k[6]<<16) +((uint32_t)k[7]<<24));
930 c += (k[8] +((uint32_t)k[9]<<8) +((uint32_t)k[10]<<16)+((uint32_t)k[11]<<24));
931 burtlemix(a,b,c);
932 k += 12; len -= 12;
933 }
934
935 /*------------------------------------- handle the last 11 bytes */
936 c += length;
937 switch(len) { /* all the case statements fall through */
938 case 11: c+=((uint32_t)k[10]<<24);
d2fe6b5e 939 /* fall-through */
06ea9015 940 case 10: c+=((uint32_t)k[9]<<16);
d2fe6b5e 941 /* fall-through */
06ea9015 942 case 9 : c+=((uint32_t)k[8]<<8);
943 /* the first byte of c is reserved for the length */
d2fe6b5e 944 /* fall-through */
06ea9015 945 case 8 : b+=((uint32_t)k[7]<<24);
d2fe6b5e 946 /* fall-through */
06ea9015 947 case 7 : b+=((uint32_t)k[6]<<16);
d2fe6b5e 948 /* fall-through */
06ea9015 949 case 6 : b+=((uint32_t)k[5]<<8);
d2fe6b5e 950 /* fall-through */
06ea9015 951 case 5 : b+=k[4];
d2fe6b5e 952 /* fall-through */
06ea9015 953 case 4 : a+=((uint32_t)k[3]<<24);
d2fe6b5e 954 /* fall-through */
06ea9015 955 case 3 : a+=((uint32_t)k[2]<<16);
d2fe6b5e 956 /* fall-through */
06ea9015 957 case 2 : a+=((uint32_t)k[1]<<8);
d2fe6b5e 958 /* fall-through */
06ea9015 959 case 1 : a+=k[0];
960 /* case 0: nothing left to add */
961 }
962 burtlemix(a,b,c);
963 /*-------------------------------------------- report the result */
964 return c;
965}
9ae194e2 966
6200227b 967uint32_t burtleCI(const unsigned char* k, uint32_t length, uint32_t initval)
968{
969 uint32_t a,b,c,len;
970
971 /* Set up the internal state */
972 len = length;
973 a = b = 0x9e3779b9; /* the golden ratio; an arbitrary value */
974 c = initval; /* the previous hash value */
975
976 /*---------------------------------------- handle most of the key */
977 while (len >= 12) {
af891b3d 978 a += (dns_tolower(k[0]) +((uint32_t)dns_tolower(k[1])<<8) +((uint32_t)dns_tolower(k[2])<<16) +((uint32_t)dns_tolower(k[3])<<24));
979 b += (dns_tolower(k[4]) +((uint32_t)dns_tolower(k[5])<<8) +((uint32_t)dns_tolower(k[6])<<16) +((uint32_t)dns_tolower(k[7])<<24));
980 c += (dns_tolower(k[8]) +((uint32_t)dns_tolower(k[9])<<8) +((uint32_t)dns_tolower(k[10])<<16)+((uint32_t)dns_tolower(k[11])<<24));
6200227b 981 burtlemix(a,b,c);
982 k += 12; len -= 12;
983 }
984
985 /*------------------------------------- handle the last 11 bytes */
986 c += length;
987 switch(len) { /* all the case statements fall through */
af891b3d 988 case 11: c+=((uint32_t)dns_tolower(k[10])<<24);
d2fe6b5e 989 /* fall-through */
af891b3d 990 case 10: c+=((uint32_t)dns_tolower(k[9])<<16);
d2fe6b5e 991 /* fall-through */
af891b3d 992 case 9 : c+=((uint32_t)dns_tolower(k[8])<<8);
6200227b 993 /* the first byte of c is reserved for the length */
d2fe6b5e 994 /* fall-through */
af891b3d 995 case 8 : b+=((uint32_t)dns_tolower(k[7])<<24);
d2fe6b5e 996 /* fall-through */
af891b3d 997 case 7 : b+=((uint32_t)dns_tolower(k[6])<<16);
d2fe6b5e 998 /* fall-through */
af891b3d 999 case 6 : b+=((uint32_t)dns_tolower(k[5])<<8);
d2fe6b5e 1000 /* fall-through */
af891b3d 1001 case 5 : b+=dns_tolower(k[4]);
d2fe6b5e 1002 /* fall-through */
af891b3d 1003 case 4 : a+=((uint32_t)dns_tolower(k[3])<<24);
d2fe6b5e 1004 /* fall-through */
af891b3d 1005 case 3 : a+=((uint32_t)dns_tolower(k[2])<<16);
d2fe6b5e 1006 /* fall-through */
af891b3d 1007 case 2 : a+=((uint32_t)dns_tolower(k[1])<<8);
d2fe6b5e 1008 /* fall-through */
af891b3d 1009 case 1 : a+=dns_tolower(k[0]);
6200227b 1010 /* case 0: nothing left to add */
1011 }
1012 burtlemix(a,b,c);
1013 /*-------------------------------------------- report the result */
1014 return c;
1015}
1016
1017
915b0c39 1018bool setSocketTimestamps(int fd)
9ae194e2 1019{
eb4c1792 1020#ifdef SO_TIMESTAMP
9ae194e2 1021 int on=1;
915b0c39 1022 return setsockopt(fd, SOL_SOCKET, SO_TIMESTAMP, (char*)&on, sizeof(on)) == 0;
99be0a43 1023#else
915b0c39 1024 return true; // we pretend this happened.
99be0a43 1025#endif
9ae194e2 1026}
58044407 1027
883a30a7 1028bool setTCPNoDelay(int sock)
149d0144 1029{
1030 int flag = 1;
883a30a7
RG
1031 return setsockopt(sock, /* socket affected */
1032 IPPROTO_TCP, /* set option at TCP level */
1033 TCP_NODELAY, /* name of option */
1034 (char *) &flag, /* the cast is historical cruft */
1035 sizeof(flag)) == 0; /* length of option value */
149d0144 1036}
1037
1038
3897b9e1 1039bool setNonBlocking(int sock)
1040{
3ddb9247 1041 int flags=fcntl(sock,F_GETFL,0);
3897b9e1 1042 if(flags<0 || fcntl(sock, F_SETFL,flags|O_NONBLOCK) <0)
1043 return false;
1044 return true;
1045}
1046
1047bool setBlocking(int sock)
1048{
3ddb9247 1049 int flags=fcntl(sock,F_GETFL,0);
3897b9e1 1050 if(flags<0 || fcntl(sock, F_SETFL,flags&(~O_NONBLOCK)) <0)
1051 return false;
1052 return true;
1053}
1054
bf676f2f
PL
1055bool setReuseAddr(int sock)
1056{
1057 int tmp = 1;
1058 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&tmp, static_cast<unsigned>(sizeof tmp))<0)
04360367 1059 throw PDNSException(string("Setsockopt failed: ")+stringerror());
bf676f2f
PL
1060 return true;
1061}
1062
18861f97
RG
1063bool isNonBlocking(int sock)
1064{
1065 int flags=fcntl(sock,F_GETFL,0);
1066 return flags & O_NONBLOCK;
1067}
1068
29bb743c
OM
1069bool setReceiveSocketErrors(int sock, int af)
1070{
1071#ifdef __linux__
1072 int tmp = 1, ret;
1073 if (af == AF_INET) {
1074 ret = setsockopt(sock, IPPROTO_IP, IP_RECVERR, &tmp, sizeof(tmp));
1075 } else {
1076 ret = setsockopt(sock, IPPROTO_IPV6, IPV6_RECVERR, &tmp, sizeof(tmp));
1077 }
1078 if (ret < 0) {
04360367 1079 throw PDNSException(string("Setsockopt failed: ") + stringerror());
29bb743c
OM
1080 }
1081#endif
1082 return true;
1083}
1084
3897b9e1 1085// Closes a socket.
1086int closesocket( int socket )
1087{
1088 int ret=::close(socket);
1089 if(ret < 0 && errno == ECONNRESET) // see ticket 192, odd BSD behaviour
1090 return 0;
3ddb9247 1091 if(ret < 0)
3897b9e1 1092 throw PDNSException("Error closing socket: "+stringerror());
1093 return ret;
1094}
1095
1096bool setCloseOnExec(int sock)
1097{
3ddb9247 1098 int flags=fcntl(sock,F_GETFD,0);
3897b9e1 1099 if(flags<0 || fcntl(sock, F_SETFD,flags|FD_CLOEXEC) <0)
1100 return false;
1101 return true;
1102}
1103
6907f014 1104string getMACAddress(const ComboAddress& ca)
1105{
1106 string ret;
1107#ifdef __linux__
1108 ifstream ifs("/proc/net/arp");
1109 if(!ifs)
1110 return ret;
1111 string line;
1112 string match=ca.toString()+' ';
1113 while(getline(ifs, line)) {
1114 if(boost::starts_with(line, match)) {
1115 vector<string> parts;
1116 stringtok(parts, line, " \n\t\r");
1117 if(parts.size() < 4)
1118 return ret;
1119 unsigned int tmp[6];
1120 sscanf(parts[3].c_str(), "%02x:%02x:%02x:%02x:%02x:%02x", tmp, tmp+1, tmp+2, tmp+3, tmp+4, tmp+5);
1121 for(int i = 0 ; i< 6 ; ++i)
1122 ret.append(1, (char)tmp[i]);
1123 return ret;
1124 }
1125 }
1126#endif
1127 return ret;
1128}
1129
8290ad9f 1130uint64_t udpErrorStats(const std::string& str)
1131{
1132#ifdef __linux__
1133 ifstream ifs("/proc/net/snmp");
1134 if(!ifs)
1135 return 0;
1136 string line;
1137 vector<string> parts;
1138 while(getline(ifs,line)) {
1139 if(boost::starts_with(line, "Udp: ") && isdigit(line[5])) {
1140 stringtok(parts, line, " \n\t\r");
1141 if(parts.size() < 7)
1142 break;
1143 if(str=="udp-rcvbuf-errors")
335da0ba 1144 return std::stoull(parts[5]);
8290ad9f 1145 else if(str=="udp-sndbuf-errors")
335da0ba 1146 return std::stoull(parts[6]);
8290ad9f 1147 else if(str=="udp-noport-errors")
335da0ba 1148 return std::stoull(parts[2]);
8290ad9f 1149 else if(str=="udp-in-errors")
335da0ba 1150 return std::stoull(parts[3]);
8290ad9f 1151 else
1152 return 0;
1153 }
1154 }
1155#endif
1156 return 0;
1157}
da15912b 1158
591d1bd3
RG
1159uint64_t getCPUIOWait(const std::string& str)
1160{
1161#ifdef __linux__
1162 ifstream ifs("/proc/stat");
1163 if (!ifs) {
1164 return 0;
1165 }
1166
1167 string line;
1168 vector<string> parts;
1169 while (getline(ifs, line)) {
1170 if (boost::starts_with(line, "cpu ")) {
1171 stringtok(parts, line, " \n\t\r");
1172
1173 if (parts.size() < 6) {
1174 break;
1175 }
1176
1177 return std::stoull(parts[5]);
1178 }
1179 }
1180#endif
1181 return 0;
1182}
1183
1184uint64_t getCPUSteal(const std::string& str)
1185{
1186#ifdef __linux__
1187 ifstream ifs("/proc/stat");
1188 if (!ifs) {
1189 return 0;
1190 }
1191
1192 string line;
1193 vector<string> parts;
1194 while (getline(ifs, line)) {
1195 if (boost::starts_with(line, "cpu ")) {
1196 stringtok(parts, line, " \n\t\r");
1197
1198 if (parts.size() < 9) {
1199 break;
1200 }
1201
1202 return std::stoull(parts[8]);
1203 }
1204 }
1205#endif
1206 return 0;
1207}
1208
21a3792f 1209bool getTSIGHashEnum(const DNSName& algoName, TSIGHashEnum& algoEnum)
da15912b 1210{
2330c421 1211 if (algoName == DNSName("hmac-md5.sig-alg.reg.int") || algoName == DNSName("hmac-md5"))
da15912b 1212 algoEnum = TSIG_MD5;
2330c421 1213 else if (algoName == DNSName("hmac-sha1"))
da15912b 1214 algoEnum = TSIG_SHA1;
2330c421 1215 else if (algoName == DNSName("hmac-sha224"))
da15912b 1216 algoEnum = TSIG_SHA224;
2330c421 1217 else if (algoName == DNSName("hmac-sha256"))
da15912b 1218 algoEnum = TSIG_SHA256;
2330c421 1219 else if (algoName == DNSName("hmac-sha384"))
da15912b 1220 algoEnum = TSIG_SHA384;
2330c421 1221 else if (algoName == DNSName("hmac-sha512"))
da15912b 1222 algoEnum = TSIG_SHA512;
2330c421 1223 else if (algoName == DNSName("gss-tsig"))
bcb5b94e 1224 algoEnum = TSIG_GSS;
da15912b
AT
1225 else {
1226 return false;
1227 }
1228 return true;
1229}
bfd4efae 1230
21a3792f 1231DNSName getTSIGAlgoName(TSIGHashEnum& algoEnum)
bfd4efae
AT
1232{
1233 switch(algoEnum) {
8171ab83 1234 case TSIG_MD5: return DNSName("hmac-md5.sig-alg.reg.int.");
1235 case TSIG_SHA1: return DNSName("hmac-sha1.");
1236 case TSIG_SHA224: return DNSName("hmac-sha224.");
1237 case TSIG_SHA256: return DNSName("hmac-sha256.");
1238 case TSIG_SHA384: return DNSName("hmac-sha384.");
1239 case TSIG_SHA512: return DNSName("hmac-sha512.");
1240 case TSIG_GSS: return DNSName("gss-tsig.");
bfd4efae
AT
1241 }
1242 throw PDNSException("getTSIGAlgoName does not understand given algorithm, please fix!");
1243}
a1a787dc 1244
a9b6db56 1245uint64_t getOpenFileDescriptors(const std::string&)
1246{
1247#ifdef __linux__
1248 DIR* dirhdl=opendir(("/proc/"+std::to_string(getpid())+"/fd/").c_str());
1249 if(!dirhdl)
1250 return 0;
1251
1252 struct dirent *entry;
1253 int ret=0;
1254 while((entry = readdir(dirhdl))) {
335da0ba
AT
1255 uint32_t num;
1256 try {
1257 num = pdns_stou(entry->d_name);
1258 } catch (...) {
1259 continue; // was not a number.
1260 }
a9b6db56 1261 if(std::to_string(num) == entry->d_name)
1262 ret++;
1263 }
1264 closedir(dirhdl);
1265 return ret;
1266
1267#else
1268 return 0;
1269#endif
1270}
1271
a1a787dc 1272uint64_t getRealMemoryUsage(const std::string&)
1273{
330dcb5c 1274#ifdef __linux__
16101f83 1275 ifstream ifs("/proc/self/statm");
330dcb5c
OM
1276 if(!ifs)
1277 return 0;
1278
1279 uint64_t size, resident, shared, text, lib, data;
1280 ifs >> size >> resident >> shared >> text >> lib >> data;
1281
1282 return data * getpagesize();
1283#else
1284 struct rusage ru;
1285 if (getrusage(RUSAGE_SELF, &ru) != 0)
1286 return 0;
1287 return ru.ru_maxrss * 1024;
1288#endif
1289}
1290
1291
1292uint64_t getSpecialMemoryUsage(const std::string&)
1293{
a1a787dc 1294#ifdef __linux__
16101f83 1295 ifstream ifs("/proc/self/smaps");
a1a787dc 1296 if(!ifs)
1297 return 0;
1298 string line;
1299 uint64_t bytes=0;
1300 string header("Private_Dirty:");
1301 while(getline(ifs, line)) {
1302 if(boost::starts_with(line, header)) {
335da0ba 1303 bytes += std::stoull(line.substr(header.length() + 1))*1024;
a1a787dc 1304 }
1305 }
1306 return bytes;
1307#else
1308 return 0;
1309#endif
1310}
4f99f3d3
RG
1311
1312uint64_t getCPUTimeUser(const std::string&)
1313{
1314 struct rusage ru;
1315 getrusage(RUSAGE_SELF, &ru);
1316 return (ru.ru_utime.tv_sec*1000ULL + ru.ru_utime.tv_usec/1000);
1317}
1318
1319uint64_t getCPUTimeSystem(const std::string&)
1320{
1321 struct rusage ru;
1322 getrusage(RUSAGE_SELF, &ru);
1323 return (ru.ru_stime.tv_sec*1000ULL + ru.ru_stime.tv_usec/1000);
1324}
3fcaeeac 1325
1326double DiffTime(const struct timespec& first, const struct timespec& second)
1327{
1328 int seconds=second.tv_sec - first.tv_sec;
1329 int nseconds=second.tv_nsec - first.tv_nsec;
1330
1331 if(nseconds < 0) {
1332 seconds-=1;
1333 nseconds+=1000000000;
1334 }
1335 return seconds + nseconds/1000000000.0;
1336}
1337
1338double DiffTime(const struct timeval& first, const struct timeval& second)
1339{
1340 int seconds=second.tv_sec - first.tv_sec;
1341 int useconds=second.tv_usec - first.tv_usec;
1342
1343 if(useconds < 0) {
1344 seconds-=1;
1345 useconds+=1000000;
1346 }
1347 return seconds + useconds/1000000.0;
1348}
ffb07158 1349
ffb07158 1350uid_t strToUID(const string &str)
1351{
1352 uid_t result = 0;
1353 const char * cstr = str.c_str();
1354 struct passwd * pwd = getpwnam(cstr);
1355
1356 if (pwd == NULL) {
e805cba5 1357 long long val;
ffb07158 1358
e805cba5
RG
1359 try {
1360 val = stoll(str);
ffb07158 1361 }
e805cba5
RG
1362 catch(std::exception& e) {
1363 throw runtime_error((boost::format("Error: Unable to parse user ID %s") % cstr).str() );
1364 }
1365
1366 if (val < std::numeric_limits<uid_t>::min() || val > std::numeric_limits<uid_t>::max()) {
1367 throw runtime_error((boost::format("Error: Unable to parse user ID %s") % cstr).str() );
ffb07158 1368 }
e805cba5
RG
1369
1370 result = static_cast<uid_t>(val);
ffb07158 1371 }
1372 else {
1373 result = pwd->pw_uid;
1374 }
1375
1376 return result;
1377}
1378
1379gid_t strToGID(const string &str)
1380{
1381 gid_t result = 0;
1382 const char * cstr = str.c_str();
1383 struct group * grp = getgrnam(cstr);
1384
1385 if (grp == NULL) {
e805cba5 1386 long long val;
ffb07158 1387
e805cba5
RG
1388 try {
1389 val = stoll(str);
ffb07158 1390 }
e805cba5
RG
1391 catch(std::exception& e) {
1392 throw runtime_error((boost::format("Error: Unable to parse group ID %s") % cstr).str() );
1393 }
1394
1395 if (val < std::numeric_limits<gid_t>::min() || val > std::numeric_limits<gid_t>::max()) {
1396 throw runtime_error((boost::format("Error: Unable to parse group ID %s") % cstr).str() );
ffb07158 1397 }
e805cba5
RG
1398
1399 result = static_cast<gid_t>(val);
ffb07158 1400 }
1401 else {
1402 result = grp->gr_gid;
1403 }
1404
1405 return result;
1406}
1407
335da0ba 1408unsigned int pdns_stou(const std::string& str, size_t * idx, int base)
a5c4e4a6 1409{
00f45062 1410 if (str.empty()) return 0; // compatibility
2f975181
PD
1411 unsigned long result;
1412 try {
1413 result = std::stoul(str, idx, base);
1414 }
1415 catch(std::invalid_argument& e) {
1416 throw std::invalid_argument(string(e.what()) + "; (invalid argument during std::stoul); data was \""+str+"\"");
1417 }
cccfa59b
PD
1418 catch(std::out_of_range& e) {
1419 throw std::out_of_range(string(e.what()) + "; (out of range during std::stoul); data was \""+str+"\"");
1420 }
a5c4e4a6 1421 if (result > std::numeric_limits<unsigned int>::max()) {
cccfa59b 1422 throw std::out_of_range("stoul returned result out of unsigned int range; data was \""+str+"\"");
a5c4e4a6
AT
1423 }
1424 return static_cast<unsigned int>(result);
1425}
1426
8fd25133
RG
1427bool isSettingThreadCPUAffinitySupported()
1428{
1429#ifdef HAVE_PTHREAD_SETAFFINITY_NP
1430 return true;
1431#else
1432 return false;
1433#endif
1434}
1435
1436int mapThreadToCPUList(pthread_t tid, const std::set<int>& cpus)
1437{
1438#ifdef HAVE_PTHREAD_SETAFFINITY_NP
4d39d7f3
TIH
1439# ifdef __NetBSD__
1440 cpuset_t *cpuset;
1441 cpuset = cpuset_create();
1442 for (const auto cpuID : cpus) {
1443 cpuset_set(cpuID, cpuset);
1444 }
1445
1446 return pthread_setaffinity_np(tid,
1447 cpuset_size(cpuset),
1448 cpuset);
1449# else
1450# ifdef __FreeBSD__
1451# define cpu_set_t cpuset_t
1452# endif
8fd25133
RG
1453 cpu_set_t cpuset;
1454 CPU_ZERO(&cpuset);
1455 for (const auto cpuID : cpus) {
1456 CPU_SET(cpuID, &cpuset);
1457 }
1458
1459 return pthread_setaffinity_np(tid,
1460 sizeof(cpuset),
1461 &cpuset);
4d39d7f3 1462# endif
99be0a43 1463#else
8fd25133 1464 return ENOSYS;
99be0a43 1465#endif /* HAVE_PTHREAD_SETAFFINITY_NP */
8fd25133 1466}
5d4e1ef8
RG
1467
1468std::vector<ComboAddress> getResolvers(const std::string& resolvConfPath)
1469{
1470 std::vector<ComboAddress> results;
1471
1472 ifstream ifs(resolvConfPath);
1473 if (!ifs) {
1474 return results;
1475 }
1476
1477 string line;
1478 while(std::getline(ifs, line)) {
1479 boost::trim_right_if(line, is_any_of(" \r\n\x1a"));
1480 boost::trim_left(line); // leading spaces, let's be nice
1481
1482 string::size_type tpos = line.find_first_of(";#");
1483 if (tpos != string::npos) {
1484 line.resize(tpos);
1485 }
1486
1487 if (boost::starts_with(line, "nameserver ") || boost::starts_with(line, "nameserver\t")) {
1488 vector<string> parts;
1489 stringtok(parts, line, " \t,"); // be REALLY nice
1490 for(vector<string>::const_iterator iter = parts.begin() + 1; iter != parts.end(); ++iter) {
1491 try {
1492 results.emplace_back(*iter, 53);
1493 }
1494 catch(...)
1495 {
1496 }
1497 }
1498 }
1499 }
1500
1501 return results;
1502}
ee271fc4
RG
1503
1504size_t getPipeBufferSize(int fd)
1505{
1506#ifdef F_GETPIPE_SZ
1507 int res = fcntl(fd, F_GETPIPE_SZ);
1508 if (res == -1) {
1509 return 0;
1510 }
1511 return res;
1512#else
1513 errno = ENOSYS;
1514 return 0;
1515#endif /* F_GETPIPE_SZ */
1516}
1517
1518bool setPipeBufferSize(int fd, size_t size)
1519{
1520#ifdef F_SETPIPE_SZ
1521 if (size > std::numeric_limits<int>::max()) {
1522 errno = EINVAL;
1523 return false;
1524 }
1525 int newSize = static_cast<int>(size);
1526 int res = fcntl(fd, F_SETPIPE_SZ, newSize);
1527 if (res == -1) {
1528 return false;
1529 }
1530 return true;
1531#else
1532 errno = ENOSYS;
1533 return false;
1534#endif /* F_SETPIPE_SZ */
1535}
ef3ee606
RG
1536
1537DNSName reverseNameFromIP(const ComboAddress& ip)
1538{
1539 if (ip.isIPv4()) {
1540 std::string result("in-addr.arpa.");
1541 auto ptr = reinterpret_cast<const uint8_t*>(&ip.sin4.sin_addr.s_addr);
1542 for (size_t idx = 0; idx < sizeof(ip.sin4.sin_addr.s_addr); idx++) {
1543 result = std::to_string(ptr[idx]) + "." + result;
1544 }
1545 return DNSName(result);
1546 }
1547 else if (ip.isIPv6()) {
1548 std::string result("ip6.arpa.");
1549 auto ptr = reinterpret_cast<const uint8_t*>(&ip.sin6.sin6_addr.s6_addr[0]);
1550 for (size_t idx = 0; idx < sizeof(ip.sin6.sin6_addr.s6_addr); idx++) {
1551 std::stringstream stream;
1552 stream << std::hex << (ptr[idx] & 0x0F);
1553 stream << '.';
1554 stream << std::hex << (((ptr[idx]) >> 4) & 0x0F);
1555 stream << '.';
1556 result = stream.str() + result;
1557 }
1558 return DNSName(result);
1559 }
1560
1561 throw std::runtime_error("Calling reverseNameFromIP() for an address which is neither an IPv4 nor an IPv6");
1562}