]>
git.ipfire.org Git - thirdparty/pdns.git/blob - pdns/misc.cc
2 * This file is part of PowerDNS or dnsdist.
3 * Copyright -- PowerDNS.COM B.V. and its contributors
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.
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.
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.
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.
25 #include <sys/param.h>
26 #include <sys/socket.h>
31 #include <sys/resource.h>
32 #include <netinet/in.h>
42 #include <sys/types.h>
45 #include <boost/optional.hpp>
48 #include <netinet/tcp.h>
52 #include "pdnsexception.hh"
53 #include <sys/types.h>
54 #include <boost/algorithm/string.hpp>
56 #include "dnsparser.hh"
57 #include <sys/types.h>
61 # include <pthread_np.h>
68 bool g_singleThreaded
;
70 size_t writen2(int fd
, const void *buf
, size_t count
)
72 const char *ptr
= (char*)buf
;
73 const char *eptr
= ptr
+ count
;
77 res
= ::write(fd
, ptr
, eptr
- ptr
);
80 throw std::runtime_error("used writen2 on non-blocking socket, got EAGAIN");
82 unixDie("failed in writen2");
85 throw std::runtime_error("could not write all bytes, got eof in writen2");
93 size_t readn2(int fd
, void* buffer
, size_t len
)
98 res
= read(fd
, (char*)buffer
+ pos
, len
- pos
);
100 throw runtime_error("EOF while reading message");
103 throw std::runtime_error("used readn2 on non-blocking socket, got EAGAIN");
105 unixDie("failed in readn2");
115 size_t readn2WithTimeout(int fd
, void* buffer
, size_t len
, int idleTimeout
, int totalTimeout
)
119 int remainingTime
= totalTimeout
;
125 ssize_t got
= read(fd
, (char *)buffer
+ pos
, len
- pos
);
130 throw runtime_error("EOF while reading message");
133 if (errno
== EAGAIN
) {
134 int res
= waitForData(fd
, (totalTimeout
== 0 || idleTimeout
<= remainingTime
) ? idleTimeout
: remainingTime
);
136 /* there is data available */
139 throw runtime_error("Timeout while waiting for data to read");
141 throw runtime_error("Error while waiting for data to read");
145 unixDie("failed in readn2WithTimeout");
150 time_t now
= time(NULL
);
151 int elapsed
= now
- start
;
152 if (elapsed
>= remainingTime
) {
153 throw runtime_error("Timeout while reading data");
156 remainingTime
-= elapsed
;
164 size_t writen2WithTimeout(int fd
, const void * buffer
, size_t len
, int timeout
)
168 ssize_t written
= write(fd
, (char *)buffer
+ pos
, len
- pos
);
171 pos
+= (size_t) written
;
173 else if (written
== 0)
174 throw runtime_error("EOF while writing message");
176 if (errno
== EAGAIN
) {
177 int res
= waitForRWData(fd
, false, timeout
, 0);
179 /* there is room available */
182 throw runtime_error("Timeout while waiting to write data");
184 throw runtime_error("Error while waiting for room to write data");
188 unixDie("failed in write2WithTimeout");
199 time_t now
= time(nullptr);
201 localtime_r(&now
, &tm
);
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
);
209 uint16_t getShort(const unsigned char *p
)
211 return p
[0] * 256 + p
[1];
215 uint16_t getShort(const char *p
)
217 return getShort((const unsigned char *)p
);
220 uint32_t getLong(const unsigned char* p
)
222 return (p
[0]<<24) + (p
[1]<<16) + (p
[2]<<8) + p
[3];
225 uint32_t getLong(const char* p
)
227 return getLong((unsigned char *)p
);
230 static bool ciEqual(const string
& a
, const string
& b
)
232 if(a
.size()!=b
.size())
235 string::size_type pos
=0, epos
=a
.size();
236 for(;pos
< epos
; ++pos
)
237 if(dns_tolower(a
[pos
])!=dns_tolower(b
[pos
]))
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
)
245 if( suffix
.empty() || ciEqual(domain
, suffix
) )
248 if(domain
.size()<=suffix
.size())
251 string::size_type dpos
=domain
.size()-suffix
.size()-1, spos
=0;
253 if(domain
[dpos
++]!='.')
256 for(; dpos
< domain
.size(); ++dpos
, ++spos
)
257 if(dns_tolower(domain
[dpos
]) != dns_tolower(suffix
[spos
]))
263 /** strips a domain suffix from a domain, returns true if it stripped */
264 bool stripDomainSuffix(string
*qname
, const string
&domain
)
266 if(!endsOn(*qname
, domain
))
269 if(toLower(*qname
)==toLower(domain
))
272 if((*qname
)[qname
->size()-domain
.size()-1]!='.')
275 qname
->resize(qname
->size()-domain
.size()-1);
280 static void parseService4(const string
&descr
, ServiceTuple
&st
)
283 stringtok(parts
,descr
,":");
285 throw PDNSException("Unable to parse '"+descr
+"' as a service");
288 st
.port
=pdns_stou(parts
[1]);
291 static void parseService6(const string
&descr
, ServiceTuple
&st
)
293 string::size_type pos
=descr
.find(']');
294 if(pos
== string::npos
)
295 throw PDNSException("Unable to parse '"+descr
+"' as an IPv6 service");
297 st
.host
=descr
.substr(1, pos
-1);
298 if(pos
+ 2 < descr
.length())
299 st
.port
=pdns_stou(descr
.substr(pos
+2));
303 void parseService(const string
&descr
, ServiceTuple
&st
)
306 throw PDNSException("Unable to parse '"+descr
+"' as a service");
308 vector
<string
> parts
;
309 stringtok(parts
, descr
, ":");
312 parseService6(descr
, st
);
314 else if(descr
[0]==':' || parts
.size() > 2 || descr
.find("::") != string::npos
) {
318 parseService4(descr
, st
);
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
)
325 return waitForRWData(fd
, true, seconds
, useconds
);
328 int waitForRWData(int fd
, bool waitForRead
, int seconds
, int useconds
, bool* error
, bool* disconnected
)
333 memset(&pfd
, 0, sizeof(pfd
));
341 ret
= poll(&pfd
, 1, seconds
* 1000 + useconds
/1000);
343 if (error
&& (pfd
.revents
& POLLERR
)) {
346 if (disconnected
&& (pfd
.revents
& POLLHUP
)) {
347 *disconnected
= true;
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
) {
357 for (const auto& fd
: fds
) {
358 if (fd
>= 0 && realFDs
.count(fd
) == 0) {
363 std::vector
<struct pollfd
> pfds(realFDs
.size());
364 memset(pfds
.data(), 0, realFDs
.size()*sizeof(struct pollfd
));
366 for (const auto& fd
: realFDs
) {
368 pfds
[ctr
].events
= POLLIN
;
374 ret
= poll(pfds
.data(), realFDs
.size(), seconds
* 1000 + useconds
/1000);
376 ret
= poll(pfds
.data(), realFDs
.size(), -1);
381 for (const auto& pfd
: pfds
) {
382 if (pfd
.revents
& POLLIN
) {
383 pollinFDs
.insert(pfd
.fd
);
386 set
<int>::const_iterator
it(pollinFDs
.begin());
387 advance(it
, random() % pollinFDs
.size());
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
)
397 struct pollfd pfds
[2];
398 memset(&pfds
[0], 0, 2*sizeof(struct pollfd
));
402 pfds
[0].events
= pfds
[1].events
= POLLIN
;
404 int nsocks
= 1 + (fd2
>= 0); // fd2 can optionally be -1
407 ret
= poll(pfds
, nsocks
, seconds
* 1000 + useconds
/1000);
409 ret
= poll(pfds
, nsocks
, -1);
413 if((pfds
[0].revents
& POLLIN
) && !(pfds
[1].revents
& POLLIN
))
415 else if((pfds
[1].revents
& POLLIN
) && !(pfds
[0].revents
& POLLIN
))
418 *fd
= pfds
[random()%2].fd
;
421 *fd
= -1; // should never happen
427 string
humanDuration(time_t passed
)
431 ret
<<passed
<<" seconds";
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";
439 ret
<<std::setprecision(3)<<passed
/(86400*30.41)<<" months";
446 // set(); // saves lots of gettimeofday calls
447 d_set
.tv_sec
=d_set
.tv_usec
=0;
455 const string
unquotify(const string
&item
)
460 string::size_type bpos
=0, epos
=item
.size();
465 if(item
[epos
-1]=='"')
468 return item
.substr(bpos
,epos
-bpos
);
471 void stripLine(string
&line
)
473 string::size_type pos
=line
.find_first_of("\r\n");
474 if(pos
!=string::npos
) {
479 string
urlEncode(const string
&text
)
482 for(string::const_iterator i
=text
.begin();i
!=text
.end();++i
)
483 if(*i
==' ')ret
.append("%20");
484 else ret
.append(1,*i
);
490 #ifndef MAXHOSTNAMELEN
491 #define MAXHOSTNAMELEN 255
494 char tmp
[MAXHOSTNAMELEN
];
495 if(gethostname(tmp
, MAXHOSTNAMELEN
))
508 string
uitoa(unsigned int i
) // MSVC 6 doesn't grok overloading (un)signed
515 string
bitFlip(const string
&str
)
517 string::size_type pos
=0, epos
=str
.size();
520 for(;pos
< epos
; ++pos
)
521 ret
.append(1, ~str
[pos
]);
525 string
stringerror(int err
)
527 return strerror(err
);
532 return strerror(errno
);
535 void cleanSlashes(string
&str
)
537 string::const_iterator i
;
539 for(i
=str
.begin();i
!=str
.end();++i
) {
540 if(*i
=='/' && i
!=str
.begin() && *(i
-1)=='/')
548 bool IpToU32(const string
&str
, uint32_t *ip
)
556 if(inet_aton(str
.c_str(), &inp
)) {
563 string
U32ToIP(uint32_t val
)
566 snprintf(tmp
, sizeof(tmp
), "%u.%u.%u.%u",
575 string
makeHexDump(const string
& str
)
579 ret
.reserve((int)(str
.size()*2.2));
581 for(string::size_type n
=0;n
<str
.size();++n
) {
582 snprintf(tmp
, sizeof(tmp
), "%02x ", (unsigned char)str
[n
]);
588 // shuffle, maintaining some semblance of order
589 void shuffle(vector
<DNSZoneRecord
>& rrs
)
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
595 for(second
=first
;second
!=rrs
.end();++second
)
596 if(second
->dr
.d_place
!=DNSResourceRecord::ANSWER
)
600 random_shuffle(first
,second
);
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
606 for(second
=first
;second
!=rrs
.end();++second
)
607 if(second
->dr
.d_place
!=DNSResourceRecord::ADDITIONAL
)
611 random_shuffle(first
,second
);
613 // we don't shuffle the rest
617 // shuffle, maintaining some semblance of order
618 void shuffle(vector
<DNSRecord
>& rrs
)
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
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
629 random_shuffle(first
,second
);
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
635 for(second
=first
; second
!=rrs
.end(); ++second
)
636 if(second
->d_place
!=DNSResourceRecord::ADDITIONAL
)
640 random_shuffle(first
,second
);
642 // we don't shuffle the rest
645 static uint16_t mapTypesToOrder(uint16_t type
)
647 if(type
== QType::CNAME
)
649 if(type
== QType::RRSIG
)
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
)
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
));
665 void normalizeTV(struct timeval
& tv
)
667 if(tv
.tv_usec
> 1000000) {
671 else if(tv
.tv_usec
< 0) {
677 const struct timeval
operator+(const struct timeval
& lhs
, const struct timeval
& rhs
)
680 ret
.tv_sec
=lhs
.tv_sec
+ rhs
.tv_sec
;
681 ret
.tv_usec
=lhs
.tv_usec
+ rhs
.tv_usec
;
686 const struct timeval
operator-(const struct timeval
& lhs
, const struct timeval
& rhs
)
689 ret
.tv_sec
=lhs
.tv_sec
- rhs
.tv_sec
;
690 ret
.tv_usec
=lhs
.tv_usec
- rhs
.tv_usec
;
695 pair
<string
, string
> splitField(const string
& inp
, char sepa
)
697 pair
<string
, string
> ret
;
698 string::size_type cpos
=inp
.find(sepa
);
699 if(cpos
==string::npos
)
702 ret
.first
=inp
.substr(0, cpos
);
703 ret
.second
=inp
.substr(cpos
+1);
708 int logFacilityToLOG(unsigned int facility
)
732 string
stripDot(const string
& dom
)
737 if(dom
[dom
.size()-1]!='.')
740 return dom
.substr(0,dom
.size()-1);
745 int makeIPv6sockaddr(const std::string
& addr
, struct sockaddr_in6
* ret
)
749 string
ourAddr(addr
);
750 bool portSet
= false;
752 if(addr
[0]=='[') { // [::]:53 style address
753 string::size_type pos
= addr
.find(']');
754 if(pos
== string::npos
)
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]!=':')
761 port
= pdns_stou(addr
.substr(pos
+2));
764 catch(const std::out_of_range
&) {
769 ret
->sin6_scope_id
=0;
770 ret
->sin6_family
=AF_INET6
;
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
));
777 hints
.ai_family
= AF_INET6
;
778 hints
.ai_flags
= AI_NUMERICHOST
;
781 // getaddrinfo has anomalous return codes, anything nonzero is an error, positive or negative
782 if((error
=getaddrinfo(ourAddr
.c_str(), 0, &hints
, &res
))) {
786 memcpy(ret
, res
->ai_addr
, res
->ai_addrlen
);
794 ret
->sin6_port
= htons(port
);
800 int makeIPv4sockaddr(const std::string
& str
, struct sockaddr_in
* ret
)
807 string::size_type pos
= str
.find(':');
808 if(pos
== string::npos
) { // no port specified, not touching the port
809 if(inet_aton(str
.c_str(), &inp
)) {
810 ret
->sin_addr
.s_addr
=inp
.s_addr
;
815 if(!*(str
.c_str() + pos
+ 1)) // trailing :
818 char *eptr
= (char*)str
.c_str() + str
.size();
819 int port
= strtol(str
.c_str() + pos
+ 1, &eptr
, 10);
820 if (port
< 0 || port
> 65535)
826 ret
->sin_port
= htons(port
);
827 if(inet_aton(str
.substr(0, pos
).c_str(), &inp
)) {
828 ret
->sin_addr
.s_addr
=inp
.s_addr
;
834 int makeUNsockaddr(const std::string
& path
, struct sockaddr_un
* ret
)
839 memset(ret
, 0, sizeof(struct sockaddr_un
));
840 ret
->sun_family
= AF_UNIX
;
841 if (path
.length() >= sizeof(ret
->sun_path
))
844 path
.copy(ret
->sun_path
, sizeof(ret
->sun_path
), 0);
848 //! read a line of text from a FILE* to a std::string, returns false on 'no data'
849 bool stringfgets(FILE* fp
, std::string
& line
)
855 if(!fgets(buffer
, sizeof(buffer
), fp
))
856 return !line
.empty();
859 } while(!strchr(buffer
, '\n'));
863 bool readFileIfThere(const char* fname
, std::string
* line
)
866 auto fp
= std::unique_ptr
<FILE, int(*)(FILE*)>(fopen(fname
, "r"), fclose
);
869 stringfgets(fp
.get(), *line
);
875 Regex::Regex(const string
&expr
)
877 if(regcomp(&d_preg
, expr
.c_str(), REG_ICASE
|REG_NOSUB
|REG_EXTENDED
))
878 throw PDNSException("Regular expression did not compile");
881 // if you end up here because valgrind told you were are doing something wrong
882 // with msgh->msg_controllen, please refer to https://github.com/PowerDNS/pdns/pull/3962
884 // Note that cmsgbuf should be aligned the same as a struct cmsghdr
885 void addCMsgSrcAddr(struct msghdr
* msgh
, cmsgbuf_aligned
* cmsgbuf
, const ComboAddress
* source
, int itfIndex
)
887 struct cmsghdr
*cmsg
= NULL
;
889 if(source
->sin4
.sin_family
== AF_INET6
) {
890 struct in6_pktinfo
*pkt
;
892 msgh
->msg_control
= cmsgbuf
;
893 #if !defined( __APPLE__ )
894 /* CMSG_SPACE is not a constexpr on macOS */
895 static_assert(CMSG_SPACE(sizeof(*pkt
)) <= sizeof(*cmsgbuf
), "Buffer is too small for in6_pktinfo");
896 #else /* __APPLE__ */
897 if (CMSG_SPACE(sizeof(*pkt
)) > sizeof(*cmsgbuf
)) {
898 throw std::runtime_error("Buffer is too small for in6_pktinfo");
900 #endif /* __APPLE__ */
901 msgh
->msg_controllen
= CMSG_SPACE(sizeof(*pkt
));
903 cmsg
= CMSG_FIRSTHDR(msgh
);
904 cmsg
->cmsg_level
= IPPROTO_IPV6
;
905 cmsg
->cmsg_type
= IPV6_PKTINFO
;
906 cmsg
->cmsg_len
= CMSG_LEN(sizeof(*pkt
));
908 pkt
= (struct in6_pktinfo
*) CMSG_DATA(cmsg
);
909 // Include the padding to stop valgrind complaining about passing uninitialized data
910 memset(pkt
, 0, CMSG_SPACE(sizeof(*pkt
)));
911 pkt
->ipi6_addr
= source
->sin6
.sin6_addr
;
912 pkt
->ipi6_ifindex
= itfIndex
;
915 #if defined(IP_PKTINFO)
916 struct in_pktinfo
*pkt
;
918 msgh
->msg_control
= cmsgbuf
;
919 #if !defined( __APPLE__ )
920 /* CMSG_SPACE is not a constexpr on macOS */
921 static_assert(CMSG_SPACE(sizeof(*pkt
)) <= sizeof(*cmsgbuf
), "Buffer is too small for in_pktinfo");
922 #else /* __APPLE__ */
923 if (CMSG_SPACE(sizeof(*pkt
)) > sizeof(*cmsgbuf
)) {
924 throw std::runtime_error("Buffer is too small for in_pktinfo");
926 #endif /* __APPLE__ */
927 msgh
->msg_controllen
= CMSG_SPACE(sizeof(*pkt
));
929 cmsg
= CMSG_FIRSTHDR(msgh
);
930 cmsg
->cmsg_level
= IPPROTO_IP
;
931 cmsg
->cmsg_type
= IP_PKTINFO
;
932 cmsg
->cmsg_len
= CMSG_LEN(sizeof(*pkt
));
934 pkt
= (struct in_pktinfo
*) CMSG_DATA(cmsg
);
935 // Include the padding to stop valgrind complaining about passing uninitialized data
936 memset(pkt
, 0, CMSG_SPACE(sizeof(*pkt
)));
937 pkt
->ipi_spec_dst
= source
->sin4
.sin_addr
;
938 pkt
->ipi_ifindex
= itfIndex
;
939 #elif defined(IP_SENDSRCADDR)
942 msgh
->msg_control
= cmsgbuf
;
943 #if !defined( __APPLE__ )
944 static_assert(CMSG_SPACE(sizeof(*in
)) <= sizeof(*cmsgbuf
), "Buffer is too small for in_addr");
945 #else /* __APPLE__ */
946 if (CMSG_SPACE(sizeof(*in
)) > sizeof(*cmsgbuf
)) {
947 throw std::runtime_error("Buffer is too small for in_addr");
949 #endif /* __APPLE__ */
950 msgh
->msg_controllen
= CMSG_SPACE(sizeof(*in
));
952 cmsg
= CMSG_FIRSTHDR(msgh
);
953 cmsg
->cmsg_level
= IPPROTO_IP
;
954 cmsg
->cmsg_type
= IP_SENDSRCADDR
;
955 cmsg
->cmsg_len
= CMSG_LEN(sizeof(*in
));
957 // Include the padding to stop valgrind complaining about passing uninitialized data
958 in
= (struct in_addr
*) CMSG_DATA(cmsg
);
959 memset(in
, 0, CMSG_SPACE(sizeof(*in
)));
960 *in
= source
->sin4
.sin_addr
;
965 unsigned int getFilenumLimit(bool hardOrSoft
)
968 if(getrlimit(RLIMIT_NOFILE
, &rlim
) < 0)
969 unixDie("Requesting number of available file descriptors");
970 return hardOrSoft
? rlim
.rlim_max
: rlim
.rlim_cur
;
973 void setFilenumLimit(unsigned int lim
)
977 if(getrlimit(RLIMIT_NOFILE
, &rlim
) < 0)
978 unixDie("Requesting number of available file descriptors");
980 if(setrlimit(RLIMIT_NOFILE
, &rlim
) < 0)
981 unixDie("Setting number of available file descriptors");
984 #define burtlemix(a,b,c) \
986 a -= b; a -= c; a ^= (c>>13); \
987 b -= c; b -= a; b ^= (a<<8); \
988 c -= a; c -= b; c ^= (b>>13); \
989 a -= b; a -= c; a ^= (c>>12); \
990 b -= c; b -= a; b ^= (a<<16); \
991 c -= a; c -= b; c ^= (b>>5); \
992 a -= b; a -= c; a ^= (c>>3); \
993 b -= c; b -= a; b ^= (a<<10); \
994 c -= a; c -= b; c ^= (b>>15); \
997 uint32_t burtle(const unsigned char* k
, uint32_t length
, uint32_t initval
)
1001 /* Set up the internal state */
1003 a
= b
= 0x9e3779b9; /* the golden ratio; an arbitrary value */
1004 c
= initval
; /* the previous hash value */
1006 /*---------------------------------------- handle most of the key */
1008 a
+= (k
[0] +((uint32_t)k
[1]<<8) +((uint32_t)k
[2]<<16) +((uint32_t)k
[3]<<24));
1009 b
+= (k
[4] +((uint32_t)k
[5]<<8) +((uint32_t)k
[6]<<16) +((uint32_t)k
[7]<<24));
1010 c
+= (k
[8] +((uint32_t)k
[9]<<8) +((uint32_t)k
[10]<<16)+((uint32_t)k
[11]<<24));
1015 /*------------------------------------- handle the last 11 bytes */
1017 switch(len
) { /* all the case statements fall through */
1018 case 11: c
+=((uint32_t)k
[10]<<24);
1020 case 10: c
+=((uint32_t)k
[9]<<16);
1022 case 9 : c
+=((uint32_t)k
[8]<<8);
1023 /* the first byte of c is reserved for the length */
1025 case 8 : b
+=((uint32_t)k
[7]<<24);
1027 case 7 : b
+=((uint32_t)k
[6]<<16);
1029 case 6 : b
+=((uint32_t)k
[5]<<8);
1033 case 4 : a
+=((uint32_t)k
[3]<<24);
1035 case 3 : a
+=((uint32_t)k
[2]<<16);
1037 case 2 : a
+=((uint32_t)k
[1]<<8);
1040 /* case 0: nothing left to add */
1043 /*-------------------------------------------- report the result */
1047 uint32_t burtleCI(const unsigned char* k
, uint32_t length
, uint32_t initval
)
1051 /* Set up the internal state */
1053 a
= b
= 0x9e3779b9; /* the golden ratio; an arbitrary value */
1054 c
= initval
; /* the previous hash value */
1056 /*---------------------------------------- handle most of the key */
1058 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));
1059 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));
1060 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));
1065 /*------------------------------------- handle the last 11 bytes */
1067 switch(len
) { /* all the case statements fall through */
1068 case 11: c
+=((uint32_t)dns_tolower(k
[10])<<24);
1070 case 10: c
+=((uint32_t)dns_tolower(k
[9])<<16);
1072 case 9 : c
+=((uint32_t)dns_tolower(k
[8])<<8);
1073 /* the first byte of c is reserved for the length */
1075 case 8 : b
+=((uint32_t)dns_tolower(k
[7])<<24);
1077 case 7 : b
+=((uint32_t)dns_tolower(k
[6])<<16);
1079 case 6 : b
+=((uint32_t)dns_tolower(k
[5])<<8);
1081 case 5 : b
+=dns_tolower(k
[4]);
1083 case 4 : a
+=((uint32_t)dns_tolower(k
[3])<<24);
1085 case 3 : a
+=((uint32_t)dns_tolower(k
[2])<<16);
1087 case 2 : a
+=((uint32_t)dns_tolower(k
[1])<<8);
1089 case 1 : a
+=dns_tolower(k
[0]);
1090 /* case 0: nothing left to add */
1093 /*-------------------------------------------- report the result */
1098 bool setSocketTimestamps(int fd
)
1102 return setsockopt(fd
, SOL_SOCKET
, SO_TIMESTAMP
, (char*)&on
, sizeof(on
)) == 0;
1104 return true; // we pretend this happened.
1108 bool setTCPNoDelay(int sock
)
1111 return setsockopt(sock
, /* socket affected */
1112 IPPROTO_TCP
, /* set option at TCP level */
1113 TCP_NODELAY
, /* name of option */
1114 (char *) &flag
, /* the cast is historical cruft */
1115 sizeof(flag
)) == 0; /* length of option value */
1119 bool setNonBlocking(int sock
)
1121 int flags
=fcntl(sock
,F_GETFL
,0);
1122 if(flags
<0 || fcntl(sock
, F_SETFL
,flags
|O_NONBLOCK
) <0)
1127 bool setBlocking(int sock
)
1129 int flags
=fcntl(sock
,F_GETFL
,0);
1130 if(flags
<0 || fcntl(sock
, F_SETFL
,flags
&(~O_NONBLOCK
)) <0)
1135 bool setReuseAddr(int sock
)
1138 if (setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, (char*)&tmp
, static_cast<unsigned>(sizeof tmp
))<0)
1139 throw PDNSException(string("Setsockopt failed: ")+stringerror());
1143 bool isNonBlocking(int sock
)
1145 int flags
=fcntl(sock
,F_GETFL
,0);
1146 return flags
& O_NONBLOCK
;
1149 bool setReceiveSocketErrors(int sock
, int af
)
1153 if (af
== AF_INET
) {
1154 ret
= setsockopt(sock
, IPPROTO_IP
, IP_RECVERR
, &tmp
, sizeof(tmp
));
1156 ret
= setsockopt(sock
, IPPROTO_IPV6
, IPV6_RECVERR
, &tmp
, sizeof(tmp
));
1159 throw PDNSException(string("Setsockopt failed: ") + stringerror());
1166 int closesocket( int socket
)
1168 int ret
=::close(socket
);
1169 if(ret
< 0 && errno
== ECONNRESET
) // see ticket 192, odd BSD behaviour
1172 throw PDNSException("Error closing socket: "+stringerror());
1176 bool setCloseOnExec(int sock
)
1178 int flags
=fcntl(sock
,F_GETFD
,0);
1179 if(flags
<0 || fcntl(sock
, F_SETFD
,flags
|FD_CLOEXEC
) <0)
1184 string
getMACAddress(const ComboAddress
& ca
)
1188 ifstream
ifs("/proc/net/arp");
1192 string match
=ca
.toString()+' ';
1193 while(getline(ifs
, line
)) {
1194 if(boost::starts_with(line
, match
)) {
1195 vector
<string
> parts
;
1196 stringtok(parts
, line
, " \n\t\r");
1197 if(parts
.size() < 4)
1199 unsigned int tmp
[6];
1200 sscanf(parts
[3].c_str(), "%02x:%02x:%02x:%02x:%02x:%02x", tmp
, tmp
+1, tmp
+2, tmp
+3, tmp
+4, tmp
+5);
1201 for(int i
= 0 ; i
< 6 ; ++i
)
1202 ret
.append(1, (char)tmp
[i
]);
1210 uint64_t udpErrorStats(const std::string
& str
)
1213 ifstream
ifs("/proc/net/snmp");
1217 vector
<string
> parts
;
1218 while(getline(ifs
,line
)) {
1219 if(boost::starts_with(line
, "Udp: ") && isdigit(line
[5])) {
1220 stringtok(parts
, line
, " \n\t\r");
1221 if(parts
.size() < 7)
1223 if(str
=="udp-rcvbuf-errors")
1224 return std::stoull(parts
[5]);
1225 else if(str
=="udp-sndbuf-errors")
1226 return std::stoull(parts
[6]);
1227 else if(str
=="udp-noport-errors")
1228 return std::stoull(parts
[2]);
1229 else if(str
=="udp-in-errors")
1230 return std::stoull(parts
[3]);
1239 uint64_t getCPUIOWait(const std::string
& str
)
1242 ifstream
ifs("/proc/stat");
1248 vector
<string
> parts
;
1249 while (getline(ifs
, line
)) {
1250 if (boost::starts_with(line
, "cpu ")) {
1251 stringtok(parts
, line
, " \n\t\r");
1253 if (parts
.size() < 6) {
1257 return std::stoull(parts
[5]);
1264 uint64_t getCPUSteal(const std::string
& str
)
1267 ifstream
ifs("/proc/stat");
1273 vector
<string
> parts
;
1274 while (getline(ifs
, line
)) {
1275 if (boost::starts_with(line
, "cpu ")) {
1276 stringtok(parts
, line
, " \n\t\r");
1278 if (parts
.size() < 9) {
1282 return std::stoull(parts
[8]);
1289 bool getTSIGHashEnum(const DNSName
& algoName
, TSIGHashEnum
& algoEnum
)
1291 if (algoName
== DNSName("hmac-md5.sig-alg.reg.int") || algoName
== DNSName("hmac-md5"))
1292 algoEnum
= TSIG_MD5
;
1293 else if (algoName
== DNSName("hmac-sha1"))
1294 algoEnum
= TSIG_SHA1
;
1295 else if (algoName
== DNSName("hmac-sha224"))
1296 algoEnum
= TSIG_SHA224
;
1297 else if (algoName
== DNSName("hmac-sha256"))
1298 algoEnum
= TSIG_SHA256
;
1299 else if (algoName
== DNSName("hmac-sha384"))
1300 algoEnum
= TSIG_SHA384
;
1301 else if (algoName
== DNSName("hmac-sha512"))
1302 algoEnum
= TSIG_SHA512
;
1303 else if (algoName
== DNSName("gss-tsig"))
1304 algoEnum
= TSIG_GSS
;
1311 DNSName
getTSIGAlgoName(TSIGHashEnum
& algoEnum
)
1314 case TSIG_MD5
: return DNSName("hmac-md5.sig-alg.reg.int.");
1315 case TSIG_SHA1
: return DNSName("hmac-sha1.");
1316 case TSIG_SHA224
: return DNSName("hmac-sha224.");
1317 case TSIG_SHA256
: return DNSName("hmac-sha256.");
1318 case TSIG_SHA384
: return DNSName("hmac-sha384.");
1319 case TSIG_SHA512
: return DNSName("hmac-sha512.");
1320 case TSIG_GSS
: return DNSName("gss-tsig.");
1322 throw PDNSException("getTSIGAlgoName does not understand given algorithm, please fix!");
1325 uint64_t getOpenFileDescriptors(const std::string
&)
1328 DIR* dirhdl
=opendir(("/proc/"+std::to_string(getpid())+"/fd/").c_str());
1332 struct dirent
*entry
;
1334 while((entry
= readdir(dirhdl
))) {
1337 num
= pdns_stou(entry
->d_name
);
1339 continue; // was not a number.
1341 if(std::to_string(num
) == entry
->d_name
)
1352 uint64_t getRealMemoryUsage(const std::string
&)
1355 ifstream
ifs("/proc/self/statm");
1359 uint64_t size
, resident
, shared
, text
, lib
, data
;
1360 ifs
>> size
>> resident
>> shared
>> text
>> lib
>> data
;
1362 return data
* getpagesize();
1365 if (getrusage(RUSAGE_SELF
, &ru
) != 0)
1367 return ru
.ru_maxrss
* 1024;
1372 uint64_t getSpecialMemoryUsage(const std::string
&)
1375 ifstream
ifs("/proc/self/smaps");
1380 string
header("Private_Dirty:");
1381 while(getline(ifs
, line
)) {
1382 if(boost::starts_with(line
, header
)) {
1383 bytes
+= std::stoull(line
.substr(header
.length() + 1))*1024;
1392 uint64_t getCPUTimeUser(const std::string
&)
1395 getrusage(RUSAGE_SELF
, &ru
);
1396 return (ru
.ru_utime
.tv_sec
*1000ULL + ru
.ru_utime
.tv_usec
/1000);
1399 uint64_t getCPUTimeSystem(const std::string
&)
1402 getrusage(RUSAGE_SELF
, &ru
);
1403 return (ru
.ru_stime
.tv_sec
*1000ULL + ru
.ru_stime
.tv_usec
/1000);
1406 double DiffTime(const struct timespec
& first
, const struct timespec
& second
)
1408 int seconds
=second
.tv_sec
- first
.tv_sec
;
1409 int nseconds
=second
.tv_nsec
- first
.tv_nsec
;
1413 nseconds
+=1000000000;
1415 return seconds
+ nseconds
/1000000000.0;
1418 double DiffTime(const struct timeval
& first
, const struct timeval
& second
)
1420 int seconds
=second
.tv_sec
- first
.tv_sec
;
1421 int useconds
=second
.tv_usec
- first
.tv_usec
;
1427 return seconds
+ useconds
/1000000.0;
1430 uid_t
strToUID(const string
&str
)
1433 const char * cstr
= str
.c_str();
1434 struct passwd
* pwd
= getpwnam(cstr
);
1442 catch(std::exception
& e
) {
1443 throw runtime_error((boost::format("Error: Unable to parse user ID %s") % cstr
).str() );
1446 if (val
< std::numeric_limits
<uid_t
>::min() || val
> std::numeric_limits
<uid_t
>::max()) {
1447 throw runtime_error((boost::format("Error: Unable to parse user ID %s") % cstr
).str() );
1450 result
= static_cast<uid_t
>(val
);
1453 result
= pwd
->pw_uid
;
1459 gid_t
strToGID(const string
&str
)
1462 const char * cstr
= str
.c_str();
1463 struct group
* grp
= getgrnam(cstr
);
1471 catch(std::exception
& e
) {
1472 throw runtime_error((boost::format("Error: Unable to parse group ID %s") % cstr
).str() );
1475 if (val
< std::numeric_limits
<gid_t
>::min() || val
> std::numeric_limits
<gid_t
>::max()) {
1476 throw runtime_error((boost::format("Error: Unable to parse group ID %s") % cstr
).str() );
1479 result
= static_cast<gid_t
>(val
);
1482 result
= grp
->gr_gid
;
1488 unsigned int pdns_stou(const std::string
& str
, size_t * idx
, int base
)
1490 if (str
.empty()) return 0; // compatibility
1491 unsigned long result
;
1493 result
= std::stoul(str
, idx
, base
);
1495 catch(std::invalid_argument
& e
) {
1496 throw std::invalid_argument(string(e
.what()) + "; (invalid argument during std::stoul); data was \""+str
+"\"");
1498 catch(std::out_of_range
& e
) {
1499 throw std::out_of_range(string(e
.what()) + "; (out of range during std::stoul); data was \""+str
+"\"");
1501 if (result
> std::numeric_limits
<unsigned int>::max()) {
1502 throw std::out_of_range("stoul returned result out of unsigned int range; data was \""+str
+"\"");
1504 return static_cast<unsigned int>(result
);
1507 bool isSettingThreadCPUAffinitySupported()
1509 #ifdef HAVE_PTHREAD_SETAFFINITY_NP
1516 int mapThreadToCPUList(pthread_t tid
, const std::set
<int>& cpus
)
1518 #ifdef HAVE_PTHREAD_SETAFFINITY_NP
1521 cpuset
= cpuset_create();
1522 for (const auto cpuID
: cpus
) {
1523 cpuset_set(cpuID
, cpuset
);
1526 return pthread_setaffinity_np(tid
,
1527 cpuset_size(cpuset
),
1531 # define cpu_set_t cpuset_t
1535 for (const auto cpuID
: cpus
) {
1536 CPU_SET(cpuID
, &cpuset
);
1539 return pthread_setaffinity_np(tid
,
1545 #endif /* HAVE_PTHREAD_SETAFFINITY_NP */
1548 std::vector
<ComboAddress
> getResolvers(const std::string
& resolvConfPath
)
1550 std::vector
<ComboAddress
> results
;
1552 ifstream
ifs(resolvConfPath
);
1558 while(std::getline(ifs
, line
)) {
1559 boost::trim_right_if(line
, is_any_of(" \r\n\x1a"));
1560 boost::trim_left(line
); // leading spaces, let's be nice
1562 string::size_type tpos
= line
.find_first_of(";#");
1563 if (tpos
!= string::npos
) {
1567 if (boost::starts_with(line
, "nameserver ") || boost::starts_with(line
, "nameserver\t")) {
1568 vector
<string
> parts
;
1569 stringtok(parts
, line
, " \t,"); // be REALLY nice
1570 for(vector
<string
>::const_iterator iter
= parts
.begin() + 1; iter
!= parts
.end(); ++iter
) {
1572 results
.emplace_back(*iter
, 53);
1584 size_t getPipeBufferSize(int fd
)
1587 int res
= fcntl(fd
, F_GETPIPE_SZ
);
1595 #endif /* F_GETPIPE_SZ */
1598 bool setPipeBufferSize(int fd
, size_t size
)
1601 if (size
> std::numeric_limits
<int>::max()) {
1605 int newSize
= static_cast<int>(size
);
1606 int res
= fcntl(fd
, F_SETPIPE_SZ
, newSize
);
1614 #endif /* F_SETPIPE_SZ */