]>
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 size_t writen2(int fd
, const void *buf
, size_t count
)
70 const char *ptr
= (char*)buf
;
71 const char *eptr
= ptr
+ count
;
75 res
= ::write(fd
, ptr
, eptr
- ptr
);
78 throw std::runtime_error("used writen2 on non-blocking socket, got EAGAIN");
80 unixDie("failed in writen2");
83 throw std::runtime_error("could not write all bytes, got eof in writen2");
91 size_t readn2(int fd
, void* buffer
, size_t len
)
96 res
= read(fd
, (char*)buffer
+ pos
, len
- pos
);
98 throw runtime_error("EOF while reading message");
101 throw std::runtime_error("used readn2 on non-blocking socket, got EAGAIN");
103 unixDie("failed in readn2");
113 size_t readn2WithTimeout(int fd
, void* buffer
, size_t len
, int idleTimeout
, int totalTimeout
)
117 int remainingTime
= totalTimeout
;
123 ssize_t got
= read(fd
, (char *)buffer
+ pos
, len
- pos
);
128 throw runtime_error("EOF while reading message");
131 if (errno
== EAGAIN
) {
132 int res
= waitForData(fd
, (totalTimeout
== 0 || idleTimeout
<= remainingTime
) ? idleTimeout
: remainingTime
);
134 /* there is data available */
137 throw runtime_error("Timeout while waiting for data to read");
139 throw runtime_error("Error while waiting for data to read");
143 unixDie("failed in readn2WithTimeout");
148 time_t now
= time(NULL
);
149 int elapsed
= now
- start
;
150 if (elapsed
>= remainingTime
) {
151 throw runtime_error("Timeout while reading data");
154 remainingTime
-= elapsed
;
162 size_t writen2WithTimeout(int fd
, const void * buffer
, size_t len
, int timeout
)
166 ssize_t written
= write(fd
, (char *)buffer
+ pos
, len
- pos
);
169 pos
+= (size_t) written
;
171 else if (written
== 0)
172 throw runtime_error("EOF while writing message");
174 if (errno
== EAGAIN
) {
175 int res
= waitForRWData(fd
, false, timeout
, 0);
177 /* there is room available */
180 throw runtime_error("Timeout while waiting to write data");
182 throw runtime_error("Error while waiting for room to write data");
186 unixDie("failed in write2WithTimeout");
197 time_t now
= time(nullptr);
199 localtime_r(&now
, &tm
);
201 // YYYY-mm-dd HH:MM:SS TZOFF
202 strftime(buffer
, sizeof(buffer
), "%F %T %z", &tm
);
203 buffer
[sizeof(buffer
)-1] = '\0';
204 return string(buffer
);
207 uint16_t getShort(const unsigned char *p
)
209 return p
[0] * 256 + p
[1];
213 uint16_t getShort(const char *p
)
215 return getShort((const unsigned char *)p
);
218 uint32_t getLong(const unsigned char* p
)
220 return (p
[0]<<24) + (p
[1]<<16) + (p
[2]<<8) + p
[3];
223 uint32_t getLong(const char* p
)
225 return getLong((unsigned char *)p
);
228 static bool ciEqual(const string
& a
, const string
& b
)
230 if(a
.size()!=b
.size())
233 string::size_type pos
=0, epos
=a
.size();
234 for(;pos
< epos
; ++pos
)
235 if(dns_tolower(a
[pos
])!=dns_tolower(b
[pos
]))
240 /** does domain end on suffix? Is smart about "wwwds9a.nl" "ds9a.nl" not matching */
241 static bool endsOn(const string
&domain
, const string
&suffix
)
243 if( suffix
.empty() || ciEqual(domain
, suffix
) )
246 if(domain
.size()<=suffix
.size())
249 string::size_type dpos
=domain
.size()-suffix
.size()-1, spos
=0;
251 if(domain
[dpos
++]!='.')
254 for(; dpos
< domain
.size(); ++dpos
, ++spos
)
255 if(dns_tolower(domain
[dpos
]) != dns_tolower(suffix
[spos
]))
261 /** strips a domain suffix from a domain, returns true if it stripped */
262 bool stripDomainSuffix(string
*qname
, const string
&domain
)
264 if(!endsOn(*qname
, domain
))
267 if(toLower(*qname
)==toLower(domain
))
270 if((*qname
)[qname
->size()-domain
.size()-1]!='.')
273 qname
->resize(qname
->size()-domain
.size()-1);
278 static void parseService4(const string
&descr
, ServiceTuple
&st
)
281 stringtok(parts
,descr
,":");
283 throw PDNSException("Unable to parse '"+descr
+"' as a service");
286 st
.port
=pdns_stou(parts
[1]);
289 static void parseService6(const string
&descr
, ServiceTuple
&st
)
291 string::size_type pos
=descr
.find(']');
292 if(pos
== string::npos
)
293 throw PDNSException("Unable to parse '"+descr
+"' as an IPv6 service");
295 st
.host
=descr
.substr(1, pos
-1);
296 if(pos
+ 2 < descr
.length())
297 st
.port
=pdns_stou(descr
.substr(pos
+2));
301 void parseService(const string
&descr
, ServiceTuple
&st
)
304 throw PDNSException("Unable to parse '"+descr
+"' as a service");
306 vector
<string
> parts
;
307 stringtok(parts
, descr
, ":");
310 parseService6(descr
, st
);
312 else if(descr
[0]==':' || parts
.size() > 2 || descr
.find("::") != string::npos
) {
316 parseService4(descr
, st
);
320 // returns -1 in case if error, 0 if no data is available, 1 if there is. In the first two cases, errno is set
321 int waitForData(int fd
, int seconds
, int useconds
)
323 return waitForRWData(fd
, true, seconds
, useconds
);
326 int waitForRWData(int fd
, bool waitForRead
, int seconds
, int useconds
, bool* error
, bool* disconnected
)
331 memset(&pfd
, 0, sizeof(pfd
));
339 ret
= poll(&pfd
, 1, seconds
* 1000 + useconds
/1000);
341 if (error
&& (pfd
.revents
& POLLERR
)) {
344 if (disconnected
&& (pfd
.revents
& POLLHUP
)) {
345 *disconnected
= true;
352 // returns -1 in case of error, 0 if no data is available, 1 if there is. In the first two cases, errno is set
353 int waitForMultiData(const set
<int>& fds
, const int seconds
, const int useconds
, int* fdOut
) {
355 for (const auto& fd
: fds
) {
356 if (fd
>= 0 && realFDs
.count(fd
) == 0) {
361 std::vector
<struct pollfd
> pfds(realFDs
.size());
362 memset(pfds
.data(), 0, realFDs
.size()*sizeof(struct pollfd
));
364 for (const auto& fd
: realFDs
) {
366 pfds
[ctr
].events
= POLLIN
;
372 ret
= poll(pfds
.data(), realFDs
.size(), seconds
* 1000 + useconds
/1000);
374 ret
= poll(pfds
.data(), realFDs
.size(), -1);
379 for (const auto& pfd
: pfds
) {
380 if (pfd
.revents
& POLLIN
) {
381 pollinFDs
.insert(pfd
.fd
);
384 set
<int>::const_iterator
it(pollinFDs
.begin());
385 advance(it
, random() % pollinFDs
.size());
390 // returns -1 in case of error, 0 if no data is available, 1 if there is. In the first two cases, errno is set
391 int waitFor2Data(int fd1
, int fd2
, int seconds
, int useconds
, int*fd
)
395 struct pollfd pfds
[2];
396 memset(&pfds
[0], 0, 2*sizeof(struct pollfd
));
400 pfds
[0].events
= pfds
[1].events
= POLLIN
;
402 int nsocks
= 1 + (fd2
>= 0); // fd2 can optionally be -1
405 ret
= poll(pfds
, nsocks
, seconds
* 1000 + useconds
/1000);
407 ret
= poll(pfds
, nsocks
, -1);
411 if((pfds
[0].revents
& POLLIN
) && !(pfds
[1].revents
& POLLIN
))
413 else if((pfds
[1].revents
& POLLIN
) && !(pfds
[0].revents
& POLLIN
))
416 *fd
= pfds
[random()%2].fd
;
419 *fd
= -1; // should never happen
425 string
humanDuration(time_t passed
)
429 ret
<<passed
<<" seconds";
431 ret
<<std::setprecision(2)<<passed
/60.0<<" minutes";
432 else if(passed
<86400)
433 ret
<<std::setprecision(3)<<passed
/3600.0<<" hours";
434 else if(passed
<(86400*30.41))
435 ret
<<std::setprecision(3)<<passed
/86400.0<<" days";
437 ret
<<std::setprecision(3)<<passed
/(86400*30.41)<<" months";
444 // set(); // saves lots of gettimeofday calls
445 d_set
.tv_sec
=d_set
.tv_usec
=0;
453 const string
unquotify(const string
&item
)
458 string::size_type bpos
=0, epos
=item
.size();
463 if(item
[epos
-1]=='"')
466 return item
.substr(bpos
,epos
-bpos
);
469 void stripLine(string
&line
)
471 string::size_type pos
=line
.find_first_of("\r\n");
472 if(pos
!=string::npos
) {
477 string
urlEncode(const string
&text
)
480 for(string::const_iterator i
=text
.begin();i
!=text
.end();++i
)
481 if(*i
==' ')ret
.append("%20");
482 else ret
.append(1,*i
);
488 #ifndef MAXHOSTNAMELEN
489 #define MAXHOSTNAMELEN 255
492 char tmp
[MAXHOSTNAMELEN
];
493 if(gethostname(tmp
, MAXHOSTNAMELEN
))
506 string
uitoa(unsigned int i
) // MSVC 6 doesn't grok overloading (un)signed
513 string
bitFlip(const string
&str
)
515 string::size_type pos
=0, epos
=str
.size();
518 for(;pos
< epos
; ++pos
)
519 ret
.append(1, ~str
[pos
]);
523 string
stringerror(int err
)
525 return strerror(err
);
530 return strerror(errno
);
533 void cleanSlashes(string
&str
)
535 string::const_iterator i
;
537 for(i
=str
.begin();i
!=str
.end();++i
) {
538 if(*i
=='/' && i
!=str
.begin() && *(i
-1)=='/')
546 bool IpToU32(const string
&str
, uint32_t *ip
)
554 if(inet_aton(str
.c_str(), &inp
)) {
561 string
U32ToIP(uint32_t val
)
564 snprintf(tmp
, sizeof(tmp
), "%u.%u.%u.%u",
573 string
makeHexDump(const string
& str
)
577 ret
.reserve((int)(str
.size()*2.2));
579 for(string::size_type n
=0;n
<str
.size();++n
) {
580 snprintf(tmp
, sizeof(tmp
), "%02x ", (unsigned char)str
[n
]);
586 void normalizeTV(struct timeval
& tv
)
588 if(tv
.tv_usec
> 1000000) {
592 else if(tv
.tv_usec
< 0) {
598 const struct timeval
operator+(const struct timeval
& lhs
, const struct timeval
& rhs
)
601 ret
.tv_sec
=lhs
.tv_sec
+ rhs
.tv_sec
;
602 ret
.tv_usec
=lhs
.tv_usec
+ rhs
.tv_usec
;
607 const struct timeval
operator-(const struct timeval
& lhs
, const struct timeval
& rhs
)
610 ret
.tv_sec
=lhs
.tv_sec
- rhs
.tv_sec
;
611 ret
.tv_usec
=lhs
.tv_usec
- rhs
.tv_usec
;
616 pair
<string
, string
> splitField(const string
& inp
, char sepa
)
618 pair
<string
, string
> ret
;
619 string::size_type cpos
=inp
.find(sepa
);
620 if(cpos
==string::npos
)
623 ret
.first
=inp
.substr(0, cpos
);
624 ret
.second
=inp
.substr(cpos
+1);
629 int logFacilityToLOG(unsigned int facility
)
653 string
stripDot(const string
& dom
)
658 if(dom
[dom
.size()-1]!='.')
661 return dom
.substr(0,dom
.size()-1);
666 int makeIPv6sockaddr(const std::string
& addr
, struct sockaddr_in6
* ret
)
670 string
ourAddr(addr
);
671 bool portSet
= false;
673 if(addr
[0]=='[') { // [::]:53 style address
674 string::size_type pos
= addr
.find(']');
675 if(pos
== string::npos
)
677 ourAddr
.assign(addr
.c_str() + 1, pos
-1);
678 if (pos
+ 1 != addr
.size()) { // complete after ], no port specified
679 if (pos
+ 2 > addr
.size() || addr
[pos
+1]!=':')
682 port
= pdns_stou(addr
.substr(pos
+2));
685 catch(const std::out_of_range
&) {
690 ret
->sin6_scope_id
=0;
691 ret
->sin6_family
=AF_INET6
;
693 if(inet_pton(AF_INET6
, ourAddr
.c_str(), (void*)&ret
->sin6_addr
) != 1) {
694 struct addrinfo
* res
;
695 struct addrinfo hints
;
696 memset(&hints
, 0, sizeof(hints
));
698 hints
.ai_family
= AF_INET6
;
699 hints
.ai_flags
= AI_NUMERICHOST
;
701 // getaddrinfo has anomalous return codes, anything nonzero is an error, positive or negative
702 if (getaddrinfo(ourAddr
.c_str(), 0, &hints
, &res
) != 0) {
706 memcpy(ret
, res
->ai_addr
, res
->ai_addrlen
);
714 ret
->sin6_port
= htons(port
);
720 int makeIPv4sockaddr(const std::string
& str
, struct sockaddr_in
* ret
)
727 string::size_type pos
= str
.find(':');
728 if(pos
== string::npos
) { // no port specified, not touching the port
729 if(inet_aton(str
.c_str(), &inp
)) {
730 ret
->sin_addr
.s_addr
=inp
.s_addr
;
735 if(!*(str
.c_str() + pos
+ 1)) // trailing :
738 char *eptr
= (char*)str
.c_str() + str
.size();
739 int port
= strtol(str
.c_str() + pos
+ 1, &eptr
, 10);
740 if (port
< 0 || port
> 65535)
746 ret
->sin_port
= htons(port
);
747 if(inet_aton(str
.substr(0, pos
).c_str(), &inp
)) {
748 ret
->sin_addr
.s_addr
=inp
.s_addr
;
754 int makeUNsockaddr(const std::string
& path
, struct sockaddr_un
* ret
)
759 memset(ret
, 0, sizeof(struct sockaddr_un
));
760 ret
->sun_family
= AF_UNIX
;
761 if (path
.length() >= sizeof(ret
->sun_path
))
764 path
.copy(ret
->sun_path
, sizeof(ret
->sun_path
), 0);
768 //! read a line of text from a FILE* to a std::string, returns false on 'no data'
769 bool stringfgets(FILE* fp
, std::string
& line
)
775 if(!fgets(buffer
, sizeof(buffer
), fp
))
776 return !line
.empty();
779 } while(!strchr(buffer
, '\n'));
783 bool readFileIfThere(const char* fname
, std::string
* line
)
786 auto fp
= std::unique_ptr
<FILE, int(*)(FILE*)>(fopen(fname
, "r"), fclose
);
789 stringfgets(fp
.get(), *line
);
795 Regex::Regex(const string
&expr
)
797 if(regcomp(&d_preg
, expr
.c_str(), REG_ICASE
|REG_NOSUB
|REG_EXTENDED
))
798 throw PDNSException("Regular expression did not compile");
801 // if you end up here because valgrind told you were are doing something wrong
802 // with msgh->msg_controllen, please refer to https://github.com/PowerDNS/pdns/pull/3962
804 // Note that cmsgbuf should be aligned the same as a struct cmsghdr
805 void addCMsgSrcAddr(struct msghdr
* msgh
, cmsgbuf_aligned
* cmsgbuf
, const ComboAddress
* source
, int itfIndex
)
807 struct cmsghdr
*cmsg
= NULL
;
809 if(source
->sin4
.sin_family
== AF_INET6
) {
810 struct in6_pktinfo
*pkt
;
812 msgh
->msg_control
= cmsgbuf
;
813 #if !defined( __APPLE__ )
814 /* CMSG_SPACE is not a constexpr on macOS */
815 static_assert(CMSG_SPACE(sizeof(*pkt
)) <= sizeof(*cmsgbuf
), "Buffer is too small for in6_pktinfo");
816 #else /* __APPLE__ */
817 if (CMSG_SPACE(sizeof(*pkt
)) > sizeof(*cmsgbuf
)) {
818 throw std::runtime_error("Buffer is too small for in6_pktinfo");
820 #endif /* __APPLE__ */
821 msgh
->msg_controllen
= CMSG_SPACE(sizeof(*pkt
));
823 cmsg
= CMSG_FIRSTHDR(msgh
);
824 cmsg
->cmsg_level
= IPPROTO_IPV6
;
825 cmsg
->cmsg_type
= IPV6_PKTINFO
;
826 cmsg
->cmsg_len
= CMSG_LEN(sizeof(*pkt
));
828 pkt
= (struct in6_pktinfo
*) CMSG_DATA(cmsg
);
829 // Include the padding to stop valgrind complaining about passing uninitialized data
830 memset(pkt
, 0, CMSG_SPACE(sizeof(*pkt
)));
831 pkt
->ipi6_addr
= source
->sin6
.sin6_addr
;
832 pkt
->ipi6_ifindex
= itfIndex
;
835 #if defined(IP_PKTINFO)
836 struct in_pktinfo
*pkt
;
838 msgh
->msg_control
= cmsgbuf
;
839 #if !defined( __APPLE__ )
840 /* CMSG_SPACE is not a constexpr on macOS */
841 static_assert(CMSG_SPACE(sizeof(*pkt
)) <= sizeof(*cmsgbuf
), "Buffer is too small for in_pktinfo");
842 #else /* __APPLE__ */
843 if (CMSG_SPACE(sizeof(*pkt
)) > sizeof(*cmsgbuf
)) {
844 throw std::runtime_error("Buffer is too small for in_pktinfo");
846 #endif /* __APPLE__ */
847 msgh
->msg_controllen
= CMSG_SPACE(sizeof(*pkt
));
849 cmsg
= CMSG_FIRSTHDR(msgh
);
850 cmsg
->cmsg_level
= IPPROTO_IP
;
851 cmsg
->cmsg_type
= IP_PKTINFO
;
852 cmsg
->cmsg_len
= CMSG_LEN(sizeof(*pkt
));
854 pkt
= (struct in_pktinfo
*) CMSG_DATA(cmsg
);
855 // Include the padding to stop valgrind complaining about passing uninitialized data
856 memset(pkt
, 0, CMSG_SPACE(sizeof(*pkt
)));
857 pkt
->ipi_spec_dst
= source
->sin4
.sin_addr
;
858 pkt
->ipi_ifindex
= itfIndex
;
859 #elif defined(IP_SENDSRCADDR)
862 msgh
->msg_control
= cmsgbuf
;
863 #if !defined( __APPLE__ )
864 static_assert(CMSG_SPACE(sizeof(*in
)) <= sizeof(*cmsgbuf
), "Buffer is too small for in_addr");
865 #else /* __APPLE__ */
866 if (CMSG_SPACE(sizeof(*in
)) > sizeof(*cmsgbuf
)) {
867 throw std::runtime_error("Buffer is too small for in_addr");
869 #endif /* __APPLE__ */
870 msgh
->msg_controllen
= CMSG_SPACE(sizeof(*in
));
872 cmsg
= CMSG_FIRSTHDR(msgh
);
873 cmsg
->cmsg_level
= IPPROTO_IP
;
874 cmsg
->cmsg_type
= IP_SENDSRCADDR
;
875 cmsg
->cmsg_len
= CMSG_LEN(sizeof(*in
));
877 // Include the padding to stop valgrind complaining about passing uninitialized data
878 in
= (struct in_addr
*) CMSG_DATA(cmsg
);
879 memset(in
, 0, CMSG_SPACE(sizeof(*in
)));
880 *in
= source
->sin4
.sin_addr
;
885 unsigned int getFilenumLimit(bool hardOrSoft
)
888 if(getrlimit(RLIMIT_NOFILE
, &rlim
) < 0)
889 unixDie("Requesting number of available file descriptors");
890 return hardOrSoft
? rlim
.rlim_max
: rlim
.rlim_cur
;
893 void setFilenumLimit(unsigned int lim
)
897 if(getrlimit(RLIMIT_NOFILE
, &rlim
) < 0)
898 unixDie("Requesting number of available file descriptors");
900 if(setrlimit(RLIMIT_NOFILE
, &rlim
) < 0)
901 unixDie("Setting number of available file descriptors");
904 #define burtlemix(a,b,c) \
906 a -= b; a -= c; a ^= (c>>13); \
907 b -= c; b -= a; b ^= (a<<8); \
908 c -= a; c -= b; c ^= (b>>13); \
909 a -= b; a -= c; a ^= (c>>12); \
910 b -= c; b -= a; b ^= (a<<16); \
911 c -= a; c -= b; c ^= (b>>5); \
912 a -= b; a -= c; a ^= (c>>3); \
913 b -= c; b -= a; b ^= (a<<10); \
914 c -= a; c -= b; c ^= (b>>15); \
917 uint32_t burtle(const unsigned char* k
, uint32_t length
, uint32_t initval
)
921 /* Set up the internal state */
923 a
= b
= 0x9e3779b9; /* the golden ratio; an arbitrary value */
924 c
= initval
; /* the previous hash value */
926 /*---------------------------------------- handle most of the key */
928 a
+= (k
[0] +((uint32_t)k
[1]<<8) +((uint32_t)k
[2]<<16) +((uint32_t)k
[3]<<24));
929 b
+= (k
[4] +((uint32_t)k
[5]<<8) +((uint32_t)k
[6]<<16) +((uint32_t)k
[7]<<24));
930 c
+= (k
[8] +((uint32_t)k
[9]<<8) +((uint32_t)k
[10]<<16)+((uint32_t)k
[11]<<24));
935 /*------------------------------------- handle the last 11 bytes */
937 switch(len
) { /* all the case statements fall through */
938 case 11: c
+=((uint32_t)k
[10]<<24);
940 case 10: c
+=((uint32_t)k
[9]<<16);
942 case 9 : c
+=((uint32_t)k
[8]<<8);
943 /* the first byte of c is reserved for the length */
945 case 8 : b
+=((uint32_t)k
[7]<<24);
947 case 7 : b
+=((uint32_t)k
[6]<<16);
949 case 6 : b
+=((uint32_t)k
[5]<<8);
953 case 4 : a
+=((uint32_t)k
[3]<<24);
955 case 3 : a
+=((uint32_t)k
[2]<<16);
957 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);
990 case 10: c
+=((uint32_t)dns_tolower(k
[9])<<16);
992 case 9 : c
+=((uint32_t)dns_tolower(k
[8])<<8);
993 /* the first byte of c is reserved for the length */
995 case 8 : b
+=((uint32_t)dns_tolower(k
[7])<<24);
997 case 7 : b
+=((uint32_t)dns_tolower(k
[6])<<16);
999 case 6 : b
+=((uint32_t)dns_tolower(k
[5])<<8);
1001 case 5 : b
+=dns_tolower(k
[4]);
1003 case 4 : a
+=((uint32_t)dns_tolower(k
[3])<<24);
1005 case 3 : a
+=((uint32_t)dns_tolower(k
[2])<<16);
1007 case 2 : a
+=((uint32_t)dns_tolower(k
[1])<<8);
1009 case 1 : a
+=dns_tolower(k
[0]);
1010 /* case 0: nothing left to add */
1013 /*-------------------------------------------- report the result */
1018 bool setSocketTimestamps(int fd
)
1022 return setsockopt(fd
, SOL_SOCKET
, SO_TIMESTAMP
, (char*)&on
, sizeof(on
)) == 0;
1024 return true; // we pretend this happened.
1028 bool setTCPNoDelay(int sock
)
1031 return setsockopt(sock
, /* socket affected */
1032 IPPROTO_TCP
, /* set option at TCP level */
1033 TCP_NODELAY
, /* name of option */
1034 (char *) &flag
, /* the cast is historical cruft */
1035 sizeof(flag
)) == 0; /* length of option value */
1039 bool setNonBlocking(int sock
)
1041 int flags
=fcntl(sock
,F_GETFL
,0);
1042 if(flags
<0 || fcntl(sock
, F_SETFL
,flags
|O_NONBLOCK
) <0)
1047 bool setBlocking(int sock
)
1049 int flags
=fcntl(sock
,F_GETFL
,0);
1050 if(flags
<0 || fcntl(sock
, F_SETFL
,flags
&(~O_NONBLOCK
)) <0)
1055 bool setReuseAddr(int sock
)
1058 if (setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, (char*)&tmp
, static_cast<unsigned>(sizeof tmp
))<0)
1059 throw PDNSException(string("Setsockopt failed: ")+stringerror());
1063 bool isNonBlocking(int sock
)
1065 int flags
=fcntl(sock
,F_GETFL
,0);
1066 return flags
& O_NONBLOCK
;
1069 bool setReceiveSocketErrors(int sock
, int af
)
1073 if (af
== AF_INET
) {
1074 ret
= setsockopt(sock
, IPPROTO_IP
, IP_RECVERR
, &tmp
, sizeof(tmp
));
1076 ret
= setsockopt(sock
, IPPROTO_IPV6
, IPV6_RECVERR
, &tmp
, sizeof(tmp
));
1079 throw PDNSException(string("Setsockopt failed: ") + stringerror());
1086 int closesocket( int socket
)
1088 int ret
=::close(socket
);
1089 if(ret
< 0 && errno
== ECONNRESET
) // see ticket 192, odd BSD behaviour
1092 throw PDNSException("Error closing socket: "+stringerror());
1096 bool setCloseOnExec(int sock
)
1098 int flags
=fcntl(sock
,F_GETFD
,0);
1099 if(flags
<0 || fcntl(sock
, F_SETFD
,flags
|FD_CLOEXEC
) <0)
1104 string
getMACAddress(const ComboAddress
& ca
)
1108 ifstream
ifs("/proc/net/arp");
1112 string match
=ca
.toString()+' ';
1113 while(getline(ifs
, line
)) {
1114 if(boost::starts_with(line
, match
)) {
1115 vector
<string
> parts
;
1116 stringtok(parts
, line
, " \n\t\r");
1117 if(parts
.size() < 4)
1119 unsigned int tmp
[6];
1120 sscanf(parts
[3].c_str(), "%02x:%02x:%02x:%02x:%02x:%02x", tmp
, tmp
+1, tmp
+2, tmp
+3, tmp
+4, tmp
+5);
1121 for(int i
= 0 ; i
< 6 ; ++i
)
1122 ret
.append(1, (char)tmp
[i
]);
1130 uint64_t udpErrorStats(const std::string
& str
)
1133 ifstream
ifs("/proc/net/snmp");
1137 vector
<string
> parts
;
1138 while(getline(ifs
,line
)) {
1139 if(boost::starts_with(line
, "Udp: ") && isdigit(line
[5])) {
1140 stringtok(parts
, line
, " \n\t\r");
1141 if(parts
.size() < 7)
1143 if(str
=="udp-rcvbuf-errors")
1144 return std::stoull(parts
[5]);
1145 else if(str
=="udp-sndbuf-errors")
1146 return std::stoull(parts
[6]);
1147 else if(str
=="udp-noport-errors")
1148 return std::stoull(parts
[2]);
1149 else if(str
=="udp-in-errors")
1150 return std::stoull(parts
[3]);
1159 uint64_t getCPUIOWait(const std::string
& str
)
1162 ifstream
ifs("/proc/stat");
1168 vector
<string
> parts
;
1169 while (getline(ifs
, line
)) {
1170 if (boost::starts_with(line
, "cpu ")) {
1171 stringtok(parts
, line
, " \n\t\r");
1173 if (parts
.size() < 6) {
1177 return std::stoull(parts
[5]);
1184 uint64_t getCPUSteal(const std::string
& str
)
1187 ifstream
ifs("/proc/stat");
1193 vector
<string
> parts
;
1194 while (getline(ifs
, line
)) {
1195 if (boost::starts_with(line
, "cpu ")) {
1196 stringtok(parts
, line
, " \n\t\r");
1198 if (parts
.size() < 9) {
1202 return std::stoull(parts
[8]);
1209 bool getTSIGHashEnum(const DNSName
& algoName
, TSIGHashEnum
& algoEnum
)
1211 if (algoName
== DNSName("hmac-md5.sig-alg.reg.int") || algoName
== DNSName("hmac-md5"))
1212 algoEnum
= TSIG_MD5
;
1213 else if (algoName
== DNSName("hmac-sha1"))
1214 algoEnum
= TSIG_SHA1
;
1215 else if (algoName
== DNSName("hmac-sha224"))
1216 algoEnum
= TSIG_SHA224
;
1217 else if (algoName
== DNSName("hmac-sha256"))
1218 algoEnum
= TSIG_SHA256
;
1219 else if (algoName
== DNSName("hmac-sha384"))
1220 algoEnum
= TSIG_SHA384
;
1221 else if (algoName
== DNSName("hmac-sha512"))
1222 algoEnum
= TSIG_SHA512
;
1223 else if (algoName
== DNSName("gss-tsig"))
1224 algoEnum
= TSIG_GSS
;
1231 DNSName
getTSIGAlgoName(TSIGHashEnum
& algoEnum
)
1234 case TSIG_MD5
: return DNSName("hmac-md5.sig-alg.reg.int.");
1235 case TSIG_SHA1
: return DNSName("hmac-sha1.");
1236 case TSIG_SHA224
: return DNSName("hmac-sha224.");
1237 case TSIG_SHA256
: return DNSName("hmac-sha256.");
1238 case TSIG_SHA384
: return DNSName("hmac-sha384.");
1239 case TSIG_SHA512
: return DNSName("hmac-sha512.");
1240 case TSIG_GSS
: return DNSName("gss-tsig.");
1242 throw PDNSException("getTSIGAlgoName does not understand given algorithm, please fix!");
1245 uint64_t getOpenFileDescriptors(const std::string
&)
1248 DIR* dirhdl
=opendir(("/proc/"+std::to_string(getpid())+"/fd/").c_str());
1252 struct dirent
*entry
;
1254 while((entry
= readdir(dirhdl
))) {
1257 num
= pdns_stou(entry
->d_name
);
1259 continue; // was not a number.
1261 if(std::to_string(num
) == entry
->d_name
)
1272 uint64_t getRealMemoryUsage(const std::string
&)
1275 ifstream
ifs("/proc/self/statm");
1279 uint64_t size
, resident
, shared
, text
, lib
, data
;
1280 ifs
>> size
>> resident
>> shared
>> text
>> lib
>> data
;
1282 return data
* getpagesize();
1285 if (getrusage(RUSAGE_SELF
, &ru
) != 0)
1287 return ru
.ru_maxrss
* 1024;
1292 uint64_t getSpecialMemoryUsage(const std::string
&)
1295 ifstream
ifs("/proc/self/smaps");
1300 string
header("Private_Dirty:");
1301 while(getline(ifs
, line
)) {
1302 if(boost::starts_with(line
, header
)) {
1303 bytes
+= std::stoull(line
.substr(header
.length() + 1))*1024;
1312 uint64_t getCPUTimeUser(const std::string
&)
1315 getrusage(RUSAGE_SELF
, &ru
);
1316 return (ru
.ru_utime
.tv_sec
*1000ULL + ru
.ru_utime
.tv_usec
/1000);
1319 uint64_t getCPUTimeSystem(const std::string
&)
1322 getrusage(RUSAGE_SELF
, &ru
);
1323 return (ru
.ru_stime
.tv_sec
*1000ULL + ru
.ru_stime
.tv_usec
/1000);
1326 double DiffTime(const struct timespec
& first
, const struct timespec
& second
)
1328 int seconds
=second
.tv_sec
- first
.tv_sec
;
1329 int nseconds
=second
.tv_nsec
- first
.tv_nsec
;
1333 nseconds
+=1000000000;
1335 return seconds
+ nseconds
/1000000000.0;
1338 double DiffTime(const struct timeval
& first
, const struct timeval
& second
)
1340 int seconds
=second
.tv_sec
- first
.tv_sec
;
1341 int useconds
=second
.tv_usec
- first
.tv_usec
;
1347 return seconds
+ useconds
/1000000.0;
1350 uid_t
strToUID(const string
&str
)
1353 const char * cstr
= str
.c_str();
1354 struct passwd
* pwd
= getpwnam(cstr
);
1362 catch(std::exception
& e
) {
1363 throw runtime_error((boost::format("Error: Unable to parse user ID %s") % cstr
).str() );
1366 if (val
< std::numeric_limits
<uid_t
>::min() || val
> std::numeric_limits
<uid_t
>::max()) {
1367 throw runtime_error((boost::format("Error: Unable to parse user ID %s") % cstr
).str() );
1370 result
= static_cast<uid_t
>(val
);
1373 result
= pwd
->pw_uid
;
1379 gid_t
strToGID(const string
&str
)
1382 const char * cstr
= str
.c_str();
1383 struct group
* grp
= getgrnam(cstr
);
1391 catch(std::exception
& e
) {
1392 throw runtime_error((boost::format("Error: Unable to parse group ID %s") % cstr
).str() );
1395 if (val
< std::numeric_limits
<gid_t
>::min() || val
> std::numeric_limits
<gid_t
>::max()) {
1396 throw runtime_error((boost::format("Error: Unable to parse group ID %s") % cstr
).str() );
1399 result
= static_cast<gid_t
>(val
);
1402 result
= grp
->gr_gid
;
1408 unsigned int pdns_stou(const std::string
& str
, size_t * idx
, int base
)
1410 if (str
.empty()) return 0; // compatibility
1411 unsigned long result
;
1413 result
= std::stoul(str
, idx
, base
);
1415 catch(std::invalid_argument
& e
) {
1416 throw std::invalid_argument(string(e
.what()) + "; (invalid argument during std::stoul); data was \""+str
+"\"");
1418 catch(std::out_of_range
& e
) {
1419 throw std::out_of_range(string(e
.what()) + "; (out of range during std::stoul); data was \""+str
+"\"");
1421 if (result
> std::numeric_limits
<unsigned int>::max()) {
1422 throw std::out_of_range("stoul returned result out of unsigned int range; data was \""+str
+"\"");
1424 return static_cast<unsigned int>(result
);
1427 bool isSettingThreadCPUAffinitySupported()
1429 #ifdef HAVE_PTHREAD_SETAFFINITY_NP
1436 int mapThreadToCPUList(pthread_t tid
, const std::set
<int>& cpus
)
1438 #ifdef HAVE_PTHREAD_SETAFFINITY_NP
1441 cpuset
= cpuset_create();
1442 for (const auto cpuID
: cpus
) {
1443 cpuset_set(cpuID
, cpuset
);
1446 return pthread_setaffinity_np(tid
,
1447 cpuset_size(cpuset
),
1451 # define cpu_set_t cpuset_t
1455 for (const auto cpuID
: cpus
) {
1456 CPU_SET(cpuID
, &cpuset
);
1459 return pthread_setaffinity_np(tid
,
1465 #endif /* HAVE_PTHREAD_SETAFFINITY_NP */
1468 std::vector
<ComboAddress
> getResolvers(const std::string
& resolvConfPath
)
1470 std::vector
<ComboAddress
> results
;
1472 ifstream
ifs(resolvConfPath
);
1478 while(std::getline(ifs
, line
)) {
1479 boost::trim_right_if(line
, is_any_of(" \r\n\x1a"));
1480 boost::trim_left(line
); // leading spaces, let's be nice
1482 string::size_type tpos
= line
.find_first_of(";#");
1483 if (tpos
!= string::npos
) {
1487 if (boost::starts_with(line
, "nameserver ") || boost::starts_with(line
, "nameserver\t")) {
1488 vector
<string
> parts
;
1489 stringtok(parts
, line
, " \t,"); // be REALLY nice
1490 for(vector
<string
>::const_iterator iter
= parts
.begin() + 1; iter
!= parts
.end(); ++iter
) {
1492 results
.emplace_back(*iter
, 53);
1504 size_t getPipeBufferSize(int fd
)
1507 int res
= fcntl(fd
, F_GETPIPE_SZ
);
1515 #endif /* F_GETPIPE_SZ */
1518 bool setPipeBufferSize(int fd
, size_t size
)
1521 if (size
> std::numeric_limits
<int>::max()) {
1525 int newSize
= static_cast<int>(size
);
1526 int res
= fcntl(fd
, F_SETPIPE_SZ
, newSize
);
1534 #endif /* F_SETPIPE_SZ */
1537 DNSName
reverseNameFromIP(const ComboAddress
& ip
)
1540 std::string
result("in-addr.arpa.");
1541 auto ptr
= reinterpret_cast<const uint8_t*>(&ip
.sin4
.sin_addr
.s_addr
);
1542 for (size_t idx
= 0; idx
< sizeof(ip
.sin4
.sin_addr
.s_addr
); idx
++) {
1543 result
= std::to_string(ptr
[idx
]) + "." + result
;
1545 return DNSName(result
);
1547 else if (ip
.isIPv6()) {
1548 std::string
result("ip6.arpa.");
1549 auto ptr
= reinterpret_cast<const uint8_t*>(&ip
.sin6
.sin6_addr
.s6_addr
[0]);
1550 for (size_t idx
= 0; idx
< sizeof(ip
.sin6
.sin6_addr
.s6_addr
); idx
++) {
1551 std::stringstream stream
;
1552 stream
<< std::hex
<< (ptr
[idx
] & 0x0F);
1554 stream
<< std::hex
<< (((ptr
[idx
]) >> 4) & 0x0F);
1556 result
= stream
.str() + result
;
1558 return DNSName(result
);
1561 throw std::runtime_error("Calling reverseNameFromIP() for an address which is neither an IPv4 nor an IPv6");