]>
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 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
) : d_set(dt
.d_set
)
458 const string
unquotify(const string
&item
)
463 string::size_type bpos
=0, epos
=item
.size();
468 if(item
[epos
-1]=='"')
471 return item
.substr(bpos
,epos
-bpos
);
474 void stripLine(string
&line
)
476 string::size_type pos
=line
.find_first_of("\r\n");
477 if(pos
!=string::npos
) {
482 string
urlEncode(const string
&text
)
485 for(string::const_iterator i
=text
.begin();i
!=text
.end();++i
)
486 if(*i
==' ')ret
.append("%20");
487 else ret
.append(1,*i
);
493 #ifndef MAXHOSTNAMELEN
494 #define MAXHOSTNAMELEN 255
497 char tmp
[MAXHOSTNAMELEN
];
498 if(gethostname(tmp
, MAXHOSTNAMELEN
))
511 string
uitoa(unsigned int i
) // MSVC 6 doesn't grok overloading (un)signed
518 string
bitFlip(const string
&str
)
520 string::size_type pos
=0, epos
=str
.size();
523 for(;pos
< epos
; ++pos
)
524 ret
.append(1, ~str
[pos
]);
530 return strerror(errno
);
533 string
netstringerror()
535 return stringerror();
538 void cleanSlashes(string
&str
)
540 string::const_iterator i
;
542 for(i
=str
.begin();i
!=str
.end();++i
) {
543 if(*i
=='/' && i
!=str
.begin() && *(i
-1)=='/')
551 bool IpToU32(const string
&str
, uint32_t *ip
)
559 if(inet_aton(str
.c_str(), &inp
)) {
566 string
U32ToIP(uint32_t val
)
569 snprintf(tmp
, sizeof(tmp
), "%u.%u.%u.%u",
578 string
makeHexDump(const string
& str
)
582 ret
.reserve((int)(str
.size()*2.2));
584 for(string::size_type n
=0;n
<str
.size();++n
) {
585 snprintf(tmp
, sizeof(tmp
), "%02x ", (unsigned char)str
[n
]);
591 // shuffle, maintaining some semblance of order
592 void shuffle(vector
<DNSZoneRecord
>& rrs
)
594 vector
<DNSZoneRecord
>::iterator first
, second
;
595 for(first
=rrs
.begin();first
!=rrs
.end();++first
)
596 if(first
->dr
.d_place
==DNSResourceRecord::ANSWER
&& first
->dr
.d_type
!= QType::CNAME
) // CNAME must come first
598 for(second
=first
;second
!=rrs
.end();++second
)
599 if(second
->dr
.d_place
!=DNSResourceRecord::ANSWER
)
603 random_shuffle(first
,second
);
605 // now shuffle the additional records
606 for(first
=second
;first
!=rrs
.end();++first
)
607 if(first
->dr
.d_place
==DNSResourceRecord::ADDITIONAL
&& first
->dr
.d_type
!= QType::CNAME
) // CNAME must come first
609 for(second
=first
;second
!=rrs
.end();++second
)
610 if(second
->dr
.d_place
!=DNSResourceRecord::ADDITIONAL
)
614 random_shuffle(first
,second
);
616 // we don't shuffle the rest
620 // shuffle, maintaining some semblance of order
621 void shuffle(vector
<DNSRecord
>& rrs
)
623 vector
<DNSRecord
>::iterator first
, second
;
624 for(first
=rrs
.begin();first
!=rrs
.end();++first
)
625 if(first
->d_place
==DNSResourceRecord::ANSWER
&& first
->d_type
!= QType::CNAME
) // CNAME must come first
627 for(second
=first
;second
!=rrs
.end();++second
)
628 if(second
->d_place
!=DNSResourceRecord::ANSWER
|| second
->d_type
== QType::RRSIG
) // leave RRSIGs at the end
632 random_shuffle(first
,second
);
634 // now shuffle the additional records
635 for(first
=second
;first
!=rrs
.end();++first
)
636 if(first
->d_place
==DNSResourceRecord::ADDITIONAL
&& first
->d_type
!= QType::CNAME
) // CNAME must come first
638 for(second
=first
; second
!=rrs
.end(); ++second
)
639 if(second
->d_place
!=DNSResourceRecord::ADDITIONAL
)
643 random_shuffle(first
,second
);
645 // we don't shuffle the rest
648 static uint16_t mapTypesToOrder(uint16_t type
)
650 if(type
== QType::CNAME
)
652 if(type
== QType::RRSIG
)
658 // make sure rrs is sorted in d_place order to avoid surprises later
659 // then shuffle the parts that desire shuffling
660 void orderAndShuffle(vector
<DNSRecord
>& rrs
)
662 std::stable_sort(rrs
.begin(), rrs
.end(), [](const DNSRecord
&a
, const DNSRecord
& b
) {
663 return std::make_tuple(a
.d_place
, mapTypesToOrder(a
.d_type
)) < std::make_tuple(b
.d_place
, mapTypesToOrder(b
.d_type
));
668 void normalizeTV(struct timeval
& tv
)
670 if(tv
.tv_usec
> 1000000) {
674 else if(tv
.tv_usec
< 0) {
680 const struct timeval
operator+(const struct timeval
& lhs
, const struct timeval
& rhs
)
683 ret
.tv_sec
=lhs
.tv_sec
+ rhs
.tv_sec
;
684 ret
.tv_usec
=lhs
.tv_usec
+ rhs
.tv_usec
;
689 const struct timeval
operator-(const struct timeval
& lhs
, const struct timeval
& rhs
)
692 ret
.tv_sec
=lhs
.tv_sec
- rhs
.tv_sec
;
693 ret
.tv_usec
=lhs
.tv_usec
- rhs
.tv_usec
;
698 pair
<string
, string
> splitField(const string
& inp
, char sepa
)
700 pair
<string
, string
> ret
;
701 string::size_type cpos
=inp
.find(sepa
);
702 if(cpos
==string::npos
)
705 ret
.first
=inp
.substr(0, cpos
);
706 ret
.second
=inp
.substr(cpos
+1);
711 int logFacilityToLOG(unsigned int facility
)
735 string
stripDot(const string
& dom
)
740 if(dom
[dom
.size()-1]!='.')
743 return dom
.substr(0,dom
.size()-1);
748 int makeIPv6sockaddr(const std::string
& addr
, struct sockaddr_in6
* ret
)
752 string
ourAddr(addr
);
753 bool portSet
= false;
755 if(addr
[0]=='[') { // [::]:53 style address
756 string::size_type pos
= addr
.find(']');
757 if(pos
== string::npos
)
759 ourAddr
.assign(addr
.c_str() + 1, pos
-1);
760 if (pos
+ 1 != addr
.size()) { // complete after ], no port specified
761 if (pos
+ 2 > addr
.size() || addr
[pos
+1]!=':')
764 port
= pdns_stou(addr
.substr(pos
+2));
767 catch(const std::out_of_range
&) {
772 ret
->sin6_scope_id
=0;
773 ret
->sin6_family
=AF_INET6
;
775 if(inet_pton(AF_INET6
, ourAddr
.c_str(), (void*)&ret
->sin6_addr
) != 1) {
776 struct addrinfo
* res
;
777 struct addrinfo hints
;
778 memset(&hints
, 0, sizeof(hints
));
780 hints
.ai_family
= AF_INET6
;
781 hints
.ai_flags
= AI_NUMERICHOST
;
784 // getaddrinfo has anomalous return codes, anything nonzero is an error, positive or negative
785 if((error
=getaddrinfo(ourAddr
.c_str(), 0, &hints
, &res
))) {
789 memcpy(ret
, res
->ai_addr
, res
->ai_addrlen
);
797 ret
->sin6_port
= htons(port
);
803 int makeIPv4sockaddr(const std::string
& str
, struct sockaddr_in
* ret
)
810 string::size_type pos
= str
.find(':');
811 if(pos
== string::npos
) { // no port specified, not touching the port
812 if(inet_aton(str
.c_str(), &inp
)) {
813 ret
->sin_addr
.s_addr
=inp
.s_addr
;
818 if(!*(str
.c_str() + pos
+ 1)) // trailing :
821 char *eptr
= (char*)str
.c_str() + str
.size();
822 int port
= strtol(str
.c_str() + pos
+ 1, &eptr
, 10);
823 if (port
< 0 || port
> 65535)
829 ret
->sin_port
= htons(port
);
830 if(inet_aton(str
.substr(0, pos
).c_str(), &inp
)) {
831 ret
->sin_addr
.s_addr
=inp
.s_addr
;
837 int makeUNsockaddr(const std::string
& path
, struct sockaddr_un
* ret
)
842 memset(ret
, 0, sizeof(struct sockaddr_un
));
843 ret
->sun_family
= AF_UNIX
;
844 if (path
.length() >= sizeof(ret
->sun_path
))
847 path
.copy(ret
->sun_path
, sizeof(ret
->sun_path
), 0);
851 //! read a line of text from a FILE* to a std::string, returns false on 'no data'
852 bool stringfgets(FILE* fp
, std::string
& line
)
858 if(!fgets(buffer
, sizeof(buffer
), fp
))
859 return !line
.empty();
862 } while(!strchr(buffer
, '\n'));
866 bool readFileIfThere(const char* fname
, std::string
* line
)
869 auto fp
= std::unique_ptr
<FILE, int(*)(FILE*)>(fopen(fname
, "r"), fclose
);
872 stringfgets(fp
.get(), *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
;
1104 bool setReceiveSocketErrors(int sock
, int af
)
1108 if (af
== AF_INET
) {
1109 ret
= setsockopt(sock
, IPPROTO_IP
, IP_RECVERR
, &tmp
, sizeof(tmp
));
1111 ret
= setsockopt(sock
, IPPROTO_IPV6
, IPV6_RECVERR
, &tmp
, sizeof(tmp
));
1114 throw PDNSException(string("Setsockopt failed: ") + strerror(errno
));
1121 int closesocket( int socket
)
1123 int ret
=::close(socket
);
1124 if(ret
< 0 && errno
== ECONNRESET
) // see ticket 192, odd BSD behaviour
1127 throw PDNSException("Error closing socket: "+stringerror());
1131 bool setCloseOnExec(int sock
)
1133 int flags
=fcntl(sock
,F_GETFD
,0);
1134 if(flags
<0 || fcntl(sock
, F_SETFD
,flags
|FD_CLOEXEC
) <0)
1139 string
getMACAddress(const ComboAddress
& ca
)
1143 ifstream
ifs("/proc/net/arp");
1147 string match
=ca
.toString()+' ';
1148 while(getline(ifs
, line
)) {
1149 if(boost::starts_with(line
, match
)) {
1150 vector
<string
> parts
;
1151 stringtok(parts
, line
, " \n\t\r");
1152 if(parts
.size() < 4)
1154 unsigned int tmp
[6];
1155 sscanf(parts
[3].c_str(), "%02x:%02x:%02x:%02x:%02x:%02x", tmp
, tmp
+1, tmp
+2, tmp
+3, tmp
+4, tmp
+5);
1156 for(int i
= 0 ; i
< 6 ; ++i
)
1157 ret
.append(1, (char)tmp
[i
]);
1165 uint64_t udpErrorStats(const std::string
& str
)
1168 ifstream
ifs("/proc/net/snmp");
1172 vector
<string
> parts
;
1173 while(getline(ifs
,line
)) {
1174 if(boost::starts_with(line
, "Udp: ") && isdigit(line
[5])) {
1175 stringtok(parts
, line
, " \n\t\r");
1176 if(parts
.size() < 7)
1178 if(str
=="udp-rcvbuf-errors")
1179 return std::stoull(parts
[5]);
1180 else if(str
=="udp-sndbuf-errors")
1181 return std::stoull(parts
[6]);
1182 else if(str
=="udp-noport-errors")
1183 return std::stoull(parts
[2]);
1184 else if(str
=="udp-in-errors")
1185 return std::stoull(parts
[3]);
1194 bool getTSIGHashEnum(const DNSName
& algoName
, TSIGHashEnum
& algoEnum
)
1196 if (algoName
== DNSName("hmac-md5.sig-alg.reg.int") || algoName
== DNSName("hmac-md5"))
1197 algoEnum
= TSIG_MD5
;
1198 else if (algoName
== DNSName("hmac-sha1"))
1199 algoEnum
= TSIG_SHA1
;
1200 else if (algoName
== DNSName("hmac-sha224"))
1201 algoEnum
= TSIG_SHA224
;
1202 else if (algoName
== DNSName("hmac-sha256"))
1203 algoEnum
= TSIG_SHA256
;
1204 else if (algoName
== DNSName("hmac-sha384"))
1205 algoEnum
= TSIG_SHA384
;
1206 else if (algoName
== DNSName("hmac-sha512"))
1207 algoEnum
= TSIG_SHA512
;
1208 else if (algoName
== DNSName("gss-tsig"))
1209 algoEnum
= TSIG_GSS
;
1216 DNSName
getTSIGAlgoName(TSIGHashEnum
& algoEnum
)
1219 case TSIG_MD5
: return DNSName("hmac-md5.sig-alg.reg.int.");
1220 case TSIG_SHA1
: return DNSName("hmac-sha1.");
1221 case TSIG_SHA224
: return DNSName("hmac-sha224.");
1222 case TSIG_SHA256
: return DNSName("hmac-sha256.");
1223 case TSIG_SHA384
: return DNSName("hmac-sha384.");
1224 case TSIG_SHA512
: return DNSName("hmac-sha512.");
1225 case TSIG_GSS
: return DNSName("gss-tsig.");
1227 throw PDNSException("getTSIGAlgoName does not understand given algorithm, please fix!");
1230 uint64_t getOpenFileDescriptors(const std::string
&)
1233 DIR* dirhdl
=opendir(("/proc/"+std::to_string(getpid())+"/fd/").c_str());
1237 struct dirent
*entry
;
1239 while((entry
= readdir(dirhdl
))) {
1242 num
= pdns_stou(entry
->d_name
);
1244 continue; // was not a number.
1246 if(std::to_string(num
) == entry
->d_name
)
1257 uint64_t getRealMemoryUsage(const std::string
&)
1260 ifstream
ifs("/proc/self/statm");
1264 uint64_t size
, resident
, shared
, text
, lib
, data
;
1265 ifs
>> size
>> resident
>> shared
>> text
>> lib
>> data
;
1267 return data
* getpagesize();
1270 if (getrusage(RUSAGE_SELF
, &ru
) != 0)
1272 return ru
.ru_maxrss
* 1024;
1277 uint64_t getSpecialMemoryUsage(const std::string
&)
1280 ifstream
ifs("/proc/self/smaps");
1285 string
header("Private_Dirty:");
1286 while(getline(ifs
, line
)) {
1287 if(boost::starts_with(line
, header
)) {
1288 bytes
+= std::stoull(line
.substr(header
.length() + 1))*1024;
1297 uint64_t getCPUTimeUser(const std::string
&)
1300 getrusage(RUSAGE_SELF
, &ru
);
1301 return (ru
.ru_utime
.tv_sec
*1000ULL + ru
.ru_utime
.tv_usec
/1000);
1304 uint64_t getCPUTimeSystem(const std::string
&)
1307 getrusage(RUSAGE_SELF
, &ru
);
1308 return (ru
.ru_stime
.tv_sec
*1000ULL + ru
.ru_stime
.tv_usec
/1000);
1311 double DiffTime(const struct timespec
& first
, const struct timespec
& second
)
1313 int seconds
=second
.tv_sec
- first
.tv_sec
;
1314 int nseconds
=second
.tv_nsec
- first
.tv_nsec
;
1318 nseconds
+=1000000000;
1320 return seconds
+ nseconds
/1000000000.0;
1323 double DiffTime(const struct timeval
& first
, const struct timeval
& second
)
1325 int seconds
=second
.tv_sec
- first
.tv_sec
;
1326 int useconds
=second
.tv_usec
- first
.tv_usec
;
1332 return seconds
+ useconds
/1000000.0;
1335 uid_t
strToUID(const string
&str
)
1338 const char * cstr
= str
.c_str();
1339 struct passwd
* pwd
= getpwnam(cstr
);
1347 catch(std::exception
& e
) {
1348 throw runtime_error((boost::format("Error: Unable to parse user ID %s") % cstr
).str() );
1351 if (val
< std::numeric_limits
<uid_t
>::min() || val
> std::numeric_limits
<uid_t
>::max()) {
1352 throw runtime_error((boost::format("Error: Unable to parse user ID %s") % cstr
).str() );
1355 result
= static_cast<uid_t
>(val
);
1358 result
= pwd
->pw_uid
;
1364 gid_t
strToGID(const string
&str
)
1367 const char * cstr
= str
.c_str();
1368 struct group
* grp
= getgrnam(cstr
);
1376 catch(std::exception
& e
) {
1377 throw runtime_error((boost::format("Error: Unable to parse group ID %s") % cstr
).str() );
1380 if (val
< std::numeric_limits
<gid_t
>::min() || val
> std::numeric_limits
<gid_t
>::max()) {
1381 throw runtime_error((boost::format("Error: Unable to parse group ID %s") % cstr
).str() );
1384 result
= static_cast<gid_t
>(val
);
1387 result
= grp
->gr_gid
;
1393 unsigned int pdns_stou(const std::string
& str
, size_t * idx
, int base
)
1395 if (str
.empty()) return 0; // compatibility
1396 unsigned long result
;
1398 result
= std::stoul(str
, idx
, base
);
1400 catch(std::invalid_argument
& e
) {
1401 throw std::invalid_argument(string(e
.what()) + "; (invalid argument during std::stoul); data was \""+str
+"\"");
1403 catch(std::out_of_range
& e
) {
1404 throw std::out_of_range(string(e
.what()) + "; (out of range during std::stoul); data was \""+str
+"\"");
1406 if (result
> std::numeric_limits
<unsigned int>::max()) {
1407 throw std::out_of_range("stoul returned result out of unsigned int range; data was \""+str
+"\"");
1409 return static_cast<unsigned int>(result
);
1412 bool isSettingThreadCPUAffinitySupported()
1414 #ifdef HAVE_PTHREAD_SETAFFINITY_NP
1421 int mapThreadToCPUList(pthread_t tid
, const std::set
<int>& cpus
)
1423 #ifdef HAVE_PTHREAD_SETAFFINITY_NP
1426 cpuset
= cpuset_create();
1427 for (const auto cpuID
: cpus
) {
1428 cpuset_set(cpuID
, cpuset
);
1431 return pthread_setaffinity_np(tid
,
1432 cpuset_size(cpuset
),
1436 # define cpu_set_t cpuset_t
1440 for (const auto cpuID
: cpus
) {
1441 CPU_SET(cpuID
, &cpuset
);
1444 return pthread_setaffinity_np(tid
,
1450 #endif /* HAVE_PTHREAD_SETAFFINITY_NP */
1453 std::vector
<ComboAddress
> getResolvers(const std::string
& resolvConfPath
)
1455 std::vector
<ComboAddress
> results
;
1457 ifstream
ifs(resolvConfPath
);
1463 while(std::getline(ifs
, line
)) {
1464 boost::trim_right_if(line
, is_any_of(" \r\n\x1a"));
1465 boost::trim_left(line
); // leading spaces, let's be nice
1467 string::size_type tpos
= line
.find_first_of(";#");
1468 if (tpos
!= string::npos
) {
1472 if (boost::starts_with(line
, "nameserver ") || boost::starts_with(line
, "nameserver\t")) {
1473 vector
<string
> parts
;
1474 stringtok(parts
, line
, " \t,"); // be REALLY nice
1475 for(vector
<string
>::const_iterator iter
= parts
.begin() + 1; iter
!= parts
.end(); ++iter
) {
1477 results
.emplace_back(*iter
, 53);