]> git.ipfire.org Git - thirdparty/pdns.git/blame - pdns/misc.cc
travis: Add -Werror=vla to prevent the use of VLAs
[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';
205 return 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);
51959320 341 if ( ret == -1 ) {
f4ff5929 342 errno = ETIMEDOUT; // ???
51959320
RG
343 }
344 else if (ret > 0) {
345 if (error && (pfd.revents & POLLERR)) {
346 *error = true;
347 }
348 if (disconnected && (pfd.revents & POLLHUP)) {
349 *disconnected = true;
350 }
351 }
1258abe0 352
12c86877
BH
353 return ret;
354}
355
a71bee29 356// returns -1 in case of error, 0 if no data is available, 1 if there is. In the first two cases, errno is set
d529011f
PL
357int waitForMultiData(const set<int>& fds, const int seconds, const int useconds, int* fd) {
358 set<int> realFDs;
359 for (const auto& fd : fds) {
360 if (fd >= 0 && realFDs.count(fd) == 0) {
361 realFDs.insert(fd);
362 }
363 }
364
dcc0e65d
RG
365 std::vector<struct pollfd> pfds(realFDs.size());
366 memset(&pfds.at(0), 0, realFDs.size()*sizeof(struct pollfd));
d529011f
PL
367 int ctr = 0;
368 for (const auto& fd : realFDs) {
369 pfds[ctr].fd = fd;
370 pfds[ctr].events = POLLIN;
371 ctr++;
372 }
373
374 int ret;
375 if(seconds >= 0)
dcc0e65d 376 ret = poll(&pfds.at(0), realFDs.size(), seconds * 1000 + useconds/1000);
d529011f 377 else
dcc0e65d 378 ret = poll(&pfds.at(0), realFDs.size(), -1);
d529011f
PL
379 if(ret <= 0)
380 return ret;
381
382 set<int> pollinFDs;
aca9c605
PL
383 for (const auto& pfd : pfds) {
384 if (pfd.revents & POLLIN) {
385 pollinFDs.insert(pfd.fd);
d529011f 386 }
d529011f
PL
387 }
388 set<int>::const_iterator it(pollinFDs.begin());
389 advance(it, random() % pollinFDs.size());
390 *fd = *it;
391 return 1;
392}
393
a71bee29 394// 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
395int waitFor2Data(int fd1, int fd2, int seconds, int useconds, int*fd)
396{
397 int ret;
398
399 struct pollfd pfds[2];
400 memset(&pfds[0], 0, 2*sizeof(struct pollfd));
401 pfds[0].fd = fd1;
402 pfds[1].fd = fd2;
3ddb9247 403
f4ff5929
BH
404 pfds[0].events= pfds[1].events = POLLIN;
405
406 int nsocks = 1 + (fd2 >= 0); // fd2 can optionally be -1
407
408 if(seconds >= 0)
409 ret = poll(pfds, nsocks, seconds * 1000 + useconds/1000);
410 else
411 ret = poll(pfds, nsocks, -1);
412 if(!ret || ret < 0)
413 return ret;
3ddb9247 414
f4ff5929
BH
415 if((pfds[0].revents & POLLIN) && !(pfds[1].revents & POLLIN))
416 *fd = pfds[0].fd;
417 else if((pfds[1].revents & POLLIN) && !(pfds[0].revents & POLLIN))
418 *fd = pfds[1].fd;
419 else if(ret == 2) {
420 *fd = pfds[random()%2].fd;
421 }
422 else
423 *fd = -1; // should never happen
3ddb9247 424
f4ff5929
BH
425 return 1;
426}
427
12c86877
BH
428
429string humanDuration(time_t passed)
430{
431 ostringstream ret;
432 if(passed<60)
433 ret<<passed<<" seconds";
434 else if(passed<3600)
9e04108d 435 ret<<std::setprecision(2)<<passed/60.0<<" minutes";
12c86877 436 else if(passed<86400)
9e04108d 437 ret<<std::setprecision(3)<<passed/3600.0<<" hours";
12c86877 438 else if(passed<(86400*30.41))
9e04108d 439 ret<<std::setprecision(3)<<passed/86400.0<<" days";
12c86877 440 else
9e04108d 441 ret<<std::setprecision(3)<<passed/(86400*30.41)<<" months";
12c86877
BH
442
443 return ret.str();
444}
445
446DTime::DTime()
447{
eefd15f9 448// set(); // saves lots of gettimeofday calls
55b6512d 449 d_set.tv_sec=d_set.tv_usec=0;
12c86877
BH
450}
451
452DTime::DTime(const DTime &dt)
453{
454 d_set=dt.d_set;
455}
456
457time_t DTime::time()
458{
459 return d_set.tv_sec;
460}
461
1d329048
BH
462const string unquotify(const string &item)
463{
464 if(item.size()<2)
465 return item;
466
467 string::size_type bpos=0, epos=item.size();
12c86877 468
3ddb9247 469 if(item[0]=='"')
1d329048 470 bpos=1;
c4bee46c 471
1d329048
BH
472 if(item[epos-1]=='"')
473 epos-=1;
474
c4bee46c 475 return item.substr(bpos,epos-bpos);
1d329048 476}
12c86877
BH
477
478void stripLine(string &line)
479{
bdf40704 480 string::size_type pos=line.find_first_of("\r\n");
12c86877
BH
481 if(pos!=string::npos) {
482 line.resize(pos);
483 }
484}
485
486string urlEncode(const string &text)
487{
488 string ret;
489 for(string::const_iterator i=text.begin();i!=text.end();++i)
490 if(*i==' ')ret.append("%20");
491 else ret.append(1,*i);
492 return ret;
493}
494
495string getHostname()
496{
0db70140 497#ifndef MAXHOSTNAMELEN
76473b92 498#define MAXHOSTNAMELEN 255
0db70140 499#endif
ac2bb9e7 500
12c86877
BH
501 char tmp[MAXHOSTNAMELEN];
502 if(gethostname(tmp, MAXHOSTNAMELEN))
503 return "UNKNOWN";
504
505 return tmp;
506}
507
508string itoa(int i)
509{
510 ostringstream o;
511 o<<i;
512 return o.str();
513}
514
22c9c86a
BH
515string uitoa(unsigned int i) // MSVC 6 doesn't grok overloading (un)signed
516{
517 ostringstream o;
518 o<<i;
519 return o.str();
520}
521
d88babea
KM
522string bitFlip(const string &str)
523{
524 string::size_type pos=0, epos=str.size();
525 string ret;
526 ret.reserve(epos);
527 for(;pos < epos; ++pos)
528 ret.append(1, ~str[pos]);
529 return ret;
530}
22c9c86a 531
12c86877
BH
532string stringerror()
533{
534 return strerror(errno);
535}
536
d3b4137e
BH
537string netstringerror()
538{
539 return stringerror();
540}
d3b4137e 541
12c86877
BH
542void cleanSlashes(string &str)
543{
544 string::const_iterator i;
545 string out;
546 for(i=str.begin();i!=str.end();++i) {
547 if(*i=='/' && i!=str.begin() && *(i-1)=='/')
548 continue;
549 out.append(1,*i);
550 }
551 str=out;
552}
553
7b35aa49 554
092f210a 555bool IpToU32(const string &str, uint32_t *ip)
525b8a7c 556{
4cf26303
BH
557 if(str.empty()) {
558 *ip=0;
559 return true;
560 }
3ddb9247 561
092c9cc4 562 struct in_addr inp;
3897b9e1 563 if(inet_aton(str.c_str(), &inp)) {
092c9cc4
BH
564 *ip=inp.s_addr;
565 return true;
566 }
567 return false;
525b8a7c
BH
568}
569
5730f30c
BH
570string U32ToIP(uint32_t val)
571{
572 char tmp[17];
3ddb9247 573 snprintf(tmp, sizeof(tmp)-1, "%u.%u.%u.%u",
4957a608
BH
574 (val >> 24)&0xff,
575 (val >> 16)&0xff,
576 (val >> 8)&0xff,
577 (val )&0xff);
5730f30c
BH
578 return tmp;
579}
580
37d3f960 581
2db9c30e
BH
582string makeHexDump(const string& str)
583{
584 char tmp[5];
585 string ret;
ea634573 586 ret.reserve((int)(str.size()*2.2));
2db9c30e
BH
587
588 for(string::size_type n=0;n<str.size();++n) {
589 sprintf(tmp,"%02x ", (unsigned char)str[n]);
590 ret+=tmp;
591 }
592 return ret;
593}
594
e67e250f 595// shuffle, maintaining some semblance of order
d190894c 596void shuffle(vector<DNSZoneRecord>& rrs)
e67e250f 597{
d190894c 598 vector<DNSZoneRecord>::iterator first, second;
3ddb9247 599 for(first=rrs.begin();first!=rrs.end();++first)
d190894c 600 if(first->dr.d_place==DNSResourceRecord::ANSWER && first->dr.d_type != QType::CNAME) // CNAME must come first
e67e250f
BH
601 break;
602 for(second=first;second!=rrs.end();++second)
d190894c 603 if(second->dr.d_place!=DNSResourceRecord::ANSWER)
e67e250f 604 break;
3ddb9247 605
d190894c 606 if(second-first > 1)
e67e250f 607 random_shuffle(first,second);
3ddb9247 608
e67e250f 609 // now shuffle the additional records
3ddb9247 610 for(first=second;first!=rrs.end();++first)
d190894c 611 if(first->dr.d_place==DNSResourceRecord::ADDITIONAL && first->dr.d_type != QType::CNAME) // CNAME must come first
e67e250f
BH
612 break;
613 for(second=first;second!=rrs.end();++second)
d190894c 614 if(second->dr.d_place!=DNSResourceRecord::ADDITIONAL)
e67e250f 615 break;
3ddb9247 616
e67e250f
BH
617 if(second-first>1)
618 random_shuffle(first,second);
619
620 // we don't shuffle the rest
621}
88358c9b 622
e325f20c 623
624// shuffle, maintaining some semblance of order
625void shuffle(vector<DNSRecord>& rrs)
92476c8b 626{
e325f20c 627 vector<DNSRecord>::iterator first, second;
628 for(first=rrs.begin();first!=rrs.end();++first)
e693ff5a 629 if(first->d_place==DNSResourceRecord::ANSWER && first->d_type != QType::CNAME) // CNAME must come first
e325f20c 630 break;
631 for(second=first;second!=rrs.end();++second)
2cccc377 632 if(second->d_place!=DNSResourceRecord::ANSWER || second->d_type == QType::RRSIG) // leave RRSIGs at the end
e325f20c 633 break;
634
635 if(second-first>1)
636 random_shuffle(first,second);
637
638 // now shuffle the additional records
639 for(first=second;first!=rrs.end();++first)
e693ff5a 640 if(first->d_place==DNSResourceRecord::ADDITIONAL && first->d_type != QType::CNAME) // CNAME must come first
e325f20c 641 break;
642 for(second=first; second!=rrs.end(); ++second)
e693ff5a 643 if(second->d_place!=DNSResourceRecord::ADDITIONAL)
e325f20c 644 break;
645
646 if(second-first>1)
647 random_shuffle(first,second);
648
649 // we don't shuffle the rest
92476c8b
PD
650}
651
2cccc377 652static uint16_t mapTypesToOrder(uint16_t type)
27b85f24 653{
654 if(type == QType::CNAME)
655 return 0;
2cccc377 656 if(type == QType::RRSIG)
657 return 65535;
27b85f24 658 else
659 return 1;
660}
661
92476c8b
PD
662// make sure rrs is sorted in d_place order to avoid surprises later
663// then shuffle the parts that desire shuffling
e325f20c 664void orderAndShuffle(vector<DNSRecord>& rrs)
92476c8b 665{
e325f20c 666 std::stable_sort(rrs.begin(), rrs.end(), [](const DNSRecord&a, const DNSRecord& b) {
2cccc377 667 return std::make_tuple(a.d_place, mapTypesToOrder(a.d_type)) < std::make_tuple(b.d_place, mapTypesToOrder(b.d_type));
e325f20c 668 });
92476c8b
PD
669 shuffle(rrs);
670}
88358c9b
BH
671
672void normalizeTV(struct timeval& tv)
673{
674 if(tv.tv_usec > 1000000) {
675 ++tv.tv_sec;
676 tv.tv_usec-=1000000;
677 }
678 else if(tv.tv_usec < 0) {
679 --tv.tv_sec;
680 tv.tv_usec+=1000000;
681 }
682}
683
684const struct timeval operator+(const struct timeval& lhs, const struct timeval& rhs)
685{
686 struct timeval ret;
687 ret.tv_sec=lhs.tv_sec + rhs.tv_sec;
688 ret.tv_usec=lhs.tv_usec + rhs.tv_usec;
689 normalizeTV(ret);
690 return ret;
691}
692
693const struct timeval operator-(const struct timeval& lhs, const struct timeval& rhs)
694{
695 struct timeval ret;
696 ret.tv_sec=lhs.tv_sec - rhs.tv_sec;
697 ret.tv_usec=lhs.tv_usec - rhs.tv_usec;
698 normalizeTV(ret);
699 return ret;
700}
50c79a76
BH
701
702pair<string, string> splitField(const string& inp, char sepa)
703{
704 pair<string, string> ret;
705 string::size_type cpos=inp.find(sepa);
706 if(cpos==string::npos)
707 ret.first=inp;
708 else {
709 ret.first=inp.substr(0, cpos);
710 ret.second=inp.substr(cpos+1);
711 }
712 return ret;
713}
6e2514e4 714
f8499e52 715int logFacilityToLOG(unsigned int facility)
6e2514e4 716{
6e2514e4
BH
717 switch(facility) {
718 case 0:
719 return LOG_LOCAL0;
720 case 1:
721 return(LOG_LOCAL1);
722 case 2:
723 return(LOG_LOCAL2);
724 case 3:
725 return(LOG_LOCAL3);
726 case 4:
727 return(LOG_LOCAL4);
728 case 5:
729 return(LOG_LOCAL5);
730 case 6:
731 return(LOG_LOCAL6);
732 case 7:
733 return(LOG_LOCAL7);
734 default:
f8499e52 735 return -1;
6e2514e4
BH
736 }
737}
da042e6e
BH
738
739string stripDot(const string& dom)
740{
741 if(dom.empty())
742 return dom;
743
744 if(dom[dom.size()-1]!='.')
745 return dom;
746
747 return dom.substr(0,dom.size()-1);
748}
4dadd22f
BH
749
750
f71bc087
BH
751
752int makeIPv6sockaddr(const std::string& addr, struct sockaddr_in6* ret)
753{
85db02c5
BH
754 if(addr.empty())
755 return -1;
756 string ourAddr(addr);
6cbfa73b
RG
757 bool portSet = false;
758 unsigned int port;
85db02c5
BH
759 if(addr[0]=='[') { // [::]:53 style address
760 string::size_type pos = addr.find(']');
0047d734 761 if(pos == string::npos)
85db02c5
BH
762 return -1;
763 ourAddr.assign(addr.c_str() + 1, pos-1);
ed2ff96e 764 if (pos + 1 != addr.size()) { // complete after ], no port specified
0047d734
CH
765 if (pos + 2 > addr.size() || addr[pos+1]!=':')
766 return -1;
767 try {
768 port = pdns_stou(addr.substr(pos+2));
769 portSet = true;
770 }
771 catch(std::out_of_range) {
772 return -1;
773 }
5b4ed369 774 }
85db02c5 775 }
39d2d9b2 776 ret->sin6_scope_id=0;
777 ret->sin6_family=AF_INET6;
778
0c9de4fc 779 if(inet_pton(AF_INET6, ourAddr.c_str(), (void*)&ret->sin6_addr) != 1) {
780 struct addrinfo* res;
781 struct addrinfo hints;
782 memset(&hints, 0, sizeof(hints));
3ddb9247 783
0c9de4fc 784 hints.ai_family = AF_INET6;
785 hints.ai_flags = AI_NUMERICHOST;
3ddb9247 786
0c9de4fc 787 int error;
1746e9bb 788 // getaddrinfo has anomalous return codes, anything nonzero is an error, positive or negative
789 if((error=getaddrinfo(ourAddr.c_str(), 0, &hints, &res))) {
0c9de4fc 790 return -1;
791 }
3ddb9247 792
0c9de4fc 793 memcpy(ret, res->ai_addr, res->ai_addrlen);
794 freeaddrinfo(res);
f71bc087 795 }
0c9de4fc 796
6cbfa73b
RG
797 if(portSet) {
798 if(port > 65535)
799 return -1;
5b4ed369 800
85db02c5 801 ret->sin6_port = htons(port);
6cbfa73b 802 }
0c9de4fc 803
f71bc087
BH
804 return 0;
805}
834942f1 806
76cb4593 807int makeIPv4sockaddr(const std::string& str, struct sockaddr_in* ret)
85db02c5
BH
808{
809 if(str.empty()) {
810 return -1;
811 }
812 struct in_addr inp;
3ddb9247 813
85db02c5
BH
814 string::size_type pos = str.find(':');
815 if(pos == string::npos) { // no port specified, not touching the port
3897b9e1 816 if(inet_aton(str.c_str(), &inp)) {
85db02c5
BH
817 ret->sin_addr.s_addr=inp.s_addr;
818 return 0;
819 }
820 return -1;
821 }
822 if(!*(str.c_str() + pos + 1)) // trailing :
3ddb9247
PD
823 return -1;
824
85db02c5
BH
825 char *eptr = (char*)str.c_str() + str.size();
826 int port = strtol(str.c_str() + pos + 1, &eptr, 10);
5b4ed369
PL
827 if (port < 0 || port > 65535)
828 return -1;
829
85db02c5
BH
830 if(*eptr)
831 return -1;
3ddb9247 832
85db02c5 833 ret->sin_port = htons(port);
3897b9e1 834 if(inet_aton(str.substr(0, pos).c_str(), &inp)) {
85db02c5
BH
835 ret->sin_addr.s_addr=inp.s_addr;
836 return 0;
837 }
838 return -1;
839}
840
76cb4593
CH
841int makeUNsockaddr(const std::string& path, struct sockaddr_un* ret)
842{
843 if (path.empty())
844 return -1;
845
846 memset(ret, 0, sizeof(struct sockaddr_un));
847 ret->sun_family = AF_UNIX;
848 if (path.length() >= sizeof(ret->sun_path))
849 return -1;
850
851 path.copy(ret->sun_path, sizeof(ret->sun_path), 0);
852 return 0;
853}
85db02c5 854
834942f1
BH
855//! read a line of text from a FILE* to a std::string, returns false on 'no data'
856bool stringfgets(FILE* fp, std::string& line)
857{
858 char buffer[1024];
859 line.clear();
3ddb9247 860
834942f1
BH
861 do {
862 if(!fgets(buffer, sizeof(buffer), fp))
863 return !line.empty();
3ddb9247
PD
864
865 line.append(buffer);
834942f1
BH
866 } while(!strchr(buffer, '\n'));
867 return true;
868}
e611a06c 869
4e9a20e6 870bool readFileIfThere(const char* fname, std::string* line)
871{
872 line->clear();
873 FILE* fp = fopen(fname, "r");
874 if(!fp)
875 return false;
876 stringfgets(fp, *line);
877 fclose(fp);
878 return true;
879}
880
3ee84c3f
BH
881Regex::Regex(const string &expr)
882{
883 if(regcomp(&d_preg, expr.c_str(), REG_ICASE|REG_NOSUB|REG_EXTENDED))
3f81d239 884 throw PDNSException("Regular expression did not compile");
3ee84c3f 885}
65d8e171 886
25ba7344
PD
887// if you end up here because valgrind told you were are doing something wrong
888// with msgh->msg_controllen, please refer to https://github.com/PowerDNS/pdns/pull/3962
889// first.
fbe2a2e0 890void addCMsgSrcAddr(struct msghdr* msgh, void* cmsgbuf, const ComboAddress* source, int itfIndex)
65d8e171 891{
ecc8571f 892 struct cmsghdr *cmsg = NULL;
65d8e171
KN
893
894 if(source->sin4.sin_family == AF_INET6) {
895 struct in6_pktinfo *pkt;
896
897 msgh->msg_control = cmsgbuf;
898 msgh->msg_controllen = CMSG_SPACE(sizeof(*pkt));
899
900 cmsg = CMSG_FIRSTHDR(msgh);
901 cmsg->cmsg_level = IPPROTO_IPV6;
902 cmsg->cmsg_type = IPV6_PKTINFO;
903 cmsg->cmsg_len = CMSG_LEN(sizeof(*pkt));
904
905 pkt = (struct in6_pktinfo *) CMSG_DATA(cmsg);
906 memset(pkt, 0, sizeof(*pkt));
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;
915 msgh->msg_controllen = CMSG_SPACE(sizeof(*pkt));
916
917 cmsg = CMSG_FIRSTHDR(msgh);
918 cmsg->cmsg_level = IPPROTO_IP;
919 cmsg->cmsg_type = IP_PKTINFO;
920 cmsg->cmsg_len = CMSG_LEN(sizeof(*pkt));
921
922 pkt = (struct in_pktinfo *) CMSG_DATA(cmsg);
923 memset(pkt, 0, sizeof(*pkt));
924 pkt->ipi_spec_dst = source->sin4.sin_addr;
fbe2a2e0 925 pkt->ipi_ifindex = itfIndex;
4d39d7f3 926#elif defined(IP_SENDSRCADDR)
65d8e171
KN
927 struct in_addr *in;
928
929 msgh->msg_control = cmsgbuf;
930 msgh->msg_controllen = CMSG_SPACE(sizeof(*in));
931
932 cmsg = CMSG_FIRSTHDR(msgh);
933 cmsg->cmsg_level = IPPROTO_IP;
934 cmsg->cmsg_type = IP_SENDSRCADDR;
935 cmsg->cmsg_len = CMSG_LEN(sizeof(*in));
936
937 in = (struct in_addr *) CMSG_DATA(cmsg);
938 *in = source->sin4.sin_addr;
ecc8571f 939#endif
65d8e171
KN
940 }
941}
3a8a4d68 942
943unsigned int getFilenumLimit(bool hardOrSoft)
944{
945 struct rlimit rlim;
946 if(getrlimit(RLIMIT_NOFILE, &rlim) < 0)
947 unixDie("Requesting number of available file descriptors");
948 return hardOrSoft ? rlim.rlim_max : rlim.rlim_cur;
949}
950
951void setFilenumLimit(unsigned int lim)
952{
953 struct rlimit rlim;
954
955 if(getrlimit(RLIMIT_NOFILE, &rlim) < 0)
956 unixDie("Requesting number of available file descriptors");
957 rlim.rlim_cur=lim;
958 if(setrlimit(RLIMIT_NOFILE, &rlim) < 0)
959 unixDie("Setting number of available file descriptors");
960}
06ea9015 961
962#define burtlemix(a,b,c) \
963{ \
964 a -= b; a -= c; a ^= (c>>13); \
965 b -= c; b -= a; b ^= (a<<8); \
966 c -= a; c -= b; c ^= (b>>13); \
967 a -= b; a -= c; a ^= (c>>12); \
968 b -= c; b -= a; b ^= (a<<16); \
969 c -= a; c -= b; c ^= (b>>5); \
970 a -= b; a -= c; a ^= (c>>3); \
971 b -= c; b -= a; b ^= (a<<10); \
972 c -= a; c -= b; c ^= (b>>15); \
973}
974
975uint32_t burtle(const unsigned char* k, uint32_t length, uint32_t initval)
976{
977 uint32_t a,b,c,len;
978
979 /* Set up the internal state */
980 len = length;
981 a = b = 0x9e3779b9; /* the golden ratio; an arbitrary value */
982 c = initval; /* the previous hash value */
983
984 /*---------------------------------------- handle most of the key */
985 while (len >= 12) {
986 a += (k[0] +((uint32_t)k[1]<<8) +((uint32_t)k[2]<<16) +((uint32_t)k[3]<<24));
987 b += (k[4] +((uint32_t)k[5]<<8) +((uint32_t)k[6]<<16) +((uint32_t)k[7]<<24));
988 c += (k[8] +((uint32_t)k[9]<<8) +((uint32_t)k[10]<<16)+((uint32_t)k[11]<<24));
989 burtlemix(a,b,c);
990 k += 12; len -= 12;
991 }
992
993 /*------------------------------------- handle the last 11 bytes */
994 c += length;
995 switch(len) { /* all the case statements fall through */
996 case 11: c+=((uint32_t)k[10]<<24);
997 case 10: c+=((uint32_t)k[9]<<16);
998 case 9 : c+=((uint32_t)k[8]<<8);
999 /* the first byte of c is reserved for the length */
1000 case 8 : b+=((uint32_t)k[7]<<24);
1001 case 7 : b+=((uint32_t)k[6]<<16);
1002 case 6 : b+=((uint32_t)k[5]<<8);
1003 case 5 : b+=k[4];
1004 case 4 : a+=((uint32_t)k[3]<<24);
1005 case 3 : a+=((uint32_t)k[2]<<16);
1006 case 2 : a+=((uint32_t)k[1]<<8);
1007 case 1 : a+=k[0];
1008 /* case 0: nothing left to add */
1009 }
1010 burtlemix(a,b,c);
1011 /*-------------------------------------------- report the result */
1012 return c;
1013}
9ae194e2 1014
6200227b 1015uint32_t burtleCI(const unsigned char* k, uint32_t length, uint32_t initval)
1016{
1017 uint32_t a,b,c,len;
1018
1019 /* Set up the internal state */
1020 len = length;
1021 a = b = 0x9e3779b9; /* the golden ratio; an arbitrary value */
1022 c = initval; /* the previous hash value */
1023
1024 /*---------------------------------------- handle most of the key */
1025 while (len >= 12) {
af891b3d 1026 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));
1027 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));
1028 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 1029 burtlemix(a,b,c);
1030 k += 12; len -= 12;
1031 }
1032
1033 /*------------------------------------- handle the last 11 bytes */
1034 c += length;
1035 switch(len) { /* all the case statements fall through */
af891b3d 1036 case 11: c+=((uint32_t)dns_tolower(k[10])<<24);
1037 case 10: c+=((uint32_t)dns_tolower(k[9])<<16);
1038 case 9 : c+=((uint32_t)dns_tolower(k[8])<<8);
6200227b 1039 /* the first byte of c is reserved for the length */
af891b3d 1040 case 8 : b+=((uint32_t)dns_tolower(k[7])<<24);
1041 case 7 : b+=((uint32_t)dns_tolower(k[6])<<16);
1042 case 6 : b+=((uint32_t)dns_tolower(k[5])<<8);
1043 case 5 : b+=dns_tolower(k[4]);
1044 case 4 : a+=((uint32_t)dns_tolower(k[3])<<24);
1045 case 3 : a+=((uint32_t)dns_tolower(k[2])<<16);
1046 case 2 : a+=((uint32_t)dns_tolower(k[1])<<8);
1047 case 1 : a+=dns_tolower(k[0]);
6200227b 1048 /* case 0: nothing left to add */
1049 }
1050 burtlemix(a,b,c);
1051 /*-------------------------------------------- report the result */
1052 return c;
1053}
1054
1055
915b0c39 1056bool setSocketTimestamps(int fd)
9ae194e2 1057{
eb4c1792 1058#ifdef SO_TIMESTAMP
9ae194e2 1059 int on=1;
915b0c39 1060 return setsockopt(fd, SOL_SOCKET, SO_TIMESTAMP, (char*)&on, sizeof(on)) == 0;
99be0a43 1061#else
915b0c39 1062 return true; // we pretend this happened.
99be0a43 1063#endif
9ae194e2 1064}
58044407 1065
883a30a7 1066bool setTCPNoDelay(int sock)
149d0144 1067{
1068 int flag = 1;
883a30a7
RG
1069 return setsockopt(sock, /* socket affected */
1070 IPPROTO_TCP, /* set option at TCP level */
1071 TCP_NODELAY, /* name of option */
1072 (char *) &flag, /* the cast is historical cruft */
1073 sizeof(flag)) == 0; /* length of option value */
149d0144 1074}
1075
1076
3897b9e1 1077bool setNonBlocking(int sock)
1078{
3ddb9247 1079 int flags=fcntl(sock,F_GETFL,0);
3897b9e1 1080 if(flags<0 || fcntl(sock, F_SETFL,flags|O_NONBLOCK) <0)
1081 return false;
1082 return true;
1083}
1084
1085bool setBlocking(int sock)
1086{
3ddb9247 1087 int flags=fcntl(sock,F_GETFL,0);
3897b9e1 1088 if(flags<0 || fcntl(sock, F_SETFL,flags&(~O_NONBLOCK)) <0)
1089 return false;
1090 return true;
1091}
1092
bf676f2f
PL
1093bool setReuseAddr(int sock)
1094{
1095 int tmp = 1;
1096 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&tmp, static_cast<unsigned>(sizeof tmp))<0)
1097 throw PDNSException(string("Setsockopt failed: ")+strerror(errno));
1098 return true;
1099}
1100
18861f97
RG
1101bool isNonBlocking(int sock)
1102{
1103 int flags=fcntl(sock,F_GETFL,0);
1104 return flags & O_NONBLOCK;
1105}
1106
3897b9e1 1107// Closes a socket.
1108int closesocket( int socket )
1109{
1110 int ret=::close(socket);
1111 if(ret < 0 && errno == ECONNRESET) // see ticket 192, odd BSD behaviour
1112 return 0;
3ddb9247 1113 if(ret < 0)
3897b9e1 1114 throw PDNSException("Error closing socket: "+stringerror());
1115 return ret;
1116}
1117
1118bool setCloseOnExec(int sock)
1119{
3ddb9247 1120 int flags=fcntl(sock,F_GETFD,0);
3897b9e1 1121 if(flags<0 || fcntl(sock, F_SETFD,flags|FD_CLOEXEC) <0)
1122 return false;
1123 return true;
1124}
1125
6907f014 1126string getMACAddress(const ComboAddress& ca)
1127{
1128 string ret;
1129#ifdef __linux__
1130 ifstream ifs("/proc/net/arp");
1131 if(!ifs)
1132 return ret;
1133 string line;
1134 string match=ca.toString()+' ';
1135 while(getline(ifs, line)) {
1136 if(boost::starts_with(line, match)) {
1137 vector<string> parts;
1138 stringtok(parts, line, " \n\t\r");
1139 if(parts.size() < 4)
1140 return ret;
1141 unsigned int tmp[6];
1142 sscanf(parts[3].c_str(), "%02x:%02x:%02x:%02x:%02x:%02x", tmp, tmp+1, tmp+2, tmp+3, tmp+4, tmp+5);
1143 for(int i = 0 ; i< 6 ; ++i)
1144 ret.append(1, (char)tmp[i]);
1145 return ret;
1146 }
1147 }
1148#endif
1149 return ret;
1150}
1151
8290ad9f 1152uint64_t udpErrorStats(const std::string& str)
1153{
1154#ifdef __linux__
1155 ifstream ifs("/proc/net/snmp");
1156 if(!ifs)
1157 return 0;
1158 string line;
1159 vector<string> parts;
1160 while(getline(ifs,line)) {
1161 if(boost::starts_with(line, "Udp: ") && isdigit(line[5])) {
1162 stringtok(parts, line, " \n\t\r");
1163 if(parts.size() < 7)
1164 break;
1165 if(str=="udp-rcvbuf-errors")
335da0ba 1166 return std::stoull(parts[5]);
8290ad9f 1167 else if(str=="udp-sndbuf-errors")
335da0ba 1168 return std::stoull(parts[6]);
8290ad9f 1169 else if(str=="udp-noport-errors")
335da0ba 1170 return std::stoull(parts[2]);
8290ad9f 1171 else if(str=="udp-in-errors")
335da0ba 1172 return std::stoull(parts[3]);
8290ad9f 1173 else
1174 return 0;
1175 }
1176 }
1177#endif
1178 return 0;
1179}
da15912b 1180
21a3792f 1181bool getTSIGHashEnum(const DNSName& algoName, TSIGHashEnum& algoEnum)
da15912b 1182{
2330c421 1183 if (algoName == DNSName("hmac-md5.sig-alg.reg.int") || algoName == DNSName("hmac-md5"))
da15912b 1184 algoEnum = TSIG_MD5;
2330c421 1185 else if (algoName == DNSName("hmac-sha1"))
da15912b 1186 algoEnum = TSIG_SHA1;
2330c421 1187 else if (algoName == DNSName("hmac-sha224"))
da15912b 1188 algoEnum = TSIG_SHA224;
2330c421 1189 else if (algoName == DNSName("hmac-sha256"))
da15912b 1190 algoEnum = TSIG_SHA256;
2330c421 1191 else if (algoName == DNSName("hmac-sha384"))
da15912b 1192 algoEnum = TSIG_SHA384;
2330c421 1193 else if (algoName == DNSName("hmac-sha512"))
da15912b 1194 algoEnum = TSIG_SHA512;
2330c421 1195 else if (algoName == DNSName("gss-tsig"))
bcb5b94e 1196 algoEnum = TSIG_GSS;
da15912b
AT
1197 else {
1198 return false;
1199 }
1200 return true;
1201}
bfd4efae 1202
21a3792f 1203DNSName getTSIGAlgoName(TSIGHashEnum& algoEnum)
bfd4efae
AT
1204{
1205 switch(algoEnum) {
8171ab83 1206 case TSIG_MD5: return DNSName("hmac-md5.sig-alg.reg.int.");
1207 case TSIG_SHA1: return DNSName("hmac-sha1.");
1208 case TSIG_SHA224: return DNSName("hmac-sha224.");
1209 case TSIG_SHA256: return DNSName("hmac-sha256.");
1210 case TSIG_SHA384: return DNSName("hmac-sha384.");
1211 case TSIG_SHA512: return DNSName("hmac-sha512.");
1212 case TSIG_GSS: return DNSName("gss-tsig.");
bfd4efae
AT
1213 }
1214 throw PDNSException("getTSIGAlgoName does not understand given algorithm, please fix!");
1215}
a1a787dc 1216
a9b6db56 1217uint64_t getOpenFileDescriptors(const std::string&)
1218{
1219#ifdef __linux__
1220 DIR* dirhdl=opendir(("/proc/"+std::to_string(getpid())+"/fd/").c_str());
1221 if(!dirhdl)
1222 return 0;
1223
1224 struct dirent *entry;
1225 int ret=0;
1226 while((entry = readdir(dirhdl))) {
335da0ba
AT
1227 uint32_t num;
1228 try {
1229 num = pdns_stou(entry->d_name);
1230 } catch (...) {
1231 continue; // was not a number.
1232 }
a9b6db56 1233 if(std::to_string(num) == entry->d_name)
1234 ret++;
1235 }
1236 closedir(dirhdl);
1237 return ret;
1238
1239#else
1240 return 0;
1241#endif
1242}
1243
a1a787dc 1244uint64_t getRealMemoryUsage(const std::string&)
1245{
1246#ifdef __linux__
1247 ifstream ifs("/proc/"+std::to_string(getpid())+"/smaps");
1248 if(!ifs)
1249 return 0;
1250 string line;
1251 uint64_t bytes=0;
1252 string header("Private_Dirty:");
1253 while(getline(ifs, line)) {
1254 if(boost::starts_with(line, header)) {
335da0ba 1255 bytes += std::stoull(line.substr(header.length() + 1))*1024;
a1a787dc 1256 }
1257 }
1258 return bytes;
1259#else
1260 return 0;
1261#endif
1262}
4f99f3d3
RG
1263
1264uint64_t getCPUTimeUser(const std::string&)
1265{
1266 struct rusage ru;
1267 getrusage(RUSAGE_SELF, &ru);
1268 return (ru.ru_utime.tv_sec*1000ULL + ru.ru_utime.tv_usec/1000);
1269}
1270
1271uint64_t getCPUTimeSystem(const std::string&)
1272{
1273 struct rusage ru;
1274 getrusage(RUSAGE_SELF, &ru);
1275 return (ru.ru_stime.tv_sec*1000ULL + ru.ru_stime.tv_usec/1000);
1276}
3fcaeeac 1277
1278double DiffTime(const struct timespec& first, const struct timespec& second)
1279{
1280 int seconds=second.tv_sec - first.tv_sec;
1281 int nseconds=second.tv_nsec - first.tv_nsec;
1282
1283 if(nseconds < 0) {
1284 seconds-=1;
1285 nseconds+=1000000000;
1286 }
1287 return seconds + nseconds/1000000000.0;
1288}
1289
1290double DiffTime(const struct timeval& first, const struct timeval& second)
1291{
1292 int seconds=second.tv_sec - first.tv_sec;
1293 int useconds=second.tv_usec - first.tv_usec;
1294
1295 if(useconds < 0) {
1296 seconds-=1;
1297 useconds+=1000000;
1298 }
1299 return seconds + useconds/1000000.0;
1300}
ffb07158 1301
ffb07158 1302uid_t strToUID(const string &str)
1303{
1304 uid_t result = 0;
1305 const char * cstr = str.c_str();
1306 struct passwd * pwd = getpwnam(cstr);
1307
1308 if (pwd == NULL) {
e805cba5 1309 long long val;
ffb07158 1310
e805cba5
RG
1311 try {
1312 val = stoll(str);
ffb07158 1313 }
e805cba5
RG
1314 catch(std::exception& e) {
1315 throw runtime_error((boost::format("Error: Unable to parse user ID %s") % cstr).str() );
1316 }
1317
1318 if (val < std::numeric_limits<uid_t>::min() || val > std::numeric_limits<uid_t>::max()) {
1319 throw runtime_error((boost::format("Error: Unable to parse user ID %s") % cstr).str() );
ffb07158 1320 }
e805cba5
RG
1321
1322 result = static_cast<uid_t>(val);
ffb07158 1323 }
1324 else {
1325 result = pwd->pw_uid;
1326 }
1327
1328 return result;
1329}
1330
1331gid_t strToGID(const string &str)
1332{
1333 gid_t result = 0;
1334 const char * cstr = str.c_str();
1335 struct group * grp = getgrnam(cstr);
1336
1337 if (grp == NULL) {
e805cba5 1338 long long val;
ffb07158 1339
e805cba5
RG
1340 try {
1341 val = stoll(str);
ffb07158 1342 }
e805cba5
RG
1343 catch(std::exception& e) {
1344 throw runtime_error((boost::format("Error: Unable to parse group ID %s") % cstr).str() );
1345 }
1346
1347 if (val < std::numeric_limits<gid_t>::min() || val > std::numeric_limits<gid_t>::max()) {
1348 throw runtime_error((boost::format("Error: Unable to parse group ID %s") % cstr).str() );
ffb07158 1349 }
e805cba5
RG
1350
1351 result = static_cast<gid_t>(val);
ffb07158 1352 }
1353 else {
1354 result = grp->gr_gid;
1355 }
1356
1357 return result;
1358}
1359
335da0ba 1360unsigned int pdns_stou(const std::string& str, size_t * idx, int base)
a5c4e4a6 1361{
00f45062 1362 if (str.empty()) return 0; // compatibility
a5c4e4a6
AT
1363 unsigned long result = std::stoul(str, idx, base);
1364 if (result > std::numeric_limits<unsigned int>::max()) {
1365 throw std::out_of_range("stou");
1366 }
1367 return static_cast<unsigned int>(result);
1368}
1369
8fd25133
RG
1370bool isSettingThreadCPUAffinitySupported()
1371{
1372#ifdef HAVE_PTHREAD_SETAFFINITY_NP
1373 return true;
1374#else
1375 return false;
1376#endif
1377}
1378
1379int mapThreadToCPUList(pthread_t tid, const std::set<int>& cpus)
1380{
1381#ifdef HAVE_PTHREAD_SETAFFINITY_NP
4d39d7f3
TIH
1382# ifdef __NetBSD__
1383 cpuset_t *cpuset;
1384 cpuset = cpuset_create();
1385 for (const auto cpuID : cpus) {
1386 cpuset_set(cpuID, cpuset);
1387 }
1388
1389 return pthread_setaffinity_np(tid,
1390 cpuset_size(cpuset),
1391 cpuset);
1392# else
1393# ifdef __FreeBSD__
1394# define cpu_set_t cpuset_t
1395# endif
8fd25133
RG
1396 cpu_set_t cpuset;
1397 CPU_ZERO(&cpuset);
1398 for (const auto cpuID : cpus) {
1399 CPU_SET(cpuID, &cpuset);
1400 }
1401
1402 return pthread_setaffinity_np(tid,
1403 sizeof(cpuset),
1404 &cpuset);
4d39d7f3 1405# endif
99be0a43 1406#else
8fd25133 1407 return ENOSYS;
99be0a43 1408#endif /* HAVE_PTHREAD_SETAFFINITY_NP */
8fd25133 1409}