]>
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>
64 bool g_singleThreaded
;
66 size_t writen2(int fd
, const void *buf
, size_t count
)
68 const char *ptr
= (char*)buf
;
69 const char *eptr
= ptr
+ count
;
73 res
= ::write(fd
, ptr
, eptr
- ptr
);
76 throw std::runtime_error("used writen2 on non-blocking socket, got EAGAIN");
78 unixDie("failed in writen2");
81 throw std::runtime_error("could not write all bytes, got eof in writen2");
89 size_t readn2(int fd
, void* buffer
, size_t len
)
94 res
= read(fd
, (char*)buffer
+ pos
, len
- pos
);
96 throw runtime_error("EOF while reading message");
99 throw std::runtime_error("used readn2 on non-blocking socket, got EAGAIN");
101 unixDie("failed in readn2");
111 size_t readn2WithTimeout(int fd
, void* buffer
, size_t len
, int idleTimeout
, int totalTimeout
)
115 int remainingTime
= totalTimeout
;
121 ssize_t got
= read(fd
, (char *)buffer
+ pos
, len
- pos
);
126 throw runtime_error("EOF while reading message");
129 if (errno
== EAGAIN
) {
130 int res
= waitForData(fd
, (totalTimeout
== 0 || idleTimeout
<= remainingTime
) ? idleTimeout
: remainingTime
);
132 /* there is data available */
135 throw runtime_error("Timeout while waiting for data to read");
137 throw runtime_error("Error while waiting for data to read");
141 unixDie("failed in readn2WithTimeout");
146 time_t now
= time(NULL
);
147 int elapsed
= now
- start
;
148 if (elapsed
>= remainingTime
) {
149 throw runtime_error("Timeout while reading data");
152 remainingTime
-= elapsed
;
160 size_t writen2WithTimeout(int fd
, const void * buffer
, size_t len
, int timeout
)
164 ssize_t written
= write(fd
, (char *)buffer
+ pos
, len
- pos
);
167 pos
+= (size_t) written
;
169 else if (written
== 0)
170 throw runtime_error("EOF while writing message");
172 if (errno
== EAGAIN
) {
173 int res
= waitForRWData(fd
, false, timeout
, 0);
175 /* there is room available */
178 throw runtime_error("Timeout while waiting to write data");
180 throw runtime_error("Error while waiting for room to write data");
184 unixDie("failed in write2WithTimeout");
195 time_t now
= time(nullptr);
196 struct tm
* tm
= localtime(&now
);
198 // YYYY-mm-dd HH:MM:SS TZOFF
199 strftime(buffer
, sizeof(buffer
), "%F %T %z", tm
);
200 buffer
[sizeof(buffer
)-1] = '\0';
204 uint16_t getShort(const unsigned char *p
)
206 return p
[0] * 256 + p
[1];
210 uint16_t getShort(const char *p
)
212 return getShort((const unsigned char *)p
);
215 uint32_t getLong(const unsigned char* p
)
217 return (p
[0]<<24) + (p
[1]<<16) + (p
[2]<<8) + p
[3];
220 uint32_t getLong(const char* p
)
222 return getLong((unsigned char *)p
);
225 static bool ciEqual(const string
& a
, const string
& b
)
227 if(a
.size()!=b
.size())
230 string::size_type pos
=0, epos
=a
.size();
231 for(;pos
< epos
; ++pos
)
232 if(dns_tolower(a
[pos
])!=dns_tolower(b
[pos
]))
237 /** does domain end on suffix? Is smart about "wwwds9a.nl" "ds9a.nl" not matching */
238 static bool endsOn(const string
&domain
, const string
&suffix
)
240 if( suffix
.empty() || ciEqual(domain
, suffix
) )
243 if(domain
.size()<=suffix
.size())
246 string::size_type dpos
=domain
.size()-suffix
.size()-1, spos
=0;
248 if(domain
[dpos
++]!='.')
251 for(; dpos
< domain
.size(); ++dpos
, ++spos
)
252 if(dns_tolower(domain
[dpos
]) != dns_tolower(suffix
[spos
]))
258 /** strips a domain suffix from a domain, returns true if it stripped */
259 bool stripDomainSuffix(string
*qname
, const string
&domain
)
261 if(!endsOn(*qname
, domain
))
264 if(toLower(*qname
)==toLower(domain
))
267 if((*qname
)[qname
->size()-domain
.size()-1]!='.')
270 qname
->resize(qname
->size()-domain
.size()-1);
275 static void parseService4(const string
&descr
, ServiceTuple
&st
)
278 stringtok(parts
,descr
,":");
280 throw PDNSException("Unable to parse '"+descr
+"' as a service");
283 st
.port
=pdns_stou(parts
[1]);
286 static void parseService6(const string
&descr
, ServiceTuple
&st
)
288 string::size_type pos
=descr
.find(']');
289 if(pos
== string::npos
)
290 throw PDNSException("Unable to parse '"+descr
+"' as an IPv6 service");
292 st
.host
=descr
.substr(1, pos
-1);
293 if(pos
+ 2 < descr
.length())
294 st
.port
=pdns_stou(descr
.substr(pos
+2));
298 void parseService(const string
&descr
, ServiceTuple
&st
)
301 throw PDNSException("Unable to parse '"+descr
+"' as a service");
303 vector
<string
> parts
;
304 stringtok(parts
, descr
, ":");
307 parseService6(descr
, st
);
309 else if(descr
[0]==':' || parts
.size() > 2 || descr
.find("::") != string::npos
) {
313 parseService4(descr
, st
);
317 // returns -1 in case if error, 0 if no data is available, 1 if there is. In the first two cases, errno is set
318 int waitForData(int fd
, int seconds
, int useconds
)
320 return waitForRWData(fd
, true, seconds
, useconds
);
323 int waitForRWData(int fd
, bool waitForRead
, int seconds
, int useconds
, bool* error
, bool* disconnected
)
328 memset(&pfd
, 0, sizeof(pfd
));
336 ret
= poll(&pfd
, 1, seconds
* 1000 + useconds
/1000);
338 if (error
&& (pfd
.revents
& POLLERR
)) {
341 if (disconnected
&& (pfd
.revents
& POLLHUP
)) {
342 *disconnected
= true;
349 // returns -1 in case of error, 0 if no data is available, 1 if there is. In the first two cases, errno is set
350 int waitFor2Data(int fd1
, int fd2
, int seconds
, int useconds
, int*fd
)
354 struct pollfd pfds
[2];
355 memset(&pfds
[0], 0, 2*sizeof(struct pollfd
));
359 pfds
[0].events
= pfds
[1].events
= POLLIN
;
361 int nsocks
= 1 + (fd2
>= 0); // fd2 can optionally be -1
364 ret
= poll(pfds
, nsocks
, seconds
* 1000 + useconds
/1000);
366 ret
= poll(pfds
, nsocks
, -1);
370 if((pfds
[0].revents
& POLLIN
) && !(pfds
[1].revents
& POLLIN
))
372 else if((pfds
[1].revents
& POLLIN
) && !(pfds
[0].revents
& POLLIN
))
375 *fd
= pfds
[random()%2].fd
;
378 *fd
= -1; // should never happen
384 string
humanDuration(time_t passed
)
388 ret
<<passed
<<" seconds";
390 ret
<<std::setprecision(2)<<passed
/60.0<<" minutes";
391 else if(passed
<86400)
392 ret
<<std::setprecision(3)<<passed
/3600.0<<" hours";
393 else if(passed
<(86400*30.41))
394 ret
<<std::setprecision(3)<<passed
/86400.0<<" days";
396 ret
<<std::setprecision(3)<<passed
/(86400*30.41)<<" months";
403 // set(); // saves lots of gettimeofday calls
404 d_set
.tv_sec
=d_set
.tv_usec
=0;
407 DTime::DTime(const DTime
&dt
)
417 const string
unquotify(const string
&item
)
422 string::size_type bpos
=0, epos
=item
.size();
427 if(item
[epos
-1]=='"')
430 return item
.substr(bpos
,epos
-bpos
);
433 void stripLine(string
&line
)
435 string::size_type pos
=line
.find_first_of("\r\n");
436 if(pos
!=string::npos
) {
441 string
urlEncode(const string
&text
)
444 for(string::const_iterator i
=text
.begin();i
!=text
.end();++i
)
445 if(*i
==' ')ret
.append("%20");
446 else ret
.append(1,*i
);
452 #ifndef MAXHOSTNAMELEN
453 #define MAXHOSTNAMELEN 255
456 char tmp
[MAXHOSTNAMELEN
];
457 if(gethostname(tmp
, MAXHOSTNAMELEN
))
470 string
uitoa(unsigned int i
) // MSVC 6 doesn't grok overloading (un)signed
477 string
bitFlip(const string
&str
)
479 string::size_type pos
=0, epos
=str
.size();
482 for(;pos
< epos
; ++pos
)
483 ret
.append(1, ~str
[pos
]);
489 return strerror(errno
);
492 string
netstringerror()
494 return stringerror();
497 void cleanSlashes(string
&str
)
499 string::const_iterator i
;
501 for(i
=str
.begin();i
!=str
.end();++i
) {
502 if(*i
=='/' && i
!=str
.begin() && *(i
-1)=='/')
510 bool IpToU32(const string
&str
, uint32_t *ip
)
518 if(inet_aton(str
.c_str(), &inp
)) {
525 string
U32ToIP(uint32_t val
)
528 snprintf(tmp
, sizeof(tmp
)-1, "%u.%u.%u.%u",
537 string
makeHexDump(const string
& str
)
541 ret
.reserve((int)(str
.size()*2.2));
543 for(string::size_type n
=0;n
<str
.size();++n
) {
544 sprintf(tmp
,"%02x ", (unsigned char)str
[n
]);
550 // shuffle, maintaining some semblance of order
551 void shuffle(vector
<DNSZoneRecord
>& rrs
)
553 vector
<DNSZoneRecord
>::iterator first
, second
;
554 for(first
=rrs
.begin();first
!=rrs
.end();++first
)
555 if(first
->dr
.d_place
==DNSResourceRecord::ANSWER
&& first
->dr
.d_type
!= QType::CNAME
) // CNAME must come first
557 for(second
=first
;second
!=rrs
.end();++second
)
558 if(second
->dr
.d_place
!=DNSResourceRecord::ANSWER
)
562 random_shuffle(first
,second
);
564 // now shuffle the additional records
565 for(first
=second
;first
!=rrs
.end();++first
)
566 if(first
->dr
.d_place
==DNSResourceRecord::ADDITIONAL
&& first
->dr
.d_type
!= QType::CNAME
) // CNAME must come first
568 for(second
=first
;second
!=rrs
.end();++second
)
569 if(second
->dr
.d_place
!=DNSResourceRecord::ADDITIONAL
)
573 random_shuffle(first
,second
);
575 // we don't shuffle the rest
579 // shuffle, maintaining some semblance of order
580 void shuffle(vector
<DNSRecord
>& rrs
)
582 vector
<DNSRecord
>::iterator first
, second
;
583 for(first
=rrs
.begin();first
!=rrs
.end();++first
)
584 if(first
->d_place
==DNSResourceRecord::ANSWER
&& first
->d_type
!= QType::CNAME
) // CNAME must come first
586 for(second
=first
;second
!=rrs
.end();++second
)
587 if(second
->d_place
!=DNSResourceRecord::ANSWER
|| second
->d_type
== QType::RRSIG
) // leave RRSIGs at the end
591 random_shuffle(first
,second
);
593 // now shuffle the additional records
594 for(first
=second
;first
!=rrs
.end();++first
)
595 if(first
->d_place
==DNSResourceRecord::ADDITIONAL
&& first
->d_type
!= QType::CNAME
) // CNAME must come first
597 for(second
=first
; second
!=rrs
.end(); ++second
)
598 if(second
->d_place
!=DNSResourceRecord::ADDITIONAL
)
602 random_shuffle(first
,second
);
604 // we don't shuffle the rest
607 static uint16_t mapTypesToOrder(uint16_t type
)
609 if(type
== QType::CNAME
)
611 if(type
== QType::RRSIG
)
617 // make sure rrs is sorted in d_place order to avoid surprises later
618 // then shuffle the parts that desire shuffling
619 void orderAndShuffle(vector
<DNSRecord
>& rrs
)
621 std::stable_sort(rrs
.begin(), rrs
.end(), [](const DNSRecord
&a
, const DNSRecord
& b
) {
622 return std::make_tuple(a
.d_place
, mapTypesToOrder(a
.d_type
)) < std::make_tuple(b
.d_place
, mapTypesToOrder(b
.d_type
));
627 void normalizeTV(struct timeval
& tv
)
629 if(tv
.tv_usec
> 1000000) {
633 else if(tv
.tv_usec
< 0) {
639 const struct timeval
operator+(const struct timeval
& lhs
, const struct timeval
& rhs
)
642 ret
.tv_sec
=lhs
.tv_sec
+ rhs
.tv_sec
;
643 ret
.tv_usec
=lhs
.tv_usec
+ rhs
.tv_usec
;
648 const struct timeval
operator-(const struct timeval
& lhs
, const struct timeval
& rhs
)
651 ret
.tv_sec
=lhs
.tv_sec
- rhs
.tv_sec
;
652 ret
.tv_usec
=lhs
.tv_usec
- rhs
.tv_usec
;
657 pair
<string
, string
> splitField(const string
& inp
, char sepa
)
659 pair
<string
, string
> ret
;
660 string::size_type cpos
=inp
.find(sepa
);
661 if(cpos
==string::npos
)
664 ret
.first
=inp
.substr(0, cpos
);
665 ret
.second
=inp
.substr(cpos
+1);
670 int logFacilityToLOG(unsigned int facility
)
694 string
stripDot(const string
& dom
)
699 if(dom
[dom
.size()-1]!='.')
702 return dom
.substr(0,dom
.size()-1);
707 int makeIPv6sockaddr(const std::string
& addr
, struct sockaddr_in6
* ret
)
711 string
ourAddr(addr
);
712 bool portSet
= false;
714 if(addr
[0]=='[') { // [::]:53 style address
715 string::size_type pos
= addr
.find(']');
716 if(pos
== string::npos
|| pos
+ 2 > addr
.size() || addr
[pos
+1]!=':')
718 ourAddr
.assign(addr
.c_str() + 1, pos
-1);
720 port
= pdns_stou(addr
.substr(pos
+2));
723 catch(const std::out_of_range
&) {
727 ret
->sin6_scope_id
=0;
728 ret
->sin6_family
=AF_INET6
;
730 if(inet_pton(AF_INET6
, ourAddr
.c_str(), (void*)&ret
->sin6_addr
) != 1) {
731 struct addrinfo
* res
;
732 struct addrinfo hints
;
733 memset(&hints
, 0, sizeof(hints
));
735 hints
.ai_family
= AF_INET6
;
736 hints
.ai_flags
= AI_NUMERICHOST
;
739 // getaddrinfo has anomalous return codes, anything nonzero is an error, positive or negative
740 if((error
=getaddrinfo(ourAddr
.c_str(), 0, &hints
, &res
))) {
744 memcpy(ret
, res
->ai_addr
, res
->ai_addrlen
);
752 ret
->sin6_port
= htons(port
);
758 int makeIPv4sockaddr(const std::string
& str
, struct sockaddr_in
* ret
)
765 string::size_type pos
= str
.find(':');
766 if(pos
== string::npos
) { // no port specified, not touching the port
767 if(inet_aton(str
.c_str(), &inp
)) {
768 ret
->sin_addr
.s_addr
=inp
.s_addr
;
773 if(!*(str
.c_str() + pos
+ 1)) // trailing :
776 char *eptr
= (char*)str
.c_str() + str
.size();
777 int port
= strtol(str
.c_str() + pos
+ 1, &eptr
, 10);
778 if (port
< 0 || port
> 65535)
784 ret
->sin_port
= htons(port
);
785 if(inet_aton(str
.substr(0, pos
).c_str(), &inp
)) {
786 ret
->sin_addr
.s_addr
=inp
.s_addr
;
792 int makeUNsockaddr(const std::string
& path
, struct sockaddr_un
* ret
)
797 memset(ret
, 0, sizeof(struct sockaddr_un
));
798 ret
->sun_family
= AF_UNIX
;
799 if (path
.length() >= sizeof(ret
->sun_path
))
802 path
.copy(ret
->sun_path
, sizeof(ret
->sun_path
), 0);
806 //! read a line of text from a FILE* to a std::string, returns false on 'no data'
807 bool stringfgets(FILE* fp
, std::string
& line
)
813 if(!fgets(buffer
, sizeof(buffer
), fp
))
814 return !line
.empty();
817 } while(!strchr(buffer
, '\n'));
821 bool readFileIfThere(const char* fname
, std::string
* line
)
824 FILE* fp
= fopen(fname
, "r");
827 stringfgets(fp
, *line
);
832 Regex::Regex(const string
&expr
)
834 if(regcomp(&d_preg
, expr
.c_str(), REG_ICASE
|REG_NOSUB
|REG_EXTENDED
))
835 throw PDNSException("Regular expression did not compile");
838 // if you end up here because valgrind told you were are doing something wrong
839 // with msgh->msg_controllen, please refer to https://github.com/PowerDNS/pdns/pull/3962
841 void addCMsgSrcAddr(struct msghdr
* msgh
, void* cmsgbuf
, const ComboAddress
* source
, int itfIndex
)
843 struct cmsghdr
*cmsg
= NULL
;
845 if(source
->sin4
.sin_family
== AF_INET6
) {
846 struct in6_pktinfo
*pkt
;
848 msgh
->msg_control
= cmsgbuf
;
849 msgh
->msg_controllen
= CMSG_SPACE(sizeof(*pkt
));
851 cmsg
= CMSG_FIRSTHDR(msgh
);
852 cmsg
->cmsg_level
= IPPROTO_IPV6
;
853 cmsg
->cmsg_type
= IPV6_PKTINFO
;
854 cmsg
->cmsg_len
= CMSG_LEN(sizeof(*pkt
));
856 pkt
= (struct in6_pktinfo
*) CMSG_DATA(cmsg
);
857 memset(pkt
, 0, sizeof(*pkt
));
858 pkt
->ipi6_addr
= source
->sin6
.sin6_addr
;
859 pkt
->ipi6_ifindex
= itfIndex
;
863 struct in_pktinfo
*pkt
;
865 msgh
->msg_control
= cmsgbuf
;
866 msgh
->msg_controllen
= CMSG_SPACE(sizeof(*pkt
));
868 cmsg
= CMSG_FIRSTHDR(msgh
);
869 cmsg
->cmsg_level
= IPPROTO_IP
;
870 cmsg
->cmsg_type
= IP_PKTINFO
;
871 cmsg
->cmsg_len
= CMSG_LEN(sizeof(*pkt
));
873 pkt
= (struct in_pktinfo
*) CMSG_DATA(cmsg
);
874 memset(pkt
, 0, sizeof(*pkt
));
875 pkt
->ipi_spec_dst
= source
->sin4
.sin_addr
;
876 pkt
->ipi_ifindex
= itfIndex
;
878 #ifdef IP_SENDSRCADDR
881 msgh
->msg_control
= cmsgbuf
;
882 msgh
->msg_controllen
= CMSG_SPACE(sizeof(*in
));
884 cmsg
= CMSG_FIRSTHDR(msgh
);
885 cmsg
->cmsg_level
= IPPROTO_IP
;
886 cmsg
->cmsg_type
= IP_SENDSRCADDR
;
887 cmsg
->cmsg_len
= CMSG_LEN(sizeof(*in
));
889 in
= (struct in_addr
*) CMSG_DATA(cmsg
);
890 *in
= source
->sin4
.sin_addr
;
895 unsigned int getFilenumLimit(bool hardOrSoft
)
898 if(getrlimit(RLIMIT_NOFILE
, &rlim
) < 0)
899 unixDie("Requesting number of available file descriptors");
900 return hardOrSoft
? rlim
.rlim_max
: rlim
.rlim_cur
;
903 void setFilenumLimit(unsigned int lim
)
907 if(getrlimit(RLIMIT_NOFILE
, &rlim
) < 0)
908 unixDie("Requesting number of available file descriptors");
910 if(setrlimit(RLIMIT_NOFILE
, &rlim
) < 0)
911 unixDie("Setting number of available file descriptors");
914 #define burtlemix(a,b,c) \
916 a -= b; a -= c; a ^= (c>>13); \
917 b -= c; b -= a; b ^= (a<<8); \
918 c -= a; c -= b; c ^= (b>>13); \
919 a -= b; a -= c; a ^= (c>>12); \
920 b -= c; b -= a; b ^= (a<<16); \
921 c -= a; c -= b; c ^= (b>>5); \
922 a -= b; a -= c; a ^= (c>>3); \
923 b -= c; b -= a; b ^= (a<<10); \
924 c -= a; c -= b; c ^= (b>>15); \
927 uint32_t burtle(const unsigned char* k
, uint32_t length
, uint32_t initval
)
931 /* Set up the internal state */
933 a
= b
= 0x9e3779b9; /* the golden ratio; an arbitrary value */
934 c
= initval
; /* the previous hash value */
936 /*---------------------------------------- handle most of the key */
938 a
+= (k
[0] +((uint32_t)k
[1]<<8) +((uint32_t)k
[2]<<16) +((uint32_t)k
[3]<<24));
939 b
+= (k
[4] +((uint32_t)k
[5]<<8) +((uint32_t)k
[6]<<16) +((uint32_t)k
[7]<<24));
940 c
+= (k
[8] +((uint32_t)k
[9]<<8) +((uint32_t)k
[10]<<16)+((uint32_t)k
[11]<<24));
945 /*------------------------------------- handle the last 11 bytes */
947 switch(len
) { /* all the case statements fall through */
948 case 11: c
+=((uint32_t)k
[10]<<24);
949 case 10: c
+=((uint32_t)k
[9]<<16);
950 case 9 : c
+=((uint32_t)k
[8]<<8);
951 /* the first byte of c is reserved for the length */
952 case 8 : b
+=((uint32_t)k
[7]<<24);
953 case 7 : b
+=((uint32_t)k
[6]<<16);
954 case 6 : b
+=((uint32_t)k
[5]<<8);
956 case 4 : a
+=((uint32_t)k
[3]<<24);
957 case 3 : a
+=((uint32_t)k
[2]<<16);
958 case 2 : a
+=((uint32_t)k
[1]<<8);
960 /* case 0: nothing left to add */
963 /*-------------------------------------------- report the result */
967 uint32_t burtleCI(const unsigned char* k
, uint32_t length
, uint32_t initval
)
971 /* Set up the internal state */
973 a
= b
= 0x9e3779b9; /* the golden ratio; an arbitrary value */
974 c
= initval
; /* the previous hash value */
976 /*---------------------------------------- handle most of the key */
978 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));
979 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));
980 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));
985 /*------------------------------------- handle the last 11 bytes */
987 switch(len
) { /* all the case statements fall through */
988 case 11: c
+=((uint32_t)dns_tolower(k
[10])<<24);
989 case 10: c
+=((uint32_t)dns_tolower(k
[9])<<16);
990 case 9 : c
+=((uint32_t)dns_tolower(k
[8])<<8);
991 /* the first byte of c is reserved for the length */
992 case 8 : b
+=((uint32_t)dns_tolower(k
[7])<<24);
993 case 7 : b
+=((uint32_t)dns_tolower(k
[6])<<16);
994 case 6 : b
+=((uint32_t)dns_tolower(k
[5])<<8);
995 case 5 : b
+=dns_tolower(k
[4]);
996 case 4 : a
+=((uint32_t)dns_tolower(k
[3])<<24);
997 case 3 : a
+=((uint32_t)dns_tolower(k
[2])<<16);
998 case 2 : a
+=((uint32_t)dns_tolower(k
[1])<<8);
999 case 1 : a
+=dns_tolower(k
[0]);
1000 /* case 0: nothing left to add */
1003 /*-------------------------------------------- report the result */
1008 bool setSocketTimestamps(int fd
)
1012 return setsockopt(fd
, SOL_SOCKET
, SO_TIMESTAMP
, (char*)&on
, sizeof(on
)) == 0;
1014 return true; // we pretend this happened.
1017 bool setTCPNoDelay(int sock
)
1020 return setsockopt(sock
, /* socket affected */
1021 IPPROTO_TCP
, /* set option at TCP level */
1022 TCP_NODELAY
, /* name of option */
1023 (char *) &flag
, /* the cast is historical cruft */
1024 sizeof(flag
)) == 0; /* length of option value */
1028 bool setNonBlocking(int sock
)
1030 int flags
=fcntl(sock
,F_GETFL
,0);
1031 if(flags
<0 || fcntl(sock
, F_SETFL
,flags
|O_NONBLOCK
) <0)
1036 bool setBlocking(int sock
)
1038 int flags
=fcntl(sock
,F_GETFL
,0);
1039 if(flags
<0 || fcntl(sock
, F_SETFL
,flags
&(~O_NONBLOCK
)) <0)
1044 bool isNonBlocking(int sock
)
1046 int flags
=fcntl(sock
,F_GETFL
,0);
1047 return flags
& O_NONBLOCK
;
1051 int closesocket( int socket
)
1053 int ret
=::close(socket
);
1054 if(ret
< 0 && errno
== ECONNRESET
) // see ticket 192, odd BSD behaviour
1057 throw PDNSException("Error closing socket: "+stringerror());
1061 bool setCloseOnExec(int sock
)
1063 int flags
=fcntl(sock
,F_GETFD
,0);
1064 if(flags
<0 || fcntl(sock
, F_SETFD
,flags
|FD_CLOEXEC
) <0)
1069 string
getMACAddress(const ComboAddress
& ca
)
1073 ifstream
ifs("/proc/net/arp");
1077 string match
=ca
.toString()+' ';
1078 while(getline(ifs
, line
)) {
1079 if(boost::starts_with(line
, match
)) {
1080 vector
<string
> parts
;
1081 stringtok(parts
, line
, " \n\t\r");
1082 if(parts
.size() < 4)
1084 unsigned int tmp
[6];
1085 sscanf(parts
[3].c_str(), "%02x:%02x:%02x:%02x:%02x:%02x", tmp
, tmp
+1, tmp
+2, tmp
+3, tmp
+4, tmp
+5);
1086 for(int i
= 0 ; i
< 6 ; ++i
)
1087 ret
.append(1, (char)tmp
[i
]);
1095 uint64_t udpErrorStats(const std::string
& str
)
1098 ifstream
ifs("/proc/net/snmp");
1102 vector
<string
> parts
;
1103 while(getline(ifs
,line
)) {
1104 if(boost::starts_with(line
, "Udp: ") && isdigit(line
[5])) {
1105 stringtok(parts
, line
, " \n\t\r");
1106 if(parts
.size() < 7)
1108 if(str
=="udp-rcvbuf-errors")
1109 return std::stoull(parts
[5]);
1110 else if(str
=="udp-sndbuf-errors")
1111 return std::stoull(parts
[6]);
1112 else if(str
=="udp-noport-errors")
1113 return std::stoull(parts
[2]);
1114 else if(str
=="udp-in-errors")
1115 return std::stoull(parts
[3]);
1124 bool getTSIGHashEnum(const DNSName
& algoName
, TSIGHashEnum
& algoEnum
)
1126 if (algoName
== DNSName("hmac-md5.sig-alg.reg.int") || algoName
== DNSName("hmac-md5"))
1127 algoEnum
= TSIG_MD5
;
1128 else if (algoName
== DNSName("hmac-sha1"))
1129 algoEnum
= TSIG_SHA1
;
1130 else if (algoName
== DNSName("hmac-sha224"))
1131 algoEnum
= TSIG_SHA224
;
1132 else if (algoName
== DNSName("hmac-sha256"))
1133 algoEnum
= TSIG_SHA256
;
1134 else if (algoName
== DNSName("hmac-sha384"))
1135 algoEnum
= TSIG_SHA384
;
1136 else if (algoName
== DNSName("hmac-sha512"))
1137 algoEnum
= TSIG_SHA512
;
1138 else if (algoName
== DNSName("gss-tsig"))
1139 algoEnum
= TSIG_GSS
;
1146 DNSName
getTSIGAlgoName(TSIGHashEnum
& algoEnum
)
1149 case TSIG_MD5
: return DNSName("hmac-md5.sig-alg.reg.int.");
1150 case TSIG_SHA1
: return DNSName("hmac-sha1.");
1151 case TSIG_SHA224
: return DNSName("hmac-sha224.");
1152 case TSIG_SHA256
: return DNSName("hmac-sha256.");
1153 case TSIG_SHA384
: return DNSName("hmac-sha384.");
1154 case TSIG_SHA512
: return DNSName("hmac-sha512.");
1155 case TSIG_GSS
: return DNSName("gss-tsig.");
1157 throw PDNSException("getTSIGAlgoName does not understand given algorithm, please fix!");
1160 uint64_t getOpenFileDescriptors(const std::string
&)
1163 DIR* dirhdl
=opendir(("/proc/"+std::to_string(getpid())+"/fd/").c_str());
1167 struct dirent
*entry
;
1169 while((entry
= readdir(dirhdl
))) {
1172 num
= pdns_stou(entry
->d_name
);
1174 continue; // was not a number.
1176 if(std::to_string(num
) == entry
->d_name
)
1187 uint64_t getRealMemoryUsage(const std::string
&)
1190 ifstream
ifs("/proc/"+std::to_string(getpid())+"/smaps");
1195 string
header("Private_Dirty:");
1196 while(getline(ifs
, line
)) {
1197 if(boost::starts_with(line
, header
)) {
1198 bytes
+= std::stoull(line
.substr(header
.length() + 1))*1024;
1207 uint64_t getCPUTimeUser(const std::string
&)
1210 getrusage(RUSAGE_SELF
, &ru
);
1211 return (ru
.ru_utime
.tv_sec
*1000ULL + ru
.ru_utime
.tv_usec
/1000);
1214 uint64_t getCPUTimeSystem(const std::string
&)
1217 getrusage(RUSAGE_SELF
, &ru
);
1218 return (ru
.ru_stime
.tv_sec
*1000ULL + ru
.ru_stime
.tv_usec
/1000);
1221 double DiffTime(const struct timespec
& first
, const struct timespec
& second
)
1223 int seconds
=second
.tv_sec
- first
.tv_sec
;
1224 int nseconds
=second
.tv_nsec
- first
.tv_nsec
;
1228 nseconds
+=1000000000;
1230 return seconds
+ nseconds
/1000000000.0;
1233 double DiffTime(const struct timeval
& first
, const struct timeval
& second
)
1235 int seconds
=second
.tv_sec
- first
.tv_sec
;
1236 int useconds
=second
.tv_usec
- first
.tv_usec
;
1242 return seconds
+ useconds
/1000000.0;
1245 uid_t
strToUID(const string
&str
)
1248 const char * cstr
= str
.c_str();
1249 struct passwd
* pwd
= getpwnam(cstr
);
1257 catch(std::exception
& e
) {
1258 throw runtime_error((boost::format("Error: Unable to parse user ID %s") % cstr
).str() );
1261 if (val
< std::numeric_limits
<uid_t
>::min() || val
> std::numeric_limits
<uid_t
>::max()) {
1262 throw runtime_error((boost::format("Error: Unable to parse user ID %s") % cstr
).str() );
1265 result
= static_cast<uid_t
>(val
);
1268 result
= pwd
->pw_uid
;
1274 gid_t
strToGID(const string
&str
)
1277 const char * cstr
= str
.c_str();
1278 struct group
* grp
= getgrnam(cstr
);
1286 catch(std::exception
& e
) {
1287 throw runtime_error((boost::format("Error: Unable to parse group ID %s") % cstr
).str() );
1290 if (val
< std::numeric_limits
<gid_t
>::min() || val
> std::numeric_limits
<gid_t
>::max()) {
1291 throw runtime_error((boost::format("Error: Unable to parse group ID %s") % cstr
).str() );
1294 result
= static_cast<gid_t
>(val
);
1297 result
= grp
->gr_gid
;
1303 unsigned int pdns_stou(const std::string
& str
, size_t * idx
, int base
)
1305 if (str
.empty()) return 0; // compatibility
1306 unsigned long result
= std::stoul(str
, idx
, base
);
1307 if (result
> std::numeric_limits
<unsigned int>::max()) {
1308 throw std::out_of_range("stou");
1310 return static_cast<unsigned int>(result
);
1313 bool isSettingThreadCPUAffinitySupported()
1315 #ifdef HAVE_PTHREAD_SETAFFINITY_NP
1322 int mapThreadToCPUList(pthread_t tid
, const std::set
<int>& cpus
)
1324 #ifdef HAVE_PTHREAD_SETAFFINITY_NP
1326 # define cpu_set_t cpuset_t
1330 for (const auto cpuID
: cpus
) {
1331 CPU_SET(cpuID
, &cpuset
);
1334 return pthread_setaffinity_np(tid
,
1337 #endif /* HAVE_PTHREAD_SETAFFINITY_NP */