]>
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);
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 errno
= ETIMEDOUT
; // ???
345 if (error
&& (pfd
.revents
& POLLERR
)) {
348 if (disconnected
&& (pfd
.revents
& POLLHUP
)) {
349 *disconnected
= true;
356 // returns -1 in case of error, 0 if no data is available, 1 if there is. In the first two cases, errno is set
357 int waitForMultiData(const set
<int>& fds
, const int seconds
, const int useconds
, int* fd
) {
359 for (const auto& fd
: fds
) {
360 if (fd
>= 0 && realFDs
.count(fd
) == 0) {
365 std::vector
<struct pollfd
> pfds(realFDs
.size());
366 memset(pfds
.data(), 0, realFDs
.size()*sizeof(struct pollfd
));
368 for (const auto& fd
: realFDs
) {
370 pfds
[ctr
].events
= POLLIN
;
376 ret
= poll(pfds
.data(), realFDs
.size(), seconds
* 1000 + useconds
/1000);
378 ret
= poll(pfds
.data(), realFDs
.size(), -1);
383 for (const auto& pfd
: pfds
) {
384 if (pfd
.revents
& POLLIN
) {
385 pollinFDs
.insert(pfd
.fd
);
388 set
<int>::const_iterator
it(pollinFDs
.begin());
389 advance(it
, random() % pollinFDs
.size());
394 // returns -1 in case of error, 0 if no data is available, 1 if there is. In the first two cases, errno is set
395 int waitFor2Data(int fd1
, int fd2
, int seconds
, int useconds
, int*fd
)
399 struct pollfd pfds
[2];
400 memset(&pfds
[0], 0, 2*sizeof(struct pollfd
));
404 pfds
[0].events
= pfds
[1].events
= POLLIN
;
406 int nsocks
= 1 + (fd2
>= 0); // fd2 can optionally be -1
409 ret
= poll(pfds
, nsocks
, seconds
* 1000 + useconds
/1000);
411 ret
= poll(pfds
, nsocks
, -1);
415 if((pfds
[0].revents
& POLLIN
) && !(pfds
[1].revents
& POLLIN
))
417 else if((pfds
[1].revents
& POLLIN
) && !(pfds
[0].revents
& POLLIN
))
420 *fd
= pfds
[random()%2].fd
;
423 *fd
= -1; // should never happen
429 string
humanDuration(time_t passed
)
433 ret
<<passed
<<" seconds";
435 ret
<<std::setprecision(2)<<passed
/60.0<<" minutes";
436 else if(passed
<86400)
437 ret
<<std::setprecision(3)<<passed
/3600.0<<" hours";
438 else if(passed
<(86400*30.41))
439 ret
<<std::setprecision(3)<<passed
/86400.0<<" days";
441 ret
<<std::setprecision(3)<<passed
/(86400*30.41)<<" months";
448 // set(); // saves lots of gettimeofday calls
449 d_set
.tv_sec
=d_set
.tv_usec
=0;
452 DTime::DTime(const DTime
&dt
)
462 const string
unquotify(const string
&item
)
467 string::size_type bpos
=0, epos
=item
.size();
472 if(item
[epos
-1]=='"')
475 return item
.substr(bpos
,epos
-bpos
);
478 void stripLine(string
&line
)
480 string::size_type pos
=line
.find_first_of("\r\n");
481 if(pos
!=string::npos
) {
486 string
urlEncode(const string
&text
)
489 for(string::const_iterator i
=text
.begin();i
!=text
.end();++i
)
490 if(*i
==' ')ret
.append("%20");
491 else ret
.append(1,*i
);
497 #ifndef MAXHOSTNAMELEN
498 #define MAXHOSTNAMELEN 255
501 char tmp
[MAXHOSTNAMELEN
];
502 if(gethostname(tmp
, MAXHOSTNAMELEN
))
515 string
uitoa(unsigned int i
) // MSVC 6 doesn't grok overloading (un)signed
522 string
bitFlip(const string
&str
)
524 string::size_type pos
=0, epos
=str
.size();
527 for(;pos
< epos
; ++pos
)
528 ret
.append(1, ~str
[pos
]);
534 return strerror(errno
);
537 string
netstringerror()
539 return stringerror();
542 void cleanSlashes(string
&str
)
544 string::const_iterator i
;
546 for(i
=str
.begin();i
!=str
.end();++i
) {
547 if(*i
=='/' && i
!=str
.begin() && *(i
-1)=='/')
555 bool IpToU32(const string
&str
, uint32_t *ip
)
563 if(inet_aton(str
.c_str(), &inp
)) {
570 string
U32ToIP(uint32_t val
)
573 snprintf(tmp
, sizeof(tmp
)-1, "%u.%u.%u.%u",
582 string
makeHexDump(const string
& str
)
586 ret
.reserve((int)(str
.size()*2.2));
588 for(string::size_type n
=0;n
<str
.size();++n
) {
589 sprintf(tmp
,"%02x ", (unsigned char)str
[n
]);
595 // shuffle, maintaining some semblance of order
596 void shuffle(vector
<DNSZoneRecord
>& rrs
)
598 vector
<DNSZoneRecord
>::iterator first
, second
;
599 for(first
=rrs
.begin();first
!=rrs
.end();++first
)
600 if(first
->dr
.d_place
==DNSResourceRecord::ANSWER
&& first
->dr
.d_type
!= QType::CNAME
) // CNAME must come first
602 for(second
=first
;second
!=rrs
.end();++second
)
603 if(second
->dr
.d_place
!=DNSResourceRecord::ANSWER
)
607 random_shuffle(first
,second
);
609 // now shuffle the additional records
610 for(first
=second
;first
!=rrs
.end();++first
)
611 if(first
->dr
.d_place
==DNSResourceRecord::ADDITIONAL
&& first
->dr
.d_type
!= QType::CNAME
) // CNAME must come first
613 for(second
=first
;second
!=rrs
.end();++second
)
614 if(second
->dr
.d_place
!=DNSResourceRecord::ADDITIONAL
)
618 random_shuffle(first
,second
);
620 // we don't shuffle the rest
624 // shuffle, maintaining some semblance of order
625 void shuffle(vector
<DNSRecord
>& rrs
)
627 vector
<DNSRecord
>::iterator first
, second
;
628 for(first
=rrs
.begin();first
!=rrs
.end();++first
)
629 if(first
->d_place
==DNSResourceRecord::ANSWER
&& first
->d_type
!= QType::CNAME
) // CNAME must come first
631 for(second
=first
;second
!=rrs
.end();++second
)
632 if(second
->d_place
!=DNSResourceRecord::ANSWER
|| second
->d_type
== QType::RRSIG
) // leave RRSIGs at the end
636 random_shuffle(first
,second
);
638 // now shuffle the additional records
639 for(first
=second
;first
!=rrs
.end();++first
)
640 if(first
->d_place
==DNSResourceRecord::ADDITIONAL
&& first
->d_type
!= QType::CNAME
) // CNAME must come first
642 for(second
=first
; second
!=rrs
.end(); ++second
)
643 if(second
->d_place
!=DNSResourceRecord::ADDITIONAL
)
647 random_shuffle(first
,second
);
649 // we don't shuffle the rest
652 static uint16_t mapTypesToOrder(uint16_t type
)
654 if(type
== QType::CNAME
)
656 if(type
== QType::RRSIG
)
662 // make sure rrs is sorted in d_place order to avoid surprises later
663 // then shuffle the parts that desire shuffling
664 void orderAndShuffle(vector
<DNSRecord
>& rrs
)
666 std::stable_sort(rrs
.begin(), rrs
.end(), [](const DNSRecord
&a
, const DNSRecord
& b
) {
667 return std::make_tuple(a
.d_place
, mapTypesToOrder(a
.d_type
)) < std::make_tuple(b
.d_place
, mapTypesToOrder(b
.d_type
));
672 void normalizeTV(struct timeval
& tv
)
674 if(tv
.tv_usec
> 1000000) {
678 else if(tv
.tv_usec
< 0) {
684 const struct timeval
operator+(const struct timeval
& lhs
, const struct timeval
& rhs
)
687 ret
.tv_sec
=lhs
.tv_sec
+ rhs
.tv_sec
;
688 ret
.tv_usec
=lhs
.tv_usec
+ rhs
.tv_usec
;
693 const struct timeval
operator-(const struct timeval
& lhs
, const struct timeval
& rhs
)
696 ret
.tv_sec
=lhs
.tv_sec
- rhs
.tv_sec
;
697 ret
.tv_usec
=lhs
.tv_usec
- rhs
.tv_usec
;
702 pair
<string
, string
> splitField(const string
& inp
, char sepa
)
704 pair
<string
, string
> ret
;
705 string::size_type cpos
=inp
.find(sepa
);
706 if(cpos
==string::npos
)
709 ret
.first
=inp
.substr(0, cpos
);
710 ret
.second
=inp
.substr(cpos
+1);
715 int logFacilityToLOG(unsigned int facility
)
739 string
stripDot(const string
& dom
)
744 if(dom
[dom
.size()-1]!='.')
747 return dom
.substr(0,dom
.size()-1);
752 int makeIPv6sockaddr(const std::string
& addr
, struct sockaddr_in6
* ret
)
756 string
ourAddr(addr
);
757 bool portSet
= false;
759 if(addr
[0]=='[') { // [::]:53 style address
760 string::size_type pos
= addr
.find(']');
761 if(pos
== string::npos
)
763 ourAddr
.assign(addr
.c_str() + 1, pos
-1);
764 if (pos
+ 1 != addr
.size()) { // complete after ], no port specified
765 if (pos
+ 2 > addr
.size() || addr
[pos
+1]!=':')
768 port
= pdns_stou(addr
.substr(pos
+2));
771 catch(std::out_of_range
) {
776 ret
->sin6_scope_id
=0;
777 ret
->sin6_family
=AF_INET6
;
779 if(inet_pton(AF_INET6
, ourAddr
.c_str(), (void*)&ret
->sin6_addr
) != 1) {
780 struct addrinfo
* res
;
781 struct addrinfo hints
;
782 memset(&hints
, 0, sizeof(hints
));
784 hints
.ai_family
= AF_INET6
;
785 hints
.ai_flags
= AI_NUMERICHOST
;
788 // getaddrinfo has anomalous return codes, anything nonzero is an error, positive or negative
789 if((error
=getaddrinfo(ourAddr
.c_str(), 0, &hints
, &res
))) {
793 memcpy(ret
, res
->ai_addr
, res
->ai_addrlen
);
801 ret
->sin6_port
= htons(port
);
807 int makeIPv4sockaddr(const std::string
& str
, struct sockaddr_in
* ret
)
814 string::size_type pos
= str
.find(':');
815 if(pos
== string::npos
) { // no port specified, not touching the port
816 if(inet_aton(str
.c_str(), &inp
)) {
817 ret
->sin_addr
.s_addr
=inp
.s_addr
;
822 if(!*(str
.c_str() + pos
+ 1)) // trailing :
825 char *eptr
= (char*)str
.c_str() + str
.size();
826 int port
= strtol(str
.c_str() + pos
+ 1, &eptr
, 10);
827 if (port
< 0 || port
> 65535)
833 ret
->sin_port
= htons(port
);
834 if(inet_aton(str
.substr(0, pos
).c_str(), &inp
)) {
835 ret
->sin_addr
.s_addr
=inp
.s_addr
;
841 int makeUNsockaddr(const std::string
& path
, struct sockaddr_un
* ret
)
846 memset(ret
, 0, sizeof(struct sockaddr_un
));
847 ret
->sun_family
= AF_UNIX
;
848 if (path
.length() >= sizeof(ret
->sun_path
))
851 path
.copy(ret
->sun_path
, sizeof(ret
->sun_path
), 0);
855 //! read a line of text from a FILE* to a std::string, returns false on 'no data'
856 bool stringfgets(FILE* fp
, std::string
& line
)
862 if(!fgets(buffer
, sizeof(buffer
), fp
))
863 return !line
.empty();
866 } while(!strchr(buffer
, '\n'));
870 bool readFileIfThere(const char* fname
, std::string
* line
)
873 FILE* fp
= fopen(fname
, "r");
876 stringfgets(fp
, *line
);
881 Regex::Regex(const string
&expr
)
883 if(regcomp(&d_preg
, expr
.c_str(), REG_ICASE
|REG_NOSUB
|REG_EXTENDED
))
884 throw PDNSException("Regular expression did not compile");
887 // if you end up here because valgrind told you were are doing something wrong
888 // with msgh->msg_controllen, please refer to https://github.com/PowerDNS/pdns/pull/3962
890 void addCMsgSrcAddr(struct msghdr
* msgh
, void* cmsgbuf
, const ComboAddress
* source
, int itfIndex
)
892 struct cmsghdr
*cmsg
= NULL
;
894 if(source
->sin4
.sin_family
== AF_INET6
) {
895 struct in6_pktinfo
*pkt
;
897 msgh
->msg_control
= cmsgbuf
;
898 msgh
->msg_controllen
= CMSG_SPACE(sizeof(*pkt
));
900 cmsg
= CMSG_FIRSTHDR(msgh
);
901 cmsg
->cmsg_level
= IPPROTO_IPV6
;
902 cmsg
->cmsg_type
= IPV6_PKTINFO
;
903 cmsg
->cmsg_len
= CMSG_LEN(sizeof(*pkt
));
905 pkt
= (struct in6_pktinfo
*) CMSG_DATA(cmsg
);
906 memset(pkt
, 0, sizeof(*pkt
));
907 pkt
->ipi6_addr
= source
->sin6
.sin6_addr
;
908 pkt
->ipi6_ifindex
= itfIndex
;
911 #if defined(IP_PKTINFO)
912 struct in_pktinfo
*pkt
;
914 msgh
->msg_control
= cmsgbuf
;
915 msgh
->msg_controllen
= CMSG_SPACE(sizeof(*pkt
));
917 cmsg
= CMSG_FIRSTHDR(msgh
);
918 cmsg
->cmsg_level
= IPPROTO_IP
;
919 cmsg
->cmsg_type
= IP_PKTINFO
;
920 cmsg
->cmsg_len
= CMSG_LEN(sizeof(*pkt
));
922 pkt
= (struct in_pktinfo
*) CMSG_DATA(cmsg
);
923 memset(pkt
, 0, sizeof(*pkt
));
924 pkt
->ipi_spec_dst
= source
->sin4
.sin_addr
;
925 pkt
->ipi_ifindex
= itfIndex
;
926 #elif defined(IP_SENDSRCADDR)
929 msgh
->msg_control
= cmsgbuf
;
930 msgh
->msg_controllen
= CMSG_SPACE(sizeof(*in
));
932 cmsg
= CMSG_FIRSTHDR(msgh
);
933 cmsg
->cmsg_level
= IPPROTO_IP
;
934 cmsg
->cmsg_type
= IP_SENDSRCADDR
;
935 cmsg
->cmsg_len
= CMSG_LEN(sizeof(*in
));
937 in
= (struct in_addr
*) CMSG_DATA(cmsg
);
938 *in
= source
->sin4
.sin_addr
;
943 unsigned int getFilenumLimit(bool hardOrSoft
)
946 if(getrlimit(RLIMIT_NOFILE
, &rlim
) < 0)
947 unixDie("Requesting number of available file descriptors");
948 return hardOrSoft
? rlim
.rlim_max
: rlim
.rlim_cur
;
951 void setFilenumLimit(unsigned int lim
)
955 if(getrlimit(RLIMIT_NOFILE
, &rlim
) < 0)
956 unixDie("Requesting number of available file descriptors");
958 if(setrlimit(RLIMIT_NOFILE
, &rlim
) < 0)
959 unixDie("Setting number of available file descriptors");
962 #define burtlemix(a,b,c) \
964 a -= b; a -= c; a ^= (c>>13); \
965 b -= c; b -= a; b ^= (a<<8); \
966 c -= a; c -= b; c ^= (b>>13); \
967 a -= b; a -= c; a ^= (c>>12); \
968 b -= c; b -= a; b ^= (a<<16); \
969 c -= a; c -= b; c ^= (b>>5); \
970 a -= b; a -= c; a ^= (c>>3); \
971 b -= c; b -= a; b ^= (a<<10); \
972 c -= a; c -= b; c ^= (b>>15); \
975 uint32_t burtle(const unsigned char* k
, uint32_t length
, uint32_t initval
)
979 /* Set up the internal state */
981 a
= b
= 0x9e3779b9; /* the golden ratio; an arbitrary value */
982 c
= initval
; /* the previous hash value */
984 /*---------------------------------------- handle most of the key */
986 a
+= (k
[0] +((uint32_t)k
[1]<<8) +((uint32_t)k
[2]<<16) +((uint32_t)k
[3]<<24));
987 b
+= (k
[4] +((uint32_t)k
[5]<<8) +((uint32_t)k
[6]<<16) +((uint32_t)k
[7]<<24));
988 c
+= (k
[8] +((uint32_t)k
[9]<<8) +((uint32_t)k
[10]<<16)+((uint32_t)k
[11]<<24));
993 /*------------------------------------- handle the last 11 bytes */
995 switch(len
) { /* all the case statements fall through */
996 case 11: c
+=((uint32_t)k
[10]<<24);
997 case 10: c
+=((uint32_t)k
[9]<<16);
998 case 9 : c
+=((uint32_t)k
[8]<<8);
999 /* the first byte of c is reserved for the length */
1000 case 8 : b
+=((uint32_t)k
[7]<<24);
1001 case 7 : b
+=((uint32_t)k
[6]<<16);
1002 case 6 : b
+=((uint32_t)k
[5]<<8);
1004 case 4 : a
+=((uint32_t)k
[3]<<24);
1005 case 3 : a
+=((uint32_t)k
[2]<<16);
1006 case 2 : a
+=((uint32_t)k
[1]<<8);
1008 /* case 0: nothing left to add */
1011 /*-------------------------------------------- report the result */
1015 uint32_t burtleCI(const unsigned char* k
, uint32_t length
, uint32_t initval
)
1019 /* Set up the internal state */
1021 a
= b
= 0x9e3779b9; /* the golden ratio; an arbitrary value */
1022 c
= initval
; /* the previous hash value */
1024 /*---------------------------------------- handle most of the key */
1026 a
+= (dns_tolower(k
[0]) +((uint32_t)dns_tolower(k
[1])<<8) +((uint32_t)dns_tolower(k
[2])<<16) +((uint32_t)dns_tolower(k
[3])<<24));
1027 b
+= (dns_tolower(k
[4]) +((uint32_t)dns_tolower(k
[5])<<8) +((uint32_t)dns_tolower(k
[6])<<16) +((uint32_t)dns_tolower(k
[7])<<24));
1028 c
+= (dns_tolower(k
[8]) +((uint32_t)dns_tolower(k
[9])<<8) +((uint32_t)dns_tolower(k
[10])<<16)+((uint32_t)dns_tolower(k
[11])<<24));
1033 /*------------------------------------- handle the last 11 bytes */
1035 switch(len
) { /* all the case statements fall through */
1036 case 11: c
+=((uint32_t)dns_tolower(k
[10])<<24);
1037 case 10: c
+=((uint32_t)dns_tolower(k
[9])<<16);
1038 case 9 : c
+=((uint32_t)dns_tolower(k
[8])<<8);
1039 /* the first byte of c is reserved for the length */
1040 case 8 : b
+=((uint32_t)dns_tolower(k
[7])<<24);
1041 case 7 : b
+=((uint32_t)dns_tolower(k
[6])<<16);
1042 case 6 : b
+=((uint32_t)dns_tolower(k
[5])<<8);
1043 case 5 : b
+=dns_tolower(k
[4]);
1044 case 4 : a
+=((uint32_t)dns_tolower(k
[3])<<24);
1045 case 3 : a
+=((uint32_t)dns_tolower(k
[2])<<16);
1046 case 2 : a
+=((uint32_t)dns_tolower(k
[1])<<8);
1047 case 1 : a
+=dns_tolower(k
[0]);
1048 /* case 0: nothing left to add */
1051 /*-------------------------------------------- report the result */
1056 bool setSocketTimestamps(int fd
)
1060 return setsockopt(fd
, SOL_SOCKET
, SO_TIMESTAMP
, (char*)&on
, sizeof(on
)) == 0;
1062 return true; // we pretend this happened.
1066 bool setTCPNoDelay(int sock
)
1069 return setsockopt(sock
, /* socket affected */
1070 IPPROTO_TCP
, /* set option at TCP level */
1071 TCP_NODELAY
, /* name of option */
1072 (char *) &flag
, /* the cast is historical cruft */
1073 sizeof(flag
)) == 0; /* length of option value */
1077 bool setNonBlocking(int sock
)
1079 int flags
=fcntl(sock
,F_GETFL
,0);
1080 if(flags
<0 || fcntl(sock
, F_SETFL
,flags
|O_NONBLOCK
) <0)
1085 bool setBlocking(int sock
)
1087 int flags
=fcntl(sock
,F_GETFL
,0);
1088 if(flags
<0 || fcntl(sock
, F_SETFL
,flags
&(~O_NONBLOCK
)) <0)
1093 bool setReuseAddr(int sock
)
1096 if (setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, (char*)&tmp
, static_cast<unsigned>(sizeof tmp
))<0)
1097 throw PDNSException(string("Setsockopt failed: ")+strerror(errno
));
1101 bool isNonBlocking(int sock
)
1103 int flags
=fcntl(sock
,F_GETFL
,0);
1104 return flags
& O_NONBLOCK
;
1108 int closesocket( int socket
)
1110 int ret
=::close(socket
);
1111 if(ret
< 0 && errno
== ECONNRESET
) // see ticket 192, odd BSD behaviour
1114 throw PDNSException("Error closing socket: "+stringerror());
1118 bool setCloseOnExec(int sock
)
1120 int flags
=fcntl(sock
,F_GETFD
,0);
1121 if(flags
<0 || fcntl(sock
, F_SETFD
,flags
|FD_CLOEXEC
) <0)
1126 string
getMACAddress(const ComboAddress
& ca
)
1130 ifstream
ifs("/proc/net/arp");
1134 string match
=ca
.toString()+' ';
1135 while(getline(ifs
, line
)) {
1136 if(boost::starts_with(line
, match
)) {
1137 vector
<string
> parts
;
1138 stringtok(parts
, line
, " \n\t\r");
1139 if(parts
.size() < 4)
1141 unsigned int tmp
[6];
1142 sscanf(parts
[3].c_str(), "%02x:%02x:%02x:%02x:%02x:%02x", tmp
, tmp
+1, tmp
+2, tmp
+3, tmp
+4, tmp
+5);
1143 for(int i
= 0 ; i
< 6 ; ++i
)
1144 ret
.append(1, (char)tmp
[i
]);
1152 uint64_t udpErrorStats(const std::string
& str
)
1155 ifstream
ifs("/proc/net/snmp");
1159 vector
<string
> parts
;
1160 while(getline(ifs
,line
)) {
1161 if(boost::starts_with(line
, "Udp: ") && isdigit(line
[5])) {
1162 stringtok(parts
, line
, " \n\t\r");
1163 if(parts
.size() < 7)
1165 if(str
=="udp-rcvbuf-errors")
1166 return std::stoull(parts
[5]);
1167 else if(str
=="udp-sndbuf-errors")
1168 return std::stoull(parts
[6]);
1169 else if(str
=="udp-noport-errors")
1170 return std::stoull(parts
[2]);
1171 else if(str
=="udp-in-errors")
1172 return std::stoull(parts
[3]);
1181 bool getTSIGHashEnum(const DNSName
& algoName
, TSIGHashEnum
& algoEnum
)
1183 if (algoName
== DNSName("hmac-md5.sig-alg.reg.int") || algoName
== DNSName("hmac-md5"))
1184 algoEnum
= TSIG_MD5
;
1185 else if (algoName
== DNSName("hmac-sha1"))
1186 algoEnum
= TSIG_SHA1
;
1187 else if (algoName
== DNSName("hmac-sha224"))
1188 algoEnum
= TSIG_SHA224
;
1189 else if (algoName
== DNSName("hmac-sha256"))
1190 algoEnum
= TSIG_SHA256
;
1191 else if (algoName
== DNSName("hmac-sha384"))
1192 algoEnum
= TSIG_SHA384
;
1193 else if (algoName
== DNSName("hmac-sha512"))
1194 algoEnum
= TSIG_SHA512
;
1195 else if (algoName
== DNSName("gss-tsig"))
1196 algoEnum
= TSIG_GSS
;
1203 DNSName
getTSIGAlgoName(TSIGHashEnum
& algoEnum
)
1206 case TSIG_MD5
: return DNSName("hmac-md5.sig-alg.reg.int.");
1207 case TSIG_SHA1
: return DNSName("hmac-sha1.");
1208 case TSIG_SHA224
: return DNSName("hmac-sha224.");
1209 case TSIG_SHA256
: return DNSName("hmac-sha256.");
1210 case TSIG_SHA384
: return DNSName("hmac-sha384.");
1211 case TSIG_SHA512
: return DNSName("hmac-sha512.");
1212 case TSIG_GSS
: return DNSName("gss-tsig.");
1214 throw PDNSException("getTSIGAlgoName does not understand given algorithm, please fix!");
1217 uint64_t getOpenFileDescriptors(const std::string
&)
1220 DIR* dirhdl
=opendir(("/proc/"+std::to_string(getpid())+"/fd/").c_str());
1224 struct dirent
*entry
;
1226 while((entry
= readdir(dirhdl
))) {
1229 num
= pdns_stou(entry
->d_name
);
1231 continue; // was not a number.
1233 if(std::to_string(num
) == entry
->d_name
)
1244 uint64_t getRealMemoryUsage(const std::string
&)
1247 ifstream
ifs("/proc/"+std::to_string(getpid())+"/smaps");
1252 string
header("Private_Dirty:");
1253 while(getline(ifs
, line
)) {
1254 if(boost::starts_with(line
, header
)) {
1255 bytes
+= std::stoull(line
.substr(header
.length() + 1))*1024;
1264 uint64_t getCPUTimeUser(const std::string
&)
1267 getrusage(RUSAGE_SELF
, &ru
);
1268 return (ru
.ru_utime
.tv_sec
*1000ULL + ru
.ru_utime
.tv_usec
/1000);
1271 uint64_t getCPUTimeSystem(const std::string
&)
1274 getrusage(RUSAGE_SELF
, &ru
);
1275 return (ru
.ru_stime
.tv_sec
*1000ULL + ru
.ru_stime
.tv_usec
/1000);
1278 double DiffTime(const struct timespec
& first
, const struct timespec
& second
)
1280 int seconds
=second
.tv_sec
- first
.tv_sec
;
1281 int nseconds
=second
.tv_nsec
- first
.tv_nsec
;
1285 nseconds
+=1000000000;
1287 return seconds
+ nseconds
/1000000000.0;
1290 double DiffTime(const struct timeval
& first
, const struct timeval
& second
)
1292 int seconds
=second
.tv_sec
- first
.tv_sec
;
1293 int useconds
=second
.tv_usec
- first
.tv_usec
;
1299 return seconds
+ useconds
/1000000.0;
1302 uid_t
strToUID(const string
&str
)
1305 const char * cstr
= str
.c_str();
1306 struct passwd
* pwd
= getpwnam(cstr
);
1314 catch(std::exception
& e
) {
1315 throw runtime_error((boost::format("Error: Unable to parse user ID %s") % cstr
).str() );
1318 if (val
< std::numeric_limits
<uid_t
>::min() || val
> std::numeric_limits
<uid_t
>::max()) {
1319 throw runtime_error((boost::format("Error: Unable to parse user ID %s") % cstr
).str() );
1322 result
= static_cast<uid_t
>(val
);
1325 result
= pwd
->pw_uid
;
1331 gid_t
strToGID(const string
&str
)
1334 const char * cstr
= str
.c_str();
1335 struct group
* grp
= getgrnam(cstr
);
1343 catch(std::exception
& e
) {
1344 throw runtime_error((boost::format("Error: Unable to parse group ID %s") % cstr
).str() );
1347 if (val
< std::numeric_limits
<gid_t
>::min() || val
> std::numeric_limits
<gid_t
>::max()) {
1348 throw runtime_error((boost::format("Error: Unable to parse group ID %s") % cstr
).str() );
1351 result
= static_cast<gid_t
>(val
);
1354 result
= grp
->gr_gid
;
1360 unsigned int pdns_stou(const std::string
& str
, size_t * idx
, int base
)
1362 if (str
.empty()) return 0; // compatibility
1363 unsigned long result
;
1365 result
= std::stoul(str
, idx
, base
);
1367 catch(std::invalid_argument
& e
) {
1368 throw std::invalid_argument(string(e
.what()) + "; (invalid argument during std::stoul); data was \""+str
+"\"");
1370 catch(std::out_of_range
& e
) {
1371 throw std::out_of_range(string(e
.what()) + "; (out of range during std::stoul); data was \""+str
+"\"");
1373 if (result
> std::numeric_limits
<unsigned int>::max()) {
1374 throw std::out_of_range("stoul returned result out of unsigned int range; data was \""+str
+"\"");
1376 return static_cast<unsigned int>(result
);
1379 bool isSettingThreadCPUAffinitySupported()
1381 #ifdef HAVE_PTHREAD_SETAFFINITY_NP
1388 int mapThreadToCPUList(pthread_t tid
, const std::set
<int>& cpus
)
1390 #ifdef HAVE_PTHREAD_SETAFFINITY_NP
1393 cpuset
= cpuset_create();
1394 for (const auto cpuID
: cpus
) {
1395 cpuset_set(cpuID
, cpuset
);
1398 return pthread_setaffinity_np(tid
,
1399 cpuset_size(cpuset
),
1403 # define cpu_set_t cpuset_t
1407 for (const auto cpuID
: cpus
) {
1408 CPU_SET(cpuID
, &cpuset
);
1411 return pthread_setaffinity_np(tid
,
1417 #endif /* HAVE_PTHREAD_SETAFFINITY_NP */