]>
git.ipfire.org Git - thirdparty/pdns.git/blob - pdns/misc.cc
196a4bcf4822bd309f069cc0ccb5c49108647503
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);
200 struct tm
* tm
= localtime(&now
);
202 // YYYY-mm-dd HH:MM:SS TZOFF
203 strftime(buffer
, sizeof(buffer
), "%F %T %z", tm
);
204 buffer
[sizeof(buffer
)-1] = '\0';
208 uint16_t getShort(const unsigned char *p
)
210 return p
[0] * 256 + p
[1];
214 uint16_t getShort(const char *p
)
216 return getShort((const unsigned char *)p
);
219 uint32_t getLong(const unsigned char* p
)
221 return (p
[0]<<24) + (p
[1]<<16) + (p
[2]<<8) + p
[3];
224 uint32_t getLong(const char* p
)
226 return getLong((unsigned char *)p
);
229 static bool ciEqual(const string
& a
, const string
& b
)
231 if(a
.size()!=b
.size())
234 string::size_type pos
=0, epos
=a
.size();
235 for(;pos
< epos
; ++pos
)
236 if(dns_tolower(a
[pos
])!=dns_tolower(b
[pos
]))
241 /** does domain end on suffix? Is smart about "wwwds9a.nl" "ds9a.nl" not matching */
242 static bool endsOn(const string
&domain
, const string
&suffix
)
244 if( suffix
.empty() || ciEqual(domain
, suffix
) )
247 if(domain
.size()<=suffix
.size())
250 string::size_type dpos
=domain
.size()-suffix
.size()-1, spos
=0;
252 if(domain
[dpos
++]!='.')
255 for(; dpos
< domain
.size(); ++dpos
, ++spos
)
256 if(dns_tolower(domain
[dpos
]) != dns_tolower(suffix
[spos
]))
262 /** strips a domain suffix from a domain, returns true if it stripped */
263 bool stripDomainSuffix(string
*qname
, const string
&domain
)
265 if(!endsOn(*qname
, domain
))
268 if(toLower(*qname
)==toLower(domain
))
271 if((*qname
)[qname
->size()-domain
.size()-1]!='.')
274 qname
->resize(qname
->size()-domain
.size()-1);
279 static void parseService4(const string
&descr
, ServiceTuple
&st
)
282 stringtok(parts
,descr
,":");
284 throw PDNSException("Unable to parse '"+descr
+"' as a service");
287 st
.port
=pdns_stou(parts
[1]);
290 static void parseService6(const string
&descr
, ServiceTuple
&st
)
292 string::size_type pos
=descr
.find(']');
293 if(pos
== string::npos
)
294 throw PDNSException("Unable to parse '"+descr
+"' as an IPv6 service");
296 st
.host
=descr
.substr(1, pos
-1);
297 if(pos
+ 2 < descr
.length())
298 st
.port
=pdns_stou(descr
.substr(pos
+2));
302 void parseService(const string
&descr
, ServiceTuple
&st
)
305 throw PDNSException("Unable to parse '"+descr
+"' as a service");
307 vector
<string
> parts
;
308 stringtok(parts
, descr
, ":");
311 parseService6(descr
, st
);
313 else if(descr
[0]==':' || parts
.size() > 2 || descr
.find("::") != string::npos
) {
317 parseService4(descr
, st
);
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
322 int waitForData(int fd
, int seconds
, int useconds
)
324 return waitForRWData(fd
, true, seconds
, useconds
);
327 int waitForRWData(int fd
, bool waitForRead
, int seconds
, int useconds
, bool* error
, bool* disconnected
)
332 memset(&pfd
, 0, sizeof(pfd
));
340 ret
= poll(&pfd
, 1, seconds
* 1000 + useconds
/1000);
342 if (error
&& (pfd
.revents
& POLLERR
)) {
345 if (disconnected
&& (pfd
.revents
& POLLHUP
)) {
346 *disconnected
= true;
353 // returns -1 in case of error, 0 if no data is available, 1 if there is. In the first two cases, errno is set
354 int waitForMultiData(const set
<int>& fds
, const int seconds
, const int useconds
, int* fdOut
) {
356 for (const auto& fd
: fds
) {
357 if (fd
>= 0 && realFDs
.count(fd
) == 0) {
362 std::vector
<struct pollfd
> pfds(realFDs
.size());
363 memset(pfds
.data(), 0, realFDs
.size()*sizeof(struct pollfd
));
365 for (const auto& fd
: realFDs
) {
367 pfds
[ctr
].events
= POLLIN
;
373 ret
= poll(pfds
.data(), realFDs
.size(), seconds
* 1000 + useconds
/1000);
375 ret
= poll(pfds
.data(), realFDs
.size(), -1);
380 for (const auto& pfd
: pfds
) {
381 if (pfd
.revents
& POLLIN
) {
382 pollinFDs
.insert(pfd
.fd
);
385 set
<int>::const_iterator
it(pollinFDs
.begin());
386 advance(it
, random() % pollinFDs
.size());
391 // returns -1 in case of error, 0 if no data is available, 1 if there is. In the first two cases, errno is set
392 int waitFor2Data(int fd1
, int fd2
, int seconds
, int useconds
, int*fd
)
396 struct pollfd pfds
[2];
397 memset(&pfds
[0], 0, 2*sizeof(struct pollfd
));
401 pfds
[0].events
= pfds
[1].events
= POLLIN
;
403 int nsocks
= 1 + (fd2
>= 0); // fd2 can optionally be -1
406 ret
= poll(pfds
, nsocks
, seconds
* 1000 + useconds
/1000);
408 ret
= poll(pfds
, nsocks
, -1);
412 if((pfds
[0].revents
& POLLIN
) && !(pfds
[1].revents
& POLLIN
))
414 else if((pfds
[1].revents
& POLLIN
) && !(pfds
[0].revents
& POLLIN
))
417 *fd
= pfds
[random()%2].fd
;
420 *fd
= -1; // should never happen
426 string
humanDuration(time_t passed
)
430 ret
<<passed
<<" seconds";
432 ret
<<std::setprecision(2)<<passed
/60.0<<" minutes";
433 else if(passed
<86400)
434 ret
<<std::setprecision(3)<<passed
/3600.0<<" hours";
435 else if(passed
<(86400*30.41))
436 ret
<<std::setprecision(3)<<passed
/86400.0<<" days";
438 ret
<<std::setprecision(3)<<passed
/(86400*30.41)<<" months";
445 // set(); // saves lots of gettimeofday calls
446 d_set
.tv_sec
=d_set
.tv_usec
=0;
449 DTime::DTime(const DTime
&dt
)
459 const string
unquotify(const string
&item
)
464 string::size_type bpos
=0, epos
=item
.size();
469 if(item
[epos
-1]=='"')
472 return item
.substr(bpos
,epos
-bpos
);
475 void stripLine(string
&line
)
477 string::size_type pos
=line
.find_first_of("\r\n");
478 if(pos
!=string::npos
) {
483 string
urlEncode(const string
&text
)
486 for(string::const_iterator i
=text
.begin();i
!=text
.end();++i
)
487 if(*i
==' ')ret
.append("%20");
488 else ret
.append(1,*i
);
494 #ifndef MAXHOSTNAMELEN
495 #define MAXHOSTNAMELEN 255
498 char tmp
[MAXHOSTNAMELEN
];
499 if(gethostname(tmp
, MAXHOSTNAMELEN
))
512 string
uitoa(unsigned int i
) // MSVC 6 doesn't grok overloading (un)signed
519 string
bitFlip(const string
&str
)
521 string::size_type pos
=0, epos
=str
.size();
524 for(;pos
< epos
; ++pos
)
525 ret
.append(1, ~str
[pos
]);
531 return strerror(errno
);
534 string
netstringerror()
536 return stringerror();
539 void cleanSlashes(string
&str
)
541 string::const_iterator i
;
543 for(i
=str
.begin();i
!=str
.end();++i
) {
544 if(*i
=='/' && i
!=str
.begin() && *(i
-1)=='/')
552 bool IpToU32(const string
&str
, uint32_t *ip
)
560 if(inet_aton(str
.c_str(), &inp
)) {
567 string
U32ToIP(uint32_t val
)
570 snprintf(tmp
, sizeof(tmp
)-1, "%u.%u.%u.%u",
579 string
makeHexDump(const string
& str
)
583 ret
.reserve((int)(str
.size()*2.2));
585 for(string::size_type n
=0;n
<str
.size();++n
) {
586 sprintf(tmp
,"%02x ", (unsigned char)str
[n
]);
592 // shuffle, maintaining some semblance of order
593 void shuffle(vector
<DNSZoneRecord
>& rrs
)
595 vector
<DNSZoneRecord
>::iterator first
, second
;
596 for(first
=rrs
.begin();first
!=rrs
.end();++first
)
597 if(first
->dr
.d_place
==DNSResourceRecord::ANSWER
&& first
->dr
.d_type
!= QType::CNAME
) // CNAME must come first
599 for(second
=first
;second
!=rrs
.end();++second
)
600 if(second
->dr
.d_place
!=DNSResourceRecord::ANSWER
)
604 random_shuffle(first
,second
);
606 // now shuffle the additional records
607 for(first
=second
;first
!=rrs
.end();++first
)
608 if(first
->dr
.d_place
==DNSResourceRecord::ADDITIONAL
&& first
->dr
.d_type
!= QType::CNAME
) // CNAME must come first
610 for(second
=first
;second
!=rrs
.end();++second
)
611 if(second
->dr
.d_place
!=DNSResourceRecord::ADDITIONAL
)
615 random_shuffle(first
,second
);
617 // we don't shuffle the rest
621 // shuffle, maintaining some semblance of order
622 void shuffle(vector
<DNSRecord
>& rrs
)
624 vector
<DNSRecord
>::iterator first
, second
;
625 for(first
=rrs
.begin();first
!=rrs
.end();++first
)
626 if(first
->d_place
==DNSResourceRecord::ANSWER
&& first
->d_type
!= QType::CNAME
) // CNAME must come first
628 for(second
=first
;second
!=rrs
.end();++second
)
629 if(second
->d_place
!=DNSResourceRecord::ANSWER
|| second
->d_type
== QType::RRSIG
) // leave RRSIGs at the end
633 random_shuffle(first
,second
);
635 // now shuffle the additional records
636 for(first
=second
;first
!=rrs
.end();++first
)
637 if(first
->d_place
==DNSResourceRecord::ADDITIONAL
&& first
->d_type
!= QType::CNAME
) // CNAME must come first
639 for(second
=first
; second
!=rrs
.end(); ++second
)
640 if(second
->d_place
!=DNSResourceRecord::ADDITIONAL
)
644 random_shuffle(first
,second
);
646 // we don't shuffle the rest
649 static uint16_t mapTypesToOrder(uint16_t type
)
651 if(type
== QType::CNAME
)
653 if(type
== QType::RRSIG
)
659 // make sure rrs is sorted in d_place order to avoid surprises later
660 // then shuffle the parts that desire shuffling
661 void orderAndShuffle(vector
<DNSRecord
>& rrs
)
663 std::stable_sort(rrs
.begin(), rrs
.end(), [](const DNSRecord
&a
, const DNSRecord
& b
) {
664 return std::make_tuple(a
.d_place
, mapTypesToOrder(a
.d_type
)) < std::make_tuple(b
.d_place
, mapTypesToOrder(b
.d_type
));
669 void normalizeTV(struct timeval
& tv
)
671 if(tv
.tv_usec
> 1000000) {
675 else if(tv
.tv_usec
< 0) {
681 const struct timeval
operator+(const struct timeval
& lhs
, const struct timeval
& rhs
)
684 ret
.tv_sec
=lhs
.tv_sec
+ rhs
.tv_sec
;
685 ret
.tv_usec
=lhs
.tv_usec
+ rhs
.tv_usec
;
690 const struct timeval
operator-(const struct timeval
& lhs
, const struct timeval
& rhs
)
693 ret
.tv_sec
=lhs
.tv_sec
- rhs
.tv_sec
;
694 ret
.tv_usec
=lhs
.tv_usec
- rhs
.tv_usec
;
699 pair
<string
, string
> splitField(const string
& inp
, char sepa
)
701 pair
<string
, string
> ret
;
702 string::size_type cpos
=inp
.find(sepa
);
703 if(cpos
==string::npos
)
706 ret
.first
=inp
.substr(0, cpos
);
707 ret
.second
=inp
.substr(cpos
+1);
712 int logFacilityToLOG(unsigned int facility
)
736 string
stripDot(const string
& dom
)
741 if(dom
[dom
.size()-1]!='.')
744 return dom
.substr(0,dom
.size()-1);
749 int makeIPv6sockaddr(const std::string
& addr
, struct sockaddr_in6
* ret
)
753 string
ourAddr(addr
);
754 bool portSet
= false;
756 if(addr
[0]=='[') { // [::]:53 style address
757 string::size_type pos
= addr
.find(']');
758 if(pos
== string::npos
)
760 ourAddr
.assign(addr
.c_str() + 1, pos
-1);
761 if (pos
+ 1 != addr
.size()) { // complete after ], no port specified
762 if (pos
+ 2 > addr
.size() || addr
[pos
+1]!=':')
765 port
= pdns_stou(addr
.substr(pos
+2));
768 catch(const std::out_of_range
&) {
773 ret
->sin6_scope_id
=0;
774 ret
->sin6_family
=AF_INET6
;
776 if(inet_pton(AF_INET6
, ourAddr
.c_str(), (void*)&ret
->sin6_addr
) != 1) {
777 struct addrinfo
* res
;
778 struct addrinfo hints
;
779 memset(&hints
, 0, sizeof(hints
));
781 hints
.ai_family
= AF_INET6
;
782 hints
.ai_flags
= AI_NUMERICHOST
;
785 // getaddrinfo has anomalous return codes, anything nonzero is an error, positive or negative
786 if((error
=getaddrinfo(ourAddr
.c_str(), 0, &hints
, &res
))) {
790 memcpy(ret
, res
->ai_addr
, res
->ai_addrlen
);
798 ret
->sin6_port
= htons(port
);
804 int makeIPv4sockaddr(const std::string
& str
, struct sockaddr_in
* ret
)
811 string::size_type pos
= str
.find(':');
812 if(pos
== string::npos
) { // no port specified, not touching the port
813 if(inet_aton(str
.c_str(), &inp
)) {
814 ret
->sin_addr
.s_addr
=inp
.s_addr
;
819 if(!*(str
.c_str() + pos
+ 1)) // trailing :
822 char *eptr
= (char*)str
.c_str() + str
.size();
823 int port
= strtol(str
.c_str() + pos
+ 1, &eptr
, 10);
824 if (port
< 0 || port
> 65535)
830 ret
->sin_port
= htons(port
);
831 if(inet_aton(str
.substr(0, pos
).c_str(), &inp
)) {
832 ret
->sin_addr
.s_addr
=inp
.s_addr
;
838 int makeUNsockaddr(const std::string
& path
, struct sockaddr_un
* ret
)
843 memset(ret
, 0, sizeof(struct sockaddr_un
));
844 ret
->sun_family
= AF_UNIX
;
845 if (path
.length() >= sizeof(ret
->sun_path
))
848 path
.copy(ret
->sun_path
, sizeof(ret
->sun_path
), 0);
852 //! read a line of text from a FILE* to a std::string, returns false on 'no data'
853 bool stringfgets(FILE* fp
, std::string
& line
)
859 if(!fgets(buffer
, sizeof(buffer
), fp
))
860 return !line
.empty();
863 } while(!strchr(buffer
, '\n'));
867 bool readFileIfThere(const char* fname
, std::string
* line
)
870 FILE* fp
= fopen(fname
, "r");
873 stringfgets(fp
, *line
);
878 Regex::Regex(const string
&expr
)
880 if(regcomp(&d_preg
, expr
.c_str(), REG_ICASE
|REG_NOSUB
|REG_EXTENDED
))
881 throw PDNSException("Regular expression did not compile");
884 // if you end up here because valgrind told you were are doing something wrong
885 // with msgh->msg_controllen, please refer to https://github.com/PowerDNS/pdns/pull/3962
887 void addCMsgSrcAddr(struct msghdr
* msgh
, void* cmsgbuf
, const ComboAddress
* source
, int itfIndex
)
889 struct cmsghdr
*cmsg
= NULL
;
891 if(source
->sin4
.sin_family
== AF_INET6
) {
892 struct in6_pktinfo
*pkt
;
894 msgh
->msg_control
= cmsgbuf
;
895 msgh
->msg_controllen
= CMSG_SPACE(sizeof(*pkt
));
897 cmsg
= CMSG_FIRSTHDR(msgh
);
898 cmsg
->cmsg_level
= IPPROTO_IPV6
;
899 cmsg
->cmsg_type
= IPV6_PKTINFO
;
900 cmsg
->cmsg_len
= CMSG_LEN(sizeof(*pkt
));
902 pkt
= (struct in6_pktinfo
*) CMSG_DATA(cmsg
);
903 memset(pkt
, 0, sizeof(*pkt
));
904 pkt
->ipi6_addr
= source
->sin6
.sin6_addr
;
905 pkt
->ipi6_ifindex
= itfIndex
;
908 #if defined(IP_PKTINFO)
909 struct in_pktinfo
*pkt
;
911 msgh
->msg_control
= cmsgbuf
;
912 msgh
->msg_controllen
= CMSG_SPACE(sizeof(*pkt
));
914 cmsg
= CMSG_FIRSTHDR(msgh
);
915 cmsg
->cmsg_level
= IPPROTO_IP
;
916 cmsg
->cmsg_type
= IP_PKTINFO
;
917 cmsg
->cmsg_len
= CMSG_LEN(sizeof(*pkt
));
919 pkt
= (struct in_pktinfo
*) CMSG_DATA(cmsg
);
920 memset(pkt
, 0, sizeof(*pkt
));
921 pkt
->ipi_spec_dst
= source
->sin4
.sin_addr
;
922 pkt
->ipi_ifindex
= itfIndex
;
923 #elif defined(IP_SENDSRCADDR)
926 msgh
->msg_control
= cmsgbuf
;
927 msgh
->msg_controllen
= CMSG_SPACE(sizeof(*in
));
929 cmsg
= CMSG_FIRSTHDR(msgh
);
930 cmsg
->cmsg_level
= IPPROTO_IP
;
931 cmsg
->cmsg_type
= IP_SENDSRCADDR
;
932 cmsg
->cmsg_len
= CMSG_LEN(sizeof(*in
));
934 in
= (struct in_addr
*) CMSG_DATA(cmsg
);
935 *in
= source
->sin4
.sin_addr
;
940 unsigned int getFilenumLimit(bool hardOrSoft
)
943 if(getrlimit(RLIMIT_NOFILE
, &rlim
) < 0)
944 unixDie("Requesting number of available file descriptors");
945 return hardOrSoft
? rlim
.rlim_max
: rlim
.rlim_cur
;
948 void setFilenumLimit(unsigned int lim
)
952 if(getrlimit(RLIMIT_NOFILE
, &rlim
) < 0)
953 unixDie("Requesting number of available file descriptors");
955 if(setrlimit(RLIMIT_NOFILE
, &rlim
) < 0)
956 unixDie("Setting number of available file descriptors");
959 #define burtlemix(a,b,c) \
961 a -= b; a -= c; a ^= (c>>13); \
962 b -= c; b -= a; b ^= (a<<8); \
963 c -= a; c -= b; c ^= (b>>13); \
964 a -= b; a -= c; a ^= (c>>12); \
965 b -= c; b -= a; b ^= (a<<16); \
966 c -= a; c -= b; c ^= (b>>5); \
967 a -= b; a -= c; a ^= (c>>3); \
968 b -= c; b -= a; b ^= (a<<10); \
969 c -= a; c -= b; c ^= (b>>15); \
972 uint32_t burtle(const unsigned char* k
, uint32_t length
, uint32_t initval
)
976 /* Set up the internal state */
978 a
= b
= 0x9e3779b9; /* the golden ratio; an arbitrary value */
979 c
= initval
; /* the previous hash value */
981 /*---------------------------------------- handle most of the key */
983 a
+= (k
[0] +((uint32_t)k
[1]<<8) +((uint32_t)k
[2]<<16) +((uint32_t)k
[3]<<24));
984 b
+= (k
[4] +((uint32_t)k
[5]<<8) +((uint32_t)k
[6]<<16) +((uint32_t)k
[7]<<24));
985 c
+= (k
[8] +((uint32_t)k
[9]<<8) +((uint32_t)k
[10]<<16)+((uint32_t)k
[11]<<24));
990 /*------------------------------------- handle the last 11 bytes */
992 switch(len
) { /* all the case statements fall through */
993 case 11: c
+=((uint32_t)k
[10]<<24);
994 case 10: c
+=((uint32_t)k
[9]<<16);
995 case 9 : c
+=((uint32_t)k
[8]<<8);
996 /* the first byte of c is reserved for the length */
997 case 8 : b
+=((uint32_t)k
[7]<<24);
998 case 7 : b
+=((uint32_t)k
[6]<<16);
999 case 6 : b
+=((uint32_t)k
[5]<<8);
1001 case 4 : a
+=((uint32_t)k
[3]<<24);
1002 case 3 : a
+=((uint32_t)k
[2]<<16);
1003 case 2 : a
+=((uint32_t)k
[1]<<8);
1005 /* case 0: nothing left to add */
1008 /*-------------------------------------------- report the result */
1012 uint32_t burtleCI(const unsigned char* k
, uint32_t length
, uint32_t initval
)
1016 /* Set up the internal state */
1018 a
= b
= 0x9e3779b9; /* the golden ratio; an arbitrary value */
1019 c
= initval
; /* the previous hash value */
1021 /*---------------------------------------- handle most of the key */
1023 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));
1024 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));
1025 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));
1030 /*------------------------------------- handle the last 11 bytes */
1032 switch(len
) { /* all the case statements fall through */
1033 case 11: c
+=((uint32_t)dns_tolower(k
[10])<<24);
1034 case 10: c
+=((uint32_t)dns_tolower(k
[9])<<16);
1035 case 9 : c
+=((uint32_t)dns_tolower(k
[8])<<8);
1036 /* the first byte of c is reserved for the length */
1037 case 8 : b
+=((uint32_t)dns_tolower(k
[7])<<24);
1038 case 7 : b
+=((uint32_t)dns_tolower(k
[6])<<16);
1039 case 6 : b
+=((uint32_t)dns_tolower(k
[5])<<8);
1040 case 5 : b
+=dns_tolower(k
[4]);
1041 case 4 : a
+=((uint32_t)dns_tolower(k
[3])<<24);
1042 case 3 : a
+=((uint32_t)dns_tolower(k
[2])<<16);
1043 case 2 : a
+=((uint32_t)dns_tolower(k
[1])<<8);
1044 case 1 : a
+=dns_tolower(k
[0]);
1045 /* case 0: nothing left to add */
1048 /*-------------------------------------------- report the result */
1053 bool setSocketTimestamps(int fd
)
1057 return setsockopt(fd
, SOL_SOCKET
, SO_TIMESTAMP
, (char*)&on
, sizeof(on
)) == 0;
1059 return true; // we pretend this happened.
1063 bool setTCPNoDelay(int sock
)
1066 return setsockopt(sock
, /* socket affected */
1067 IPPROTO_TCP
, /* set option at TCP level */
1068 TCP_NODELAY
, /* name of option */
1069 (char *) &flag
, /* the cast is historical cruft */
1070 sizeof(flag
)) == 0; /* length of option value */
1074 bool setNonBlocking(int sock
)
1076 int flags
=fcntl(sock
,F_GETFL
,0);
1077 if(flags
<0 || fcntl(sock
, F_SETFL
,flags
|O_NONBLOCK
) <0)
1082 bool setBlocking(int sock
)
1084 int flags
=fcntl(sock
,F_GETFL
,0);
1085 if(flags
<0 || fcntl(sock
, F_SETFL
,flags
&(~O_NONBLOCK
)) <0)
1090 bool setReuseAddr(int sock
)
1093 if (setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, (char*)&tmp
, static_cast<unsigned>(sizeof tmp
))<0)
1094 throw PDNSException(string("Setsockopt failed: ")+strerror(errno
));
1098 bool isNonBlocking(int sock
)
1100 int flags
=fcntl(sock
,F_GETFL
,0);
1101 return flags
& O_NONBLOCK
;
1105 int closesocket( int socket
)
1107 int ret
=::close(socket
);
1108 if(ret
< 0 && errno
== ECONNRESET
) // see ticket 192, odd BSD behaviour
1111 throw PDNSException("Error closing socket: "+stringerror());
1115 bool setCloseOnExec(int sock
)
1117 int flags
=fcntl(sock
,F_GETFD
,0);
1118 if(flags
<0 || fcntl(sock
, F_SETFD
,flags
|FD_CLOEXEC
) <0)
1123 string
getMACAddress(const ComboAddress
& ca
)
1127 ifstream
ifs("/proc/net/arp");
1131 string match
=ca
.toString()+' ';
1132 while(getline(ifs
, line
)) {
1133 if(boost::starts_with(line
, match
)) {
1134 vector
<string
> parts
;
1135 stringtok(parts
, line
, " \n\t\r");
1136 if(parts
.size() < 4)
1138 unsigned int tmp
[6];
1139 sscanf(parts
[3].c_str(), "%02x:%02x:%02x:%02x:%02x:%02x", tmp
, tmp
+1, tmp
+2, tmp
+3, tmp
+4, tmp
+5);
1140 for(int i
= 0 ; i
< 6 ; ++i
)
1141 ret
.append(1, (char)tmp
[i
]);
1149 uint64_t udpErrorStats(const std::string
& str
)
1152 ifstream
ifs("/proc/net/snmp");
1156 vector
<string
> parts
;
1157 while(getline(ifs
,line
)) {
1158 if(boost::starts_with(line
, "Udp: ") && isdigit(line
[5])) {
1159 stringtok(parts
, line
, " \n\t\r");
1160 if(parts
.size() < 7)
1162 if(str
=="udp-rcvbuf-errors")
1163 return std::stoull(parts
[5]);
1164 else if(str
=="udp-sndbuf-errors")
1165 return std::stoull(parts
[6]);
1166 else if(str
=="udp-noport-errors")
1167 return std::stoull(parts
[2]);
1168 else if(str
=="udp-in-errors")
1169 return std::stoull(parts
[3]);
1178 bool getTSIGHashEnum(const DNSName
& algoName
, TSIGHashEnum
& algoEnum
)
1180 if (algoName
== DNSName("hmac-md5.sig-alg.reg.int") || algoName
== DNSName("hmac-md5"))
1181 algoEnum
= TSIG_MD5
;
1182 else if (algoName
== DNSName("hmac-sha1"))
1183 algoEnum
= TSIG_SHA1
;
1184 else if (algoName
== DNSName("hmac-sha224"))
1185 algoEnum
= TSIG_SHA224
;
1186 else if (algoName
== DNSName("hmac-sha256"))
1187 algoEnum
= TSIG_SHA256
;
1188 else if (algoName
== DNSName("hmac-sha384"))
1189 algoEnum
= TSIG_SHA384
;
1190 else if (algoName
== DNSName("hmac-sha512"))
1191 algoEnum
= TSIG_SHA512
;
1192 else if (algoName
== DNSName("gss-tsig"))
1193 algoEnum
= TSIG_GSS
;
1200 DNSName
getTSIGAlgoName(TSIGHashEnum
& algoEnum
)
1203 case TSIG_MD5
: return DNSName("hmac-md5.sig-alg.reg.int.");
1204 case TSIG_SHA1
: return DNSName("hmac-sha1.");
1205 case TSIG_SHA224
: return DNSName("hmac-sha224.");
1206 case TSIG_SHA256
: return DNSName("hmac-sha256.");
1207 case TSIG_SHA384
: return DNSName("hmac-sha384.");
1208 case TSIG_SHA512
: return DNSName("hmac-sha512.");
1209 case TSIG_GSS
: return DNSName("gss-tsig.");
1211 throw PDNSException("getTSIGAlgoName does not understand given algorithm, please fix!");
1214 uint64_t getOpenFileDescriptors(const std::string
&)
1217 DIR* dirhdl
=opendir(("/proc/"+std::to_string(getpid())+"/fd/").c_str());
1221 struct dirent
*entry
;
1223 while((entry
= readdir(dirhdl
))) {
1226 num
= pdns_stou(entry
->d_name
);
1228 continue; // was not a number.
1230 if(std::to_string(num
) == entry
->d_name
)
1241 uint64_t getRealMemoryUsage(const std::string
&)
1244 ifstream
ifs("/proc/"+std::to_string(getpid())+"/smaps");
1249 string
header("Private_Dirty:");
1250 while(getline(ifs
, line
)) {
1251 if(boost::starts_with(line
, header
)) {
1252 bytes
+= std::stoull(line
.substr(header
.length() + 1))*1024;
1261 uint64_t getCPUTimeUser(const std::string
&)
1264 getrusage(RUSAGE_SELF
, &ru
);
1265 return (ru
.ru_utime
.tv_sec
*1000ULL + ru
.ru_utime
.tv_usec
/1000);
1268 uint64_t getCPUTimeSystem(const std::string
&)
1271 getrusage(RUSAGE_SELF
, &ru
);
1272 return (ru
.ru_stime
.tv_sec
*1000ULL + ru
.ru_stime
.tv_usec
/1000);
1275 double DiffTime(const struct timespec
& first
, const struct timespec
& second
)
1277 int seconds
=second
.tv_sec
- first
.tv_sec
;
1278 int nseconds
=second
.tv_nsec
- first
.tv_nsec
;
1282 nseconds
+=1000000000;
1284 return seconds
+ nseconds
/1000000000.0;
1287 double DiffTime(const struct timeval
& first
, const struct timeval
& second
)
1289 int seconds
=second
.tv_sec
- first
.tv_sec
;
1290 int useconds
=second
.tv_usec
- first
.tv_usec
;
1296 return seconds
+ useconds
/1000000.0;
1299 uid_t
strToUID(const string
&str
)
1302 const char * cstr
= str
.c_str();
1303 struct passwd
* pwd
= getpwnam(cstr
);
1311 catch(std::exception
& e
) {
1312 throw runtime_error((boost::format("Error: Unable to parse user ID %s") % cstr
).str() );
1315 if (val
< std::numeric_limits
<uid_t
>::min() || val
> std::numeric_limits
<uid_t
>::max()) {
1316 throw runtime_error((boost::format("Error: Unable to parse user ID %s") % cstr
).str() );
1319 result
= static_cast<uid_t
>(val
);
1322 result
= pwd
->pw_uid
;
1328 gid_t
strToGID(const string
&str
)
1331 const char * cstr
= str
.c_str();
1332 struct group
* grp
= getgrnam(cstr
);
1340 catch(std::exception
& e
) {
1341 throw runtime_error((boost::format("Error: Unable to parse group ID %s") % cstr
).str() );
1344 if (val
< std::numeric_limits
<gid_t
>::min() || val
> std::numeric_limits
<gid_t
>::max()) {
1345 throw runtime_error((boost::format("Error: Unable to parse group ID %s") % cstr
).str() );
1348 result
= static_cast<gid_t
>(val
);
1351 result
= grp
->gr_gid
;
1357 unsigned int pdns_stou(const std::string
& str
, size_t * idx
, int base
)
1359 if (str
.empty()) return 0; // compatibility
1360 unsigned long result
;
1362 result
= std::stoul(str
, idx
, base
);
1364 catch(std::invalid_argument
& e
) {
1365 throw std::invalid_argument(string(e
.what()) + "; (invalid argument during std::stoul); data was \""+str
+"\"");
1367 catch(std::out_of_range
& e
) {
1368 throw std::out_of_range(string(e
.what()) + "; (out of range during std::stoul); data was \""+str
+"\"");
1370 if (result
> std::numeric_limits
<unsigned int>::max()) {
1371 throw std::out_of_range("stoul returned result out of unsigned int range; data was \""+str
+"\"");
1373 return static_cast<unsigned int>(result
);
1376 bool isSettingThreadCPUAffinitySupported()
1378 #ifdef HAVE_PTHREAD_SETAFFINITY_NP
1385 int mapThreadToCPUList(pthread_t tid
, const std::set
<int>& cpus
)
1387 #ifdef HAVE_PTHREAD_SETAFFINITY_NP
1390 cpuset
= cpuset_create();
1391 for (const auto cpuID
: cpus
) {
1392 cpuset_set(cpuID
, cpuset
);
1395 return pthread_setaffinity_np(tid
,
1396 cpuset_size(cpuset
),
1400 # define cpu_set_t cpuset_t
1404 for (const auto cpuID
: cpus
) {
1405 CPU_SET(cpuID
, &cpuset
);
1408 return pthread_setaffinity_np(tid
,
1414 #endif /* HAVE_PTHREAD_SETAFFINITY_NP */
1417 std::vector
<ComboAddress
> getResolvers(const std::string
& resolvConfPath
)
1419 std::vector
<ComboAddress
> results
;
1421 ifstream
ifs(resolvConfPath
);
1427 while(std::getline(ifs
, line
)) {
1428 boost::trim_right_if(line
, is_any_of(" \r\n\x1a"));
1429 boost::trim_left(line
); // leading spaces, let's be nice
1431 string::size_type tpos
= line
.find_first_of(";#");
1432 if (tpos
!= string::npos
) {
1436 if (boost::starts_with(line
, "nameserver ") || boost::starts_with(line
, "nameserver\t")) {
1437 vector
<string
> parts
;
1438 stringtok(parts
, line
, " \t,"); // be REALLY nice
1439 for(vector
<string
>::const_iterator iter
= parts
.begin() + 1; iter
!= parts
.end(); ++iter
) {
1441 results
.emplace_back(*iter
, 53);