]> git.ipfire.org Git - thirdparty/pdns.git/blob - pdns/misc.cc
Merge pull request #4759 from rgacogne/dnsdist-110-beta2-changelog
[thirdparty/pdns.git] / pdns / misc.cc
1 /*
2 * This file is part of PowerDNS or dnsdist.
3 * Copyright -- PowerDNS.COM B.V. and its contributors
4 *
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.
8 *
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.
12 *
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.
17 *
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.
21 */
22 #ifdef HAVE_CONFIG_H
23 #include "config.h"
24 #endif
25 #include <sys/param.h>
26 #include <sys/socket.h>
27 #include <fcntl.h>
28 #include <netdb.h>
29 #include <sys/time.h>
30 #include <time.h>
31 #include <sys/resource.h>
32 #include <netinet/in.h>
33 #include <sys/un.h>
34 #include <unistd.h>
35 #include <fstream>
36 #include "misc.hh"
37 #include <vector>
38 #include <sstream>
39 #include <errno.h>
40 #include <cstring>
41 #include <iostream>
42 #include <sys/types.h>
43 #include <dirent.h>
44 #include <algorithm>
45 #include <boost/optional.hpp>
46 #include <poll.h>
47 #include <iomanip>
48 #include <netinet/tcp.h>
49 #include <string.h>
50 #include <stdlib.h>
51 #include <stdio.h>
52 #include "pdnsexception.hh"
53 #include <sys/types.h>
54 #include <boost/algorithm/string.hpp>
55 #include "iputils.hh"
56 #include "dnsparser.hh"
57 #include <sys/types.h>
58 #include <pwd.h>
59 #include <grp.h>
60
61
62 bool g_singleThreaded;
63
64 size_t writen2(int fd, const void *buf, size_t count)
65 {
66 const char *ptr = (char*)buf;
67 const char *eptr = ptr + count;
68
69 ssize_t res;
70 while(ptr != eptr) {
71 res = ::write(fd, ptr, eptr - ptr);
72 if(res < 0) {
73 if (errno == EAGAIN)
74 throw std::runtime_error("used writen2 on non-blocking socket, got EAGAIN");
75 else
76 unixDie("failed in writen2");
77 }
78 else if (res == 0)
79 throw std::runtime_error("could not write all bytes, got eof in writen2");
80
81 ptr += (size_t) res;
82 }
83
84 return count;
85 }
86
87 size_t readn2(int fd, void* buffer, size_t len)
88 {
89 size_t pos=0;
90 ssize_t res;
91 for(;;) {
92 res = read(fd, (char*)buffer + pos, len - pos);
93 if(res == 0)
94 throw runtime_error("EOF while reading message");
95 if(res < 0) {
96 if (errno == EAGAIN)
97 throw std::runtime_error("used readn2 on non-blocking socket, got EAGAIN");
98 else
99 unixDie("failed in readn2");
100 }
101
102 pos+=(size_t)res;
103 if(pos == len)
104 break;
105 }
106 return len;
107 }
108
109 size_t readn2WithTimeout(int fd, void* buffer, size_t len, int timeout)
110 {
111 size_t pos = 0;
112 do {
113 ssize_t got = read(fd, (char *)buffer + pos, len - pos);
114 if (got > 0) {
115 pos += (size_t) got;
116 }
117 else if (got == 0) {
118 throw runtime_error("EOF while reading message");
119 }
120 else {
121 if (errno == EAGAIN) {
122 int res = waitForData(fd, timeout);
123 if (res > 0) {
124 /* there is data available */
125 }
126 else if (res == 0) {
127 throw runtime_error("Timeout while waiting for data to read");
128 } else {
129 throw runtime_error("Error while waiting for data to read");
130 }
131 }
132 else {
133 unixDie("failed in readn2WithTimeout");
134 }
135 }
136 }
137 while (pos < len);
138
139 return len;
140 }
141
142 size_t writen2WithTimeout(int fd, const void * buffer, size_t len, int timeout)
143 {
144 size_t pos = 0;
145 do {
146 ssize_t written = write(fd, (char *)buffer + pos, len - pos);
147
148 if (written > 0) {
149 pos += (size_t) written;
150 }
151 else if (written == 0)
152 throw runtime_error("EOF while writing message");
153 else {
154 if (errno == EAGAIN) {
155 int res = waitForRWData(fd, false, timeout, 0);
156 if (res > 0) {
157 /* there is room available */
158 }
159 else if (res == 0) {
160 throw runtime_error("Timeout while waiting to write data");
161 } else {
162 throw runtime_error("Error while waiting for room to write data");
163 }
164 }
165 else {
166 unixDie("failed in write2WithTimeout");
167 }
168 }
169 }
170 while (pos < len);
171
172 return len;
173 }
174
175 string nowTime()
176 {
177 time_t now = time(nullptr);
178 struct tm* tm = localtime(&now);
179 char buffer[30];
180 // YYYY-mm-dd HH:MM:SS TZOFF
181 strftime(buffer, sizeof(buffer), "%F %T %z", tm);
182 buffer[sizeof(buffer)-1] = '\0';
183 return buffer;
184 }
185
186 uint16_t getShort(const unsigned char *p)
187 {
188 return p[0] * 256 + p[1];
189 }
190
191
192 uint16_t getShort(const char *p)
193 {
194 return getShort((const unsigned char *)p);
195 }
196
197 uint32_t getLong(const unsigned char* p)
198 {
199 return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3];
200 }
201
202 uint32_t getLong(const char* p)
203 {
204 return getLong((unsigned char *)p);
205 }
206
207 static bool ciEqual(const string& a, const string& b)
208 {
209 if(a.size()!=b.size())
210 return false;
211
212 string::size_type pos=0, epos=a.size();
213 for(;pos < epos; ++pos)
214 if(dns_tolower(a[pos])!=dns_tolower(b[pos]))
215 return false;
216 return true;
217 }
218
219 /** does domain end on suffix? Is smart about "wwwds9a.nl" "ds9a.nl" not matching */
220 static bool endsOn(const string &domain, const string &suffix)
221 {
222 if( suffix.empty() || ciEqual(domain, suffix) )
223 return true;
224
225 if(domain.size()<=suffix.size())
226 return false;
227
228 string::size_type dpos=domain.size()-suffix.size()-1, spos=0;
229
230 if(domain[dpos++]!='.')
231 return false;
232
233 for(; dpos < domain.size(); ++dpos, ++spos)
234 if(dns_tolower(domain[dpos]) != dns_tolower(suffix[spos]))
235 return false;
236
237 return true;
238 }
239
240 /** strips a domain suffix from a domain, returns true if it stripped */
241 bool stripDomainSuffix(string *qname, const string &domain)
242 {
243 if(!endsOn(*qname, domain))
244 return false;
245
246 if(toLower(*qname)==toLower(domain))
247 *qname="@";
248 else {
249 if((*qname)[qname->size()-domain.size()-1]!='.')
250 return false;
251
252 qname->resize(qname->size()-domain.size()-1);
253 }
254 return true;
255 }
256
257 static void parseService4(const string &descr, ServiceTuple &st)
258 {
259 vector<string>parts;
260 stringtok(parts,descr,":");
261 if(parts.empty())
262 throw PDNSException("Unable to parse '"+descr+"' as a service");
263 st.host=parts[0];
264 if(parts.size()>1)
265 st.port=pdns_stou(parts[1]);
266 }
267
268 static void parseService6(const string &descr, ServiceTuple &st)
269 {
270 string::size_type pos=descr.find(']');
271 if(pos == string::npos)
272 throw PDNSException("Unable to parse '"+descr+"' as an IPv6 service");
273
274 st.host=descr.substr(1, pos-1);
275 if(pos + 2 < descr.length())
276 st.port=pdns_stou(descr.substr(pos+2));
277 }
278
279
280 void parseService(const string &descr, ServiceTuple &st)
281 {
282 if(descr.empty())
283 throw PDNSException("Unable to parse '"+descr+"' as a service");
284
285 vector<string> parts;
286 stringtok(parts, descr, ":");
287
288 if(descr[0]=='[') {
289 parseService6(descr, st);
290 }
291 else if(descr[0]==':' || parts.size() > 2 || descr.find("::") != string::npos) {
292 st.host=descr;
293 }
294 else {
295 parseService4(descr, st);
296 }
297 }
298
299 // returns -1 in case if error, 0 if no data is available, 1 if there is. In the first two cases, errno is set
300 int waitForData(int fd, int seconds, int useconds)
301 {
302 return waitForRWData(fd, true, seconds, useconds);
303 }
304
305 int waitForRWData(int fd, bool waitForRead, int seconds, int useconds, bool* error, bool* disconnected)
306 {
307 int ret;
308
309 struct pollfd pfd;
310 memset(&pfd, 0, sizeof(pfd));
311 pfd.fd = fd;
312
313 if(waitForRead)
314 pfd.events=POLLIN;
315 else
316 pfd.events=POLLOUT;
317
318 ret = poll(&pfd, 1, seconds * 1000 + useconds/1000);
319 if ( ret == -1 ) {
320 errno = ETIMEDOUT; // ???
321 }
322 else if (ret > 0) {
323 if (error && (pfd.revents & POLLERR)) {
324 *error = true;
325 }
326 if (disconnected && (pfd.revents & POLLHUP)) {
327 *disconnected = true;
328 }
329 }
330
331 return ret;
332 }
333
334 // returns -1 in case of error, 0 if no data is available, 1 if there is. In the first two cases, errno is set
335 int waitFor2Data(int fd1, int fd2, int seconds, int useconds, int*fd)
336 {
337 int ret;
338
339 struct pollfd pfds[2];
340 memset(&pfds[0], 0, 2*sizeof(struct pollfd));
341 pfds[0].fd = fd1;
342 pfds[1].fd = fd2;
343
344 pfds[0].events= pfds[1].events = POLLIN;
345
346 int nsocks = 1 + (fd2 >= 0); // fd2 can optionally be -1
347
348 if(seconds >= 0)
349 ret = poll(pfds, nsocks, seconds * 1000 + useconds/1000);
350 else
351 ret = poll(pfds, nsocks, -1);
352 if(!ret || ret < 0)
353 return ret;
354
355 if((pfds[0].revents & POLLIN) && !(pfds[1].revents & POLLIN))
356 *fd = pfds[0].fd;
357 else if((pfds[1].revents & POLLIN) && !(pfds[0].revents & POLLIN))
358 *fd = pfds[1].fd;
359 else if(ret == 2) {
360 *fd = pfds[random()%2].fd;
361 }
362 else
363 *fd = -1; // should never happen
364
365 return 1;
366 }
367
368
369 string humanDuration(time_t passed)
370 {
371 ostringstream ret;
372 if(passed<60)
373 ret<<passed<<" seconds";
374 else if(passed<3600)
375 ret<<std::setprecision(2)<<passed/60.0<<" minutes";
376 else if(passed<86400)
377 ret<<std::setprecision(3)<<passed/3600.0<<" hours";
378 else if(passed<(86400*30.41))
379 ret<<std::setprecision(3)<<passed/86400.0<<" days";
380 else
381 ret<<std::setprecision(3)<<passed/(86400*30.41)<<" months";
382
383 return ret.str();
384 }
385
386 DTime::DTime()
387 {
388 // set(); // saves lots of gettimeofday calls
389 d_set.tv_sec=d_set.tv_usec=0;
390 }
391
392 DTime::DTime(const DTime &dt)
393 {
394 d_set=dt.d_set;
395 }
396
397 time_t DTime::time()
398 {
399 return d_set.tv_sec;
400 }
401
402 const string unquotify(const string &item)
403 {
404 if(item.size()<2)
405 return item;
406
407 string::size_type bpos=0, epos=item.size();
408
409 if(item[0]=='"')
410 bpos=1;
411
412 if(item[epos-1]=='"')
413 epos-=1;
414
415 return item.substr(bpos,epos-bpos);
416 }
417
418 void stripLine(string &line)
419 {
420 string::size_type pos=line.find_first_of("\r\n");
421 if(pos!=string::npos) {
422 line.resize(pos);
423 }
424 }
425
426 string urlEncode(const string &text)
427 {
428 string ret;
429 for(string::const_iterator i=text.begin();i!=text.end();++i)
430 if(*i==' ')ret.append("%20");
431 else ret.append(1,*i);
432 return ret;
433 }
434
435 string getHostname()
436 {
437 #ifndef MAXHOSTNAMELEN
438 #define MAXHOSTNAMELEN 255
439 #endif
440
441 char tmp[MAXHOSTNAMELEN];
442 if(gethostname(tmp, MAXHOSTNAMELEN))
443 return "UNKNOWN";
444
445 return tmp;
446 }
447
448 string itoa(int i)
449 {
450 ostringstream o;
451 o<<i;
452 return o.str();
453 }
454
455 string uitoa(unsigned int i) // MSVC 6 doesn't grok overloading (un)signed
456 {
457 ostringstream o;
458 o<<i;
459 return o.str();
460 }
461
462 string bitFlip(const string &str)
463 {
464 string::size_type pos=0, epos=str.size();
465 string ret;
466 ret.reserve(epos);
467 for(;pos < epos; ++pos)
468 ret.append(1, ~str[pos]);
469 return ret;
470 }
471
472 string stringerror()
473 {
474 return strerror(errno);
475 }
476
477 string netstringerror()
478 {
479 return stringerror();
480 }
481
482 void cleanSlashes(string &str)
483 {
484 string::const_iterator i;
485 string out;
486 for(i=str.begin();i!=str.end();++i) {
487 if(*i=='/' && i!=str.begin() && *(i-1)=='/')
488 continue;
489 out.append(1,*i);
490 }
491 str=out;
492 }
493
494
495 bool IpToU32(const string &str, uint32_t *ip)
496 {
497 if(str.empty()) {
498 *ip=0;
499 return true;
500 }
501
502 struct in_addr inp;
503 if(inet_aton(str.c_str(), &inp)) {
504 *ip=inp.s_addr;
505 return true;
506 }
507 return false;
508 }
509
510 string U32ToIP(uint32_t val)
511 {
512 char tmp[17];
513 snprintf(tmp, sizeof(tmp)-1, "%u.%u.%u.%u",
514 (val >> 24)&0xff,
515 (val >> 16)&0xff,
516 (val >> 8)&0xff,
517 (val )&0xff);
518 return tmp;
519 }
520
521
522 string makeHexDump(const string& str)
523 {
524 char tmp[5];
525 string ret;
526 ret.reserve((int)(str.size()*2.2));
527
528 for(string::size_type n=0;n<str.size();++n) {
529 sprintf(tmp,"%02x ", (unsigned char)str[n]);
530 ret+=tmp;
531 }
532 return ret;
533 }
534
535 // shuffle, maintaining some semblance of order
536 void shuffle(vector<DNSZoneRecord>& rrs)
537 {
538 vector<DNSZoneRecord>::iterator first, second;
539 for(first=rrs.begin();first!=rrs.end();++first)
540 if(first->dr.d_place==DNSResourceRecord::ANSWER && first->dr.d_type != QType::CNAME) // CNAME must come first
541 break;
542 for(second=first;second!=rrs.end();++second)
543 if(second->dr.d_place!=DNSResourceRecord::ANSWER)
544 break;
545
546 if(second-first > 1)
547 random_shuffle(first,second);
548
549 // now shuffle the additional records
550 for(first=second;first!=rrs.end();++first)
551 if(first->dr.d_place==DNSResourceRecord::ADDITIONAL && first->dr.d_type != QType::CNAME) // CNAME must come first
552 break;
553 for(second=first;second!=rrs.end();++second)
554 if(second->dr.d_place!=DNSResourceRecord::ADDITIONAL)
555 break;
556
557 if(second-first>1)
558 random_shuffle(first,second);
559
560 // we don't shuffle the rest
561 }
562
563
564 // shuffle, maintaining some semblance of order
565 void shuffle(vector<DNSRecord>& rrs)
566 {
567 vector<DNSRecord>::iterator first, second;
568 for(first=rrs.begin();first!=rrs.end();++first)
569 if(first->d_place==DNSResourceRecord::ANSWER && first->d_type != QType::CNAME) // CNAME must come first
570 break;
571 for(second=first;second!=rrs.end();++second)
572 if(second->d_place!=DNSResourceRecord::ANSWER || second->d_type == QType::RRSIG) // leave RRSIGs at the end
573 break;
574
575 if(second-first>1)
576 random_shuffle(first,second);
577
578 // now shuffle the additional records
579 for(first=second;first!=rrs.end();++first)
580 if(first->d_place==DNSResourceRecord::ADDITIONAL && first->d_type != QType::CNAME) // CNAME must come first
581 break;
582 for(second=first; second!=rrs.end(); ++second)
583 if(second->d_place!=DNSResourceRecord::ADDITIONAL)
584 break;
585
586 if(second-first>1)
587 random_shuffle(first,second);
588
589 // we don't shuffle the rest
590 }
591
592 static uint16_t mapTypesToOrder(uint16_t type)
593 {
594 if(type == QType::CNAME)
595 return 0;
596 if(type == QType::RRSIG)
597 return 65535;
598 else
599 return 1;
600 }
601
602 // make sure rrs is sorted in d_place order to avoid surprises later
603 // then shuffle the parts that desire shuffling
604 void orderAndShuffle(vector<DNSRecord>& rrs)
605 {
606 std::stable_sort(rrs.begin(), rrs.end(), [](const DNSRecord&a, const DNSRecord& b) {
607 return std::make_tuple(a.d_place, mapTypesToOrder(a.d_type)) < std::make_tuple(b.d_place, mapTypesToOrder(b.d_type));
608 });
609 shuffle(rrs);
610 }
611
612 void normalizeTV(struct timeval& tv)
613 {
614 if(tv.tv_usec > 1000000) {
615 ++tv.tv_sec;
616 tv.tv_usec-=1000000;
617 }
618 else if(tv.tv_usec < 0) {
619 --tv.tv_sec;
620 tv.tv_usec+=1000000;
621 }
622 }
623
624 const struct timeval operator+(const struct timeval& lhs, const struct timeval& rhs)
625 {
626 struct timeval ret;
627 ret.tv_sec=lhs.tv_sec + rhs.tv_sec;
628 ret.tv_usec=lhs.tv_usec + rhs.tv_usec;
629 normalizeTV(ret);
630 return ret;
631 }
632
633 const struct timeval operator-(const struct timeval& lhs, const struct timeval& rhs)
634 {
635 struct timeval ret;
636 ret.tv_sec=lhs.tv_sec - rhs.tv_sec;
637 ret.tv_usec=lhs.tv_usec - rhs.tv_usec;
638 normalizeTV(ret);
639 return ret;
640 }
641
642 pair<string, string> splitField(const string& inp, char sepa)
643 {
644 pair<string, string> ret;
645 string::size_type cpos=inp.find(sepa);
646 if(cpos==string::npos)
647 ret.first=inp;
648 else {
649 ret.first=inp.substr(0, cpos);
650 ret.second=inp.substr(cpos+1);
651 }
652 return ret;
653 }
654
655 int logFacilityToLOG(unsigned int facility)
656 {
657 switch(facility) {
658 case 0:
659 return LOG_LOCAL0;
660 case 1:
661 return(LOG_LOCAL1);
662 case 2:
663 return(LOG_LOCAL2);
664 case 3:
665 return(LOG_LOCAL3);
666 case 4:
667 return(LOG_LOCAL4);
668 case 5:
669 return(LOG_LOCAL5);
670 case 6:
671 return(LOG_LOCAL6);
672 case 7:
673 return(LOG_LOCAL7);
674 default:
675 return -1;
676 }
677 }
678
679 string stripDot(const string& dom)
680 {
681 if(dom.empty())
682 return dom;
683
684 if(dom[dom.size()-1]!='.')
685 return dom;
686
687 return dom.substr(0,dom.size()-1);
688 }
689
690
691
692 int makeIPv6sockaddr(const std::string& addr, struct sockaddr_in6* ret)
693 {
694 if(addr.empty())
695 return -1;
696 string ourAddr(addr);
697 int port = -1;
698 if(addr[0]=='[') { // [::]:53 style address
699 string::size_type pos = addr.find(']');
700 if(pos == string::npos || pos + 2 > addr.size() || addr[pos+1]!=':')
701 return -1;
702 ourAddr.assign(addr.c_str() + 1, pos-1);
703 try {
704 port = pdns_stou(addr.substr(pos+2));
705 }
706 catch(std::out_of_range) {
707 return -1;
708 }
709 }
710 ret->sin6_scope_id=0;
711 ret->sin6_family=AF_INET6;
712
713 if(inet_pton(AF_INET6, ourAddr.c_str(), (void*)&ret->sin6_addr) != 1) {
714 struct addrinfo* res;
715 struct addrinfo hints;
716 memset(&hints, 0, sizeof(hints));
717
718 hints.ai_family = AF_INET6;
719 hints.ai_flags = AI_NUMERICHOST;
720
721 int error;
722 if((error=getaddrinfo(ourAddr.c_str(), 0, &hints, &res))) { // this is correct
723 return -1;
724 }
725
726 memcpy(ret, res->ai_addr, res->ai_addrlen);
727 freeaddrinfo(res);
728 }
729
730 if(port > 65535)
731 // negative ports are found with the pdns_stou above
732 return -1;
733
734 if(port >= 0)
735 ret->sin6_port = htons(port);
736
737 return 0;
738 }
739
740 int makeIPv4sockaddr(const std::string& str, struct sockaddr_in* ret)
741 {
742 if(str.empty()) {
743 return -1;
744 }
745 struct in_addr inp;
746
747 string::size_type pos = str.find(':');
748 if(pos == string::npos) { // no port specified, not touching the port
749 if(inet_aton(str.c_str(), &inp)) {
750 ret->sin_addr.s_addr=inp.s_addr;
751 return 0;
752 }
753 return -1;
754 }
755 if(!*(str.c_str() + pos + 1)) // trailing :
756 return -1;
757
758 char *eptr = (char*)str.c_str() + str.size();
759 int port = strtol(str.c_str() + pos + 1, &eptr, 10);
760 if (port < 0 || port > 65535)
761 return -1;
762
763 if(*eptr)
764 return -1;
765
766 ret->sin_port = htons(port);
767 if(inet_aton(str.substr(0, pos).c_str(), &inp)) {
768 ret->sin_addr.s_addr=inp.s_addr;
769 return 0;
770 }
771 return -1;
772 }
773
774 int makeUNsockaddr(const std::string& path, struct sockaddr_un* ret)
775 {
776 if (path.empty())
777 return -1;
778
779 memset(ret, 0, sizeof(struct sockaddr_un));
780 ret->sun_family = AF_UNIX;
781 if (path.length() >= sizeof(ret->sun_path))
782 return -1;
783
784 path.copy(ret->sun_path, sizeof(ret->sun_path), 0);
785 return 0;
786 }
787
788 //! read a line of text from a FILE* to a std::string, returns false on 'no data'
789 bool stringfgets(FILE* fp, std::string& line)
790 {
791 char buffer[1024];
792 line.clear();
793
794 do {
795 if(!fgets(buffer, sizeof(buffer), fp))
796 return !line.empty();
797
798 line.append(buffer);
799 } while(!strchr(buffer, '\n'));
800 return true;
801 }
802
803 bool readFileIfThere(const char* fname, std::string* line)
804 {
805 line->clear();
806 FILE* fp = fopen(fname, "r");
807 if(!fp)
808 return false;
809 stringfgets(fp, *line);
810 fclose(fp);
811 return true;
812 }
813
814 Regex::Regex(const string &expr)
815 {
816 if(regcomp(&d_preg, expr.c_str(), REG_ICASE|REG_NOSUB|REG_EXTENDED))
817 throw PDNSException("Regular expression did not compile");
818 }
819
820 // if you end up here because valgrind told you were are doing something wrong
821 // with msgh->msg_controllen, please refer to https://github.com/PowerDNS/pdns/pull/3962
822 // first.
823 void addCMsgSrcAddr(struct msghdr* msgh, void* cmsgbuf, const ComboAddress* source, int itfIndex)
824 {
825 struct cmsghdr *cmsg = NULL;
826
827 if(source->sin4.sin_family == AF_INET6) {
828 struct in6_pktinfo *pkt;
829
830 msgh->msg_control = cmsgbuf;
831 msgh->msg_controllen = CMSG_SPACE(sizeof(*pkt));
832
833 cmsg = CMSG_FIRSTHDR(msgh);
834 cmsg->cmsg_level = IPPROTO_IPV6;
835 cmsg->cmsg_type = IPV6_PKTINFO;
836 cmsg->cmsg_len = CMSG_LEN(sizeof(*pkt));
837
838 pkt = (struct in6_pktinfo *) CMSG_DATA(cmsg);
839 memset(pkt, 0, sizeof(*pkt));
840 pkt->ipi6_addr = source->sin6.sin6_addr;
841 pkt->ipi6_ifindex = itfIndex;
842 }
843 else {
844 #ifdef IP_PKTINFO
845 struct in_pktinfo *pkt;
846
847 msgh->msg_control = cmsgbuf;
848 msgh->msg_controllen = CMSG_SPACE(sizeof(*pkt));
849
850 cmsg = CMSG_FIRSTHDR(msgh);
851 cmsg->cmsg_level = IPPROTO_IP;
852 cmsg->cmsg_type = IP_PKTINFO;
853 cmsg->cmsg_len = CMSG_LEN(sizeof(*pkt));
854
855 pkt = (struct in_pktinfo *) CMSG_DATA(cmsg);
856 memset(pkt, 0, sizeof(*pkt));
857 pkt->ipi_spec_dst = source->sin4.sin_addr;
858 pkt->ipi_ifindex = itfIndex;
859 #endif
860 #ifdef IP_SENDSRCADDR
861 struct in_addr *in;
862
863 msgh->msg_control = cmsgbuf;
864 msgh->msg_controllen = CMSG_SPACE(sizeof(*in));
865
866 cmsg = CMSG_FIRSTHDR(msgh);
867 cmsg->cmsg_level = IPPROTO_IP;
868 cmsg->cmsg_type = IP_SENDSRCADDR;
869 cmsg->cmsg_len = CMSG_LEN(sizeof(*in));
870
871 in = (struct in_addr *) CMSG_DATA(cmsg);
872 *in = source->sin4.sin_addr;
873 #endif
874 }
875 }
876
877 unsigned int getFilenumLimit(bool hardOrSoft)
878 {
879 struct rlimit rlim;
880 if(getrlimit(RLIMIT_NOFILE, &rlim) < 0)
881 unixDie("Requesting number of available file descriptors");
882 return hardOrSoft ? rlim.rlim_max : rlim.rlim_cur;
883 }
884
885 void setFilenumLimit(unsigned int lim)
886 {
887 struct rlimit rlim;
888
889 if(getrlimit(RLIMIT_NOFILE, &rlim) < 0)
890 unixDie("Requesting number of available file descriptors");
891 rlim.rlim_cur=lim;
892 if(setrlimit(RLIMIT_NOFILE, &rlim) < 0)
893 unixDie("Setting number of available file descriptors");
894 }
895
896 #define burtlemix(a,b,c) \
897 { \
898 a -= b; a -= c; a ^= (c>>13); \
899 b -= c; b -= a; b ^= (a<<8); \
900 c -= a; c -= b; c ^= (b>>13); \
901 a -= b; a -= c; a ^= (c>>12); \
902 b -= c; b -= a; b ^= (a<<16); \
903 c -= a; c -= b; c ^= (b>>5); \
904 a -= b; a -= c; a ^= (c>>3); \
905 b -= c; b -= a; b ^= (a<<10); \
906 c -= a; c -= b; c ^= (b>>15); \
907 }
908
909 uint32_t burtle(const unsigned char* k, uint32_t length, uint32_t initval)
910 {
911 uint32_t a,b,c,len;
912
913 /* Set up the internal state */
914 len = length;
915 a = b = 0x9e3779b9; /* the golden ratio; an arbitrary value */
916 c = initval; /* the previous hash value */
917
918 /*---------------------------------------- handle most of the key */
919 while (len >= 12) {
920 a += (k[0] +((uint32_t)k[1]<<8) +((uint32_t)k[2]<<16) +((uint32_t)k[3]<<24));
921 b += (k[4] +((uint32_t)k[5]<<8) +((uint32_t)k[6]<<16) +((uint32_t)k[7]<<24));
922 c += (k[8] +((uint32_t)k[9]<<8) +((uint32_t)k[10]<<16)+((uint32_t)k[11]<<24));
923 burtlemix(a,b,c);
924 k += 12; len -= 12;
925 }
926
927 /*------------------------------------- handle the last 11 bytes */
928 c += length;
929 switch(len) { /* all the case statements fall through */
930 case 11: c+=((uint32_t)k[10]<<24);
931 case 10: c+=((uint32_t)k[9]<<16);
932 case 9 : c+=((uint32_t)k[8]<<8);
933 /* the first byte of c is reserved for the length */
934 case 8 : b+=((uint32_t)k[7]<<24);
935 case 7 : b+=((uint32_t)k[6]<<16);
936 case 6 : b+=((uint32_t)k[5]<<8);
937 case 5 : b+=k[4];
938 case 4 : a+=((uint32_t)k[3]<<24);
939 case 3 : a+=((uint32_t)k[2]<<16);
940 case 2 : a+=((uint32_t)k[1]<<8);
941 case 1 : a+=k[0];
942 /* case 0: nothing left to add */
943 }
944 burtlemix(a,b,c);
945 /*-------------------------------------------- report the result */
946 return c;
947 }
948
949 uint32_t burtleCI(const unsigned char* k, uint32_t length, uint32_t initval)
950 {
951 uint32_t a,b,c,len;
952
953 /* Set up the internal state */
954 len = length;
955 a = b = 0x9e3779b9; /* the golden ratio; an arbitrary value */
956 c = initval; /* the previous hash value */
957
958 /*---------------------------------------- handle most of the key */
959 while (len >= 12) {
960 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));
961 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));
962 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));
963 burtlemix(a,b,c);
964 k += 12; len -= 12;
965 }
966
967 /*------------------------------------- handle the last 11 bytes */
968 c += length;
969 switch(len) { /* all the case statements fall through */
970 case 11: c+=((uint32_t)dns_tolower(k[10])<<24);
971 case 10: c+=((uint32_t)dns_tolower(k[9])<<16);
972 case 9 : c+=((uint32_t)dns_tolower(k[8])<<8);
973 /* the first byte of c is reserved for the length */
974 case 8 : b+=((uint32_t)dns_tolower(k[7])<<24);
975 case 7 : b+=((uint32_t)dns_tolower(k[6])<<16);
976 case 6 : b+=((uint32_t)dns_tolower(k[5])<<8);
977 case 5 : b+=dns_tolower(k[4]);
978 case 4 : a+=((uint32_t)dns_tolower(k[3])<<24);
979 case 3 : a+=((uint32_t)dns_tolower(k[2])<<16);
980 case 2 : a+=((uint32_t)dns_tolower(k[1])<<8);
981 case 1 : a+=dns_tolower(k[0]);
982 /* case 0: nothing left to add */
983 }
984 burtlemix(a,b,c);
985 /*-------------------------------------------- report the result */
986 return c;
987 }
988
989
990 bool setSocketTimestamps(int fd)
991 {
992 #ifdef SO_TIMESTAMP
993 int on=1;
994 return setsockopt(fd, SOL_SOCKET, SO_TIMESTAMP, (char*)&on, sizeof(on)) == 0;
995 #endif
996 return true; // we pretend this happened.
997 }
998
999 bool setTCPNoDelay(int sock)
1000 {
1001 int flag = 1;
1002 return setsockopt(sock, /* socket affected */
1003 IPPROTO_TCP, /* set option at TCP level */
1004 TCP_NODELAY, /* name of option */
1005 (char *) &flag, /* the cast is historical cruft */
1006 sizeof(flag)) == 0; /* length of option value */
1007 }
1008
1009
1010 bool setNonBlocking(int sock)
1011 {
1012 int flags=fcntl(sock,F_GETFL,0);
1013 if(flags<0 || fcntl(sock, F_SETFL,flags|O_NONBLOCK) <0)
1014 return false;
1015 return true;
1016 }
1017
1018 bool setBlocking(int sock)
1019 {
1020 int flags=fcntl(sock,F_GETFL,0);
1021 if(flags<0 || fcntl(sock, F_SETFL,flags&(~O_NONBLOCK)) <0)
1022 return false;
1023 return true;
1024 }
1025
1026 bool isNonBlocking(int sock)
1027 {
1028 int flags=fcntl(sock,F_GETFL,0);
1029 return flags & O_NONBLOCK;
1030 }
1031
1032 // Closes a socket.
1033 int closesocket( int socket )
1034 {
1035 int ret=::close(socket);
1036 if(ret < 0 && errno == ECONNRESET) // see ticket 192, odd BSD behaviour
1037 return 0;
1038 if(ret < 0)
1039 throw PDNSException("Error closing socket: "+stringerror());
1040 return ret;
1041 }
1042
1043 bool setCloseOnExec(int sock)
1044 {
1045 int flags=fcntl(sock,F_GETFD,0);
1046 if(flags<0 || fcntl(sock, F_SETFD,flags|FD_CLOEXEC) <0)
1047 return false;
1048 return true;
1049 }
1050
1051 string getMACAddress(const ComboAddress& ca)
1052 {
1053 string ret;
1054 #ifdef __linux__
1055 ifstream ifs("/proc/net/arp");
1056 if(!ifs)
1057 return ret;
1058 string line;
1059 string match=ca.toString()+' ';
1060 while(getline(ifs, line)) {
1061 if(boost::starts_with(line, match)) {
1062 vector<string> parts;
1063 stringtok(parts, line, " \n\t\r");
1064 if(parts.size() < 4)
1065 return ret;
1066 unsigned int tmp[6];
1067 sscanf(parts[3].c_str(), "%02x:%02x:%02x:%02x:%02x:%02x", tmp, tmp+1, tmp+2, tmp+3, tmp+4, tmp+5);
1068 for(int i = 0 ; i< 6 ; ++i)
1069 ret.append(1, (char)tmp[i]);
1070 return ret;
1071 }
1072 }
1073 #endif
1074 return ret;
1075 }
1076
1077 uint64_t udpErrorStats(const std::string& str)
1078 {
1079 #ifdef __linux__
1080 ifstream ifs("/proc/net/snmp");
1081 if(!ifs)
1082 return 0;
1083 string line;
1084 vector<string> parts;
1085 while(getline(ifs,line)) {
1086 if(boost::starts_with(line, "Udp: ") && isdigit(line[5])) {
1087 stringtok(parts, line, " \n\t\r");
1088 if(parts.size() < 7)
1089 break;
1090 if(str=="udp-rcvbuf-errors")
1091 return std::stoull(parts[5]);
1092 else if(str=="udp-sndbuf-errors")
1093 return std::stoull(parts[6]);
1094 else if(str=="udp-noport-errors")
1095 return std::stoull(parts[2]);
1096 else if(str=="udp-in-errors")
1097 return std::stoull(parts[3]);
1098 else
1099 return 0;
1100 }
1101 }
1102 #endif
1103 return 0;
1104 }
1105
1106 bool getTSIGHashEnum(const DNSName& algoName, TSIGHashEnum& algoEnum)
1107 {
1108 if (algoName == DNSName("hmac-md5.sig-alg.reg.int") || algoName == DNSName("hmac-md5"))
1109 algoEnum = TSIG_MD5;
1110 else if (algoName == DNSName("hmac-sha1"))
1111 algoEnum = TSIG_SHA1;
1112 else if (algoName == DNSName("hmac-sha224"))
1113 algoEnum = TSIG_SHA224;
1114 else if (algoName == DNSName("hmac-sha256"))
1115 algoEnum = TSIG_SHA256;
1116 else if (algoName == DNSName("hmac-sha384"))
1117 algoEnum = TSIG_SHA384;
1118 else if (algoName == DNSName("hmac-sha512"))
1119 algoEnum = TSIG_SHA512;
1120 else if (algoName == DNSName("gss-tsig"))
1121 algoEnum = TSIG_GSS;
1122 else {
1123 return false;
1124 }
1125 return true;
1126 }
1127
1128 DNSName getTSIGAlgoName(TSIGHashEnum& algoEnum)
1129 {
1130 switch(algoEnum) {
1131 case TSIG_MD5: return DNSName("hmac-md5.sig-alg.reg.int.");
1132 case TSIG_SHA1: return DNSName("hmac-sha1.");
1133 case TSIG_SHA224: return DNSName("hmac-sha224.");
1134 case TSIG_SHA256: return DNSName("hmac-sha256.");
1135 case TSIG_SHA384: return DNSName("hmac-sha384.");
1136 case TSIG_SHA512: return DNSName("hmac-sha512.");
1137 case TSIG_GSS: return DNSName("gss-tsig.");
1138 }
1139 throw PDNSException("getTSIGAlgoName does not understand given algorithm, please fix!");
1140 }
1141
1142 uint64_t getOpenFileDescriptors(const std::string&)
1143 {
1144 #ifdef __linux__
1145 DIR* dirhdl=opendir(("/proc/"+std::to_string(getpid())+"/fd/").c_str());
1146 if(!dirhdl)
1147 return 0;
1148
1149 struct dirent *entry;
1150 int ret=0;
1151 while((entry = readdir(dirhdl))) {
1152 uint32_t num;
1153 try {
1154 num = pdns_stou(entry->d_name);
1155 } catch (...) {
1156 continue; // was not a number.
1157 }
1158 if(std::to_string(num) == entry->d_name)
1159 ret++;
1160 }
1161 closedir(dirhdl);
1162 return ret;
1163
1164 #else
1165 return 0;
1166 #endif
1167 }
1168
1169 uint64_t getRealMemoryUsage(const std::string&)
1170 {
1171 #ifdef __linux__
1172 ifstream ifs("/proc/"+std::to_string(getpid())+"/smaps");
1173 if(!ifs)
1174 return 0;
1175 string line;
1176 uint64_t bytes=0;
1177 string header("Private_Dirty:");
1178 while(getline(ifs, line)) {
1179 if(boost::starts_with(line, header)) {
1180 bytes += std::stoull(line.substr(header.length() + 1))*1024;
1181 }
1182 }
1183 return bytes;
1184 #else
1185 return 0;
1186 #endif
1187 }
1188
1189 uint64_t getCPUTimeUser(const std::string&)
1190 {
1191 struct rusage ru;
1192 getrusage(RUSAGE_SELF, &ru);
1193 return (ru.ru_utime.tv_sec*1000ULL + ru.ru_utime.tv_usec/1000);
1194 }
1195
1196 uint64_t getCPUTimeSystem(const std::string&)
1197 {
1198 struct rusage ru;
1199 getrusage(RUSAGE_SELF, &ru);
1200 return (ru.ru_stime.tv_sec*1000ULL + ru.ru_stime.tv_usec/1000);
1201 }
1202
1203 double DiffTime(const struct timespec& first, const struct timespec& second)
1204 {
1205 int seconds=second.tv_sec - first.tv_sec;
1206 int nseconds=second.tv_nsec - first.tv_nsec;
1207
1208 if(nseconds < 0) {
1209 seconds-=1;
1210 nseconds+=1000000000;
1211 }
1212 return seconds + nseconds/1000000000.0;
1213 }
1214
1215 double DiffTime(const struct timeval& first, const struct timeval& second)
1216 {
1217 int seconds=second.tv_sec - first.tv_sec;
1218 int useconds=second.tv_usec - first.tv_usec;
1219
1220 if(useconds < 0) {
1221 seconds-=1;
1222 useconds+=1000000;
1223 }
1224 return seconds + useconds/1000000.0;
1225 }
1226
1227 uid_t strToUID(const string &str)
1228 {
1229 uid_t result = 0;
1230 const char * cstr = str.c_str();
1231 struct passwd * pwd = getpwnam(cstr);
1232
1233 if (pwd == NULL) {
1234 long long val;
1235
1236 try {
1237 val = stoll(str);
1238 }
1239 catch(std::exception& e) {
1240 throw runtime_error((boost::format("Error: Unable to parse user ID %s") % cstr).str() );
1241 }
1242
1243 if (val < std::numeric_limits<uid_t>::min() || val > std::numeric_limits<uid_t>::max()) {
1244 throw runtime_error((boost::format("Error: Unable to parse user ID %s") % cstr).str() );
1245 }
1246
1247 result = static_cast<uid_t>(val);
1248 }
1249 else {
1250 result = pwd->pw_uid;
1251 }
1252
1253 return result;
1254 }
1255
1256 gid_t strToGID(const string &str)
1257 {
1258 gid_t result = 0;
1259 const char * cstr = str.c_str();
1260 struct group * grp = getgrnam(cstr);
1261
1262 if (grp == NULL) {
1263 long long val;
1264
1265 try {
1266 val = stoll(str);
1267 }
1268 catch(std::exception& e) {
1269 throw runtime_error((boost::format("Error: Unable to parse group ID %s") % cstr).str() );
1270 }
1271
1272 if (val < std::numeric_limits<gid_t>::min() || val > std::numeric_limits<gid_t>::max()) {
1273 throw runtime_error((boost::format("Error: Unable to parse group ID %s") % cstr).str() );
1274 }
1275
1276 result = static_cast<gid_t>(val);
1277 }
1278 else {
1279 result = grp->gr_gid;
1280 }
1281
1282 return result;
1283 }
1284
1285 unsigned int pdns_stou(const std::string& str, size_t * idx, int base)
1286 {
1287 if (str.empty()) return 0; // compability
1288 unsigned long result = std::stoul(str, idx, base);
1289 if (result > std::numeric_limits<unsigned int>::max()) {
1290 throw std::out_of_range("stou");
1291 }
1292 return static_cast<unsigned int>(result);
1293 }
1294