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