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