]> git.ipfire.org Git - thirdparty/pdns.git/blame - pdns/misc.cc
Merge pull request #4823 from rgacogne/dnsdist-110-changelog
[thirdparty/pdns.git] / pdns / misc.cc
CommitLineData
12c86877 1/*
12471842
PL
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 */
870a0fe4
AT
22#ifdef HAVE_CONFIG_H
23#include "config.h"
24#endif
705f31ae 25#include <sys/param.h>
22cf1fda 26#include <sys/socket.h>
3897b9e1 27#include <fcntl.h>
705f31ae
BH
28#include <netdb.h>
29#include <sys/time.h>
30#include <time.h>
3a8a4d68 31#include <sys/resource.h>
705f31ae 32#include <netinet/in.h>
76cb4593 33#include <sys/un.h>
705f31ae 34#include <unistd.h>
8290ad9f 35#include <fstream>
12c86877
BH
36#include "misc.hh"
37#include <vector>
38#include <sstream>
39#include <errno.h>
1258abe0 40#include <cstring>
c4bee46c 41#include <iostream>
a9b6db56 42#include <sys/types.h>
43#include <dirent.h>
705f31ae 44#include <algorithm>
6e2514e4 45#include <boost/optional.hpp>
fab091b9 46#include <poll.h>
12c86877 47#include <iomanip>
149d0144 48#include <netinet/tcp.h>
12c86877
BH
49#include <string.h>
50#include <stdlib.h>
51#include <stdio.h>
5c409fa2 52#include "pdnsexception.hh"
c6566265 53#include <sys/types.h>
040712e0 54#include <boost/algorithm/string.hpp>
65d8e171 55#include "iputils.hh"
e325f20c 56#include "dnsparser.hh"
ffb07158 57#include <sys/types.h>
58#include <pwd.h>
59#include <grp.h>
60
a61e8e59 61
1e08edde
BH
62bool g_singleThreaded;
63
a683e8bd 64size_t writen2(int fd, const void *buf, size_t count)
040712e0
BH
65{
66 const char *ptr = (char*)buf;
67 const char *eptr = ptr + count;
3ddb9247 68
a683e8bd 69 ssize_t res;
040712e0
BH
70 while(ptr != eptr) {
71 res = ::write(fd, ptr, eptr - ptr);
72 if(res < 0) {
73 if (errno == EAGAIN)
4957a608 74 throw std::runtime_error("used writen2 on non-blocking socket, got EAGAIN");
040712e0 75 else
4957a608 76 unixDie("failed in writen2");
040712e0
BH
77 }
78 else if (res == 0)
79 throw std::runtime_error("could not write all bytes, got eof in writen2");
3ddb9247 80
a683e8bd 81 ptr += (size_t) res;
040712e0 82 }
3ddb9247 83
040712e0
BH
84 return count;
85}
86
a683e8bd 87size_t readn2(int fd, void* buffer, size_t len)
36fbf590 88{
a683e8bd
RG
89 size_t pos=0;
90 ssize_t res;
36fbf590 91 for(;;) {
92 res = read(fd, (char*)buffer + pos, len - pos);
3ddb9247 93 if(res == 0)
3f6d07a4 94 throw runtime_error("EOF while reading message");
36fbf590 95 if(res < 0) {
96 if (errno == EAGAIN)
3f6d07a4 97 throw std::runtime_error("used readn2 on non-blocking socket, got EAGAIN");
36fbf590 98 else
3f6d07a4 99 unixDie("failed in readn2");
3ddb9247
PD
100 }
101
a683e8bd 102 pos+=(size_t)res;
36fbf590 103 if(pos == len)
104 break;
105 }
106 return len;
107}
108
a683e8bd 109size_t readn2WithTimeout(int fd, void* buffer, size_t len, int timeout)
3f6d07a4
RG
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
a683e8bd 142size_t writen2WithTimeout(int fd, const void * buffer, size_t len, int timeout)
3f6d07a4
RG
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}
12c86877 174
cc3afe25
BH
175string nowTime()
176{
74ab661c
CH
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;
cc3afe25 184}
12c86877 185
092f210a 186uint16_t getShort(const unsigned char *p)
0d8612f2
BH
187{
188 return p[0] * 256 + p[1];
189}
190
191
092f210a 192uint16_t getShort(const char *p)
0d8612f2
BH
193{
194 return getShort((const unsigned char *)p);
195}
196
092f210a 197uint32_t getLong(const unsigned char* p)
b636533b
BH
198{
199 return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3];
200}
201
092f210a 202uint32_t getLong(const char* p)
b636533b
BH
203{
204 return getLong((unsigned char *)p);
205}
206
a683e8bd 207static bool ciEqual(const string& a, const string& b)
49bd5a20
BH
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
728485ca 219/** does domain end on suffix? Is smart about "wwwds9a.nl" "ds9a.nl" not matching */
a683e8bd 220static bool endsOn(const string &domain, const string &suffix)
728485ca 221{
49bd5a20 222 if( suffix.empty() || ciEqual(domain, suffix) )
728485ca 223 return true;
7738a23f 224
728485ca
BH
225 if(domain.size()<=suffix.size())
226 return false;
3ddb9247 227
49bd5a20 228 string::size_type dpos=domain.size()-suffix.size()-1, spos=0;
7738a23f 229
49bd5a20
BH
230 if(domain[dpos++]!='.')
231 return false;
728485ca 232
49bd5a20
BH
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}
f2c11a48 239
a683e8bd
RG
240/** strips a domain suffix from a domain, returns true if it stripped */
241bool 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
32252594 257static void parseService4(const string &descr, ServiceTuple &st)
12c86877
BH
258{
259 vector<string>parts;
260 stringtok(parts,descr,":");
52936200 261 if(parts.empty())
3f81d239 262 throw PDNSException("Unable to parse '"+descr+"' as a service");
12c86877
BH
263 st.host=parts[0];
264 if(parts.size()>1)
335da0ba 265 st.port=pdns_stou(parts[1]);
12c86877
BH
266}
267
32252594
BH
268static void parseService6(const string &descr, ServiceTuple &st)
269{
270 string::size_type pos=descr.find(']');
271 if(pos == string::npos)
3f81d239 272 throw PDNSException("Unable to parse '"+descr+"' as an IPv6 service");
32252594
BH
273
274 st.host=descr.substr(1, pos-1);
275 if(pos + 2 < descr.length())
335da0ba 276 st.port=pdns_stou(descr.substr(pos+2));
32252594
BH
277}
278
279
280void parseService(const string &descr, ServiceTuple &st)
281{
282 if(descr.empty())
3f81d239 283 throw PDNSException("Unable to parse '"+descr+"' as a service");
32252594
BH
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}
12c86877 298
1fb3f0fc 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
a7d50153 300int waitForData(int fd, int seconds, int useconds)
649a88df
BH
301{
302 return waitForRWData(fd, true, seconds, useconds);
303}
304
51959320 305int waitForRWData(int fd, bool waitForRead, int seconds, int useconds, bool* error, bool* disconnected)
12c86877 306{
1258abe0
BH
307 int ret;
308
fab091b9
BH
309 struct pollfd pfd;
310 memset(&pfd, 0, sizeof(pfd));
311 pfd.fd = fd;
3ddb9247 312
649a88df 313 if(waitForRead)
fab091b9 314 pfd.events=POLLIN;
649a88df 315 else
fab091b9 316 pfd.events=POLLOUT;
1258abe0 317
6b3d4330 318 ret = poll(&pfd, 1, seconds * 1000 + useconds/1000);
51959320 319 if ( ret == -1 ) {
f4ff5929 320 errno = ETIMEDOUT; // ???
51959320
RG
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 }
1258abe0 330
12c86877
BH
331 return ret;
332}
333
a71bee29 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
f4ff5929
BH
335int 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;
3ddb9247 343
f4ff5929
BH
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;
3ddb9247 354
f4ff5929
BH
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
3ddb9247 364
f4ff5929
BH
365 return 1;
366}
367
12c86877
BH
368
369string humanDuration(time_t passed)
370{
371 ostringstream ret;
372 if(passed<60)
373 ret<<passed<<" seconds";
374 else if(passed<3600)
9e04108d 375 ret<<std::setprecision(2)<<passed/60.0<<" minutes";
12c86877 376 else if(passed<86400)
9e04108d 377 ret<<std::setprecision(3)<<passed/3600.0<<" hours";
12c86877 378 else if(passed<(86400*30.41))
9e04108d 379 ret<<std::setprecision(3)<<passed/86400.0<<" days";
12c86877 380 else
9e04108d 381 ret<<std::setprecision(3)<<passed/(86400*30.41)<<" months";
12c86877
BH
382
383 return ret.str();
384}
385
386DTime::DTime()
387{
eefd15f9 388// set(); // saves lots of gettimeofday calls
55b6512d 389 d_set.tv_sec=d_set.tv_usec=0;
12c86877
BH
390}
391
392DTime::DTime(const DTime &dt)
393{
394 d_set=dt.d_set;
395}
396
397time_t DTime::time()
398{
399 return d_set.tv_sec;
400}
401
1d329048
BH
402const string unquotify(const string &item)
403{
404 if(item.size()<2)
405 return item;
406
407 string::size_type bpos=0, epos=item.size();
12c86877 408
3ddb9247 409 if(item[0]=='"')
1d329048 410 bpos=1;
c4bee46c 411
1d329048
BH
412 if(item[epos-1]=='"')
413 epos-=1;
414
c4bee46c 415 return item.substr(bpos,epos-bpos);
1d329048 416}
12c86877
BH
417
418void stripLine(string &line)
419{
bdf40704 420 string::size_type pos=line.find_first_of("\r\n");
12c86877
BH
421 if(pos!=string::npos) {
422 line.resize(pos);
423 }
424}
425
426string 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
435string getHostname()
436{
0db70140 437#ifndef MAXHOSTNAMELEN
76473b92 438#define MAXHOSTNAMELEN 255
0db70140 439#endif
ac2bb9e7 440
12c86877
BH
441 char tmp[MAXHOSTNAMELEN];
442 if(gethostname(tmp, MAXHOSTNAMELEN))
443 return "UNKNOWN";
444
445 return tmp;
446}
447
448string itoa(int i)
449{
450 ostringstream o;
451 o<<i;
452 return o.str();
453}
454
22c9c86a
BH
455string 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
d88babea
KM
462string 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}
22c9c86a 471
12c86877
BH
472string stringerror()
473{
474 return strerror(errno);
475}
476
d3b4137e
BH
477string netstringerror()
478{
479 return stringerror();
480}
d3b4137e 481
12c86877
BH
482void 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
7b35aa49 494
092f210a 495bool IpToU32(const string &str, uint32_t *ip)
525b8a7c 496{
4cf26303
BH
497 if(str.empty()) {
498 *ip=0;
499 return true;
500 }
3ddb9247 501
092c9cc4 502 struct in_addr inp;
3897b9e1 503 if(inet_aton(str.c_str(), &inp)) {
092c9cc4
BH
504 *ip=inp.s_addr;
505 return true;
506 }
507 return false;
525b8a7c
BH
508}
509
5730f30c
BH
510string U32ToIP(uint32_t val)
511{
512 char tmp[17];
3ddb9247 513 snprintf(tmp, sizeof(tmp)-1, "%u.%u.%u.%u",
4957a608
BH
514 (val >> 24)&0xff,
515 (val >> 16)&0xff,
516 (val >> 8)&0xff,
517 (val )&0xff);
5730f30c
BH
518 return tmp;
519}
520
37d3f960 521
2db9c30e
BH
522string makeHexDump(const string& str)
523{
524 char tmp[5];
525 string ret;
ea634573 526 ret.reserve((int)(str.size()*2.2));
2db9c30e
BH
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
e67e250f 535// shuffle, maintaining some semblance of order
d190894c 536void shuffle(vector<DNSZoneRecord>& rrs)
e67e250f 537{
d190894c 538 vector<DNSZoneRecord>::iterator first, second;
3ddb9247 539 for(first=rrs.begin();first!=rrs.end();++first)
d190894c 540 if(first->dr.d_place==DNSResourceRecord::ANSWER && first->dr.d_type != QType::CNAME) // CNAME must come first
e67e250f
BH
541 break;
542 for(second=first;second!=rrs.end();++second)
d190894c 543 if(second->dr.d_place!=DNSResourceRecord::ANSWER)
e67e250f 544 break;
3ddb9247 545
d190894c 546 if(second-first > 1)
e67e250f 547 random_shuffle(first,second);
3ddb9247 548
e67e250f 549 // now shuffle the additional records
3ddb9247 550 for(first=second;first!=rrs.end();++first)
d190894c 551 if(first->dr.d_place==DNSResourceRecord::ADDITIONAL && first->dr.d_type != QType::CNAME) // CNAME must come first
e67e250f
BH
552 break;
553 for(second=first;second!=rrs.end();++second)
d190894c 554 if(second->dr.d_place!=DNSResourceRecord::ADDITIONAL)
e67e250f 555 break;
3ddb9247 556
e67e250f
BH
557 if(second-first>1)
558 random_shuffle(first,second);
559
560 // we don't shuffle the rest
561}
88358c9b 562
e325f20c 563
564// shuffle, maintaining some semblance of order
565void shuffle(vector<DNSRecord>& rrs)
92476c8b 566{
e325f20c 567 vector<DNSRecord>::iterator first, second;
568 for(first=rrs.begin();first!=rrs.end();++first)
e693ff5a 569 if(first->d_place==DNSResourceRecord::ANSWER && first->d_type != QType::CNAME) // CNAME must come first
e325f20c 570 break;
571 for(second=first;second!=rrs.end();++second)
2cccc377 572 if(second->d_place!=DNSResourceRecord::ANSWER || second->d_type == QType::RRSIG) // leave RRSIGs at the end
e325f20c 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)
e693ff5a 580 if(first->d_place==DNSResourceRecord::ADDITIONAL && first->d_type != QType::CNAME) // CNAME must come first
e325f20c 581 break;
582 for(second=first; second!=rrs.end(); ++second)
e693ff5a 583 if(second->d_place!=DNSResourceRecord::ADDITIONAL)
e325f20c 584 break;
585
586 if(second-first>1)
587 random_shuffle(first,second);
588
589 // we don't shuffle the rest
92476c8b
PD
590}
591
2cccc377 592static uint16_t mapTypesToOrder(uint16_t type)
27b85f24 593{
594 if(type == QType::CNAME)
595 return 0;
2cccc377 596 if(type == QType::RRSIG)
597 return 65535;
27b85f24 598 else
599 return 1;
600}
601
92476c8b
PD
602// make sure rrs is sorted in d_place order to avoid surprises later
603// then shuffle the parts that desire shuffling
e325f20c 604void orderAndShuffle(vector<DNSRecord>& rrs)
92476c8b 605{
e325f20c 606 std::stable_sort(rrs.begin(), rrs.end(), [](const DNSRecord&a, const DNSRecord& b) {
2cccc377 607 return std::make_tuple(a.d_place, mapTypesToOrder(a.d_type)) < std::make_tuple(b.d_place, mapTypesToOrder(b.d_type));
e325f20c 608 });
92476c8b
PD
609 shuffle(rrs);
610}
88358c9b
BH
611
612void 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
624const 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
633const 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}
50c79a76
BH
641
642pair<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}
6e2514e4 654
f8499e52 655int logFacilityToLOG(unsigned int facility)
6e2514e4 656{
6e2514e4
BH
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:
f8499e52 675 return -1;
6e2514e4
BH
676 }
677}
da042e6e
BH
678
679string 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}
4dadd22f
BH
689
690
f71bc087
BH
691
692int makeIPv6sockaddr(const std::string& addr, struct sockaddr_in6* ret)
693{
85db02c5
BH
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);
5b4ed369
PL
703 try {
704 port = pdns_stou(addr.substr(pos+2));
705 }
706 catch(std::out_of_range) {
707 return -1;
708 }
85db02c5 709 }
39d2d9b2 710 ret->sin6_scope_id=0;
711 ret->sin6_family=AF_INET6;
712
0c9de4fc 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));
3ddb9247 717
0c9de4fc 718 hints.ai_family = AF_INET6;
719 hints.ai_flags = AI_NUMERICHOST;
3ddb9247 720
0c9de4fc 721 int error;
722 if((error=getaddrinfo(ourAddr.c_str(), 0, &hints, &res))) { // this is correct
723 return -1;
724 }
3ddb9247 725
0c9de4fc 726 memcpy(ret, res->ai_addr, res->ai_addrlen);
727 freeaddrinfo(res);
f71bc087 728 }
0c9de4fc 729
5b4ed369
PL
730 if(port > 65535)
731 // negative ports are found with the pdns_stou above
732 return -1;
733
85db02c5
BH
734 if(port >= 0)
735 ret->sin6_port = htons(port);
0c9de4fc 736
f71bc087
BH
737 return 0;
738}
834942f1 739
76cb4593 740int makeIPv4sockaddr(const std::string& str, struct sockaddr_in* ret)
85db02c5
BH
741{
742 if(str.empty()) {
743 return -1;
744 }
745 struct in_addr inp;
3ddb9247 746
85db02c5
BH
747 string::size_type pos = str.find(':');
748 if(pos == string::npos) { // no port specified, not touching the port
3897b9e1 749 if(inet_aton(str.c_str(), &inp)) {
85db02c5
BH
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 :
3ddb9247
PD
756 return -1;
757
85db02c5
BH
758 char *eptr = (char*)str.c_str() + str.size();
759 int port = strtol(str.c_str() + pos + 1, &eptr, 10);
5b4ed369
PL
760 if (port < 0 || port > 65535)
761 return -1;
762
85db02c5
BH
763 if(*eptr)
764 return -1;
3ddb9247 765
85db02c5 766 ret->sin_port = htons(port);
3897b9e1 767 if(inet_aton(str.substr(0, pos).c_str(), &inp)) {
85db02c5
BH
768 ret->sin_addr.s_addr=inp.s_addr;
769 return 0;
770 }
771 return -1;
772}
773
76cb4593
CH
774int 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}
85db02c5 787
834942f1
BH
788//! read a line of text from a FILE* to a std::string, returns false on 'no data'
789bool stringfgets(FILE* fp, std::string& line)
790{
791 char buffer[1024];
792 line.clear();
3ddb9247 793
834942f1
BH
794 do {
795 if(!fgets(buffer, sizeof(buffer), fp))
796 return !line.empty();
3ddb9247
PD
797
798 line.append(buffer);
834942f1
BH
799 } while(!strchr(buffer, '\n'));
800 return true;
801}
e611a06c 802
4e9a20e6 803bool 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
3ee84c3f
BH
814Regex::Regex(const string &expr)
815{
816 if(regcomp(&d_preg, expr.c_str(), REG_ICASE|REG_NOSUB|REG_EXTENDED))
3f81d239 817 throw PDNSException("Regular expression did not compile");
3ee84c3f 818}
65d8e171 819
25ba7344
PD
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.
fbe2a2e0 823void addCMsgSrcAddr(struct msghdr* msgh, void* cmsgbuf, const ComboAddress* source, int itfIndex)
65d8e171 824{
ecc8571f 825 struct cmsghdr *cmsg = NULL;
65d8e171
KN
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;
fbe2a2e0 841 pkt->ipi6_ifindex = itfIndex;
65d8e171
KN
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;
fbe2a2e0 858 pkt->ipi_ifindex = itfIndex;
65d8e171
KN
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;
ecc8571f 873#endif
65d8e171
KN
874 }
875}
3a8a4d68 876
877unsigned 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
885void 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}
06ea9015 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
909uint32_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}
9ae194e2 948
6200227b 949uint32_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) {
af891b3d 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));
6200227b 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 */
af891b3d 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);
6200227b 973 /* the first byte of c is reserved for the length */
af891b3d 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]);
6200227b 982 /* case 0: nothing left to add */
983 }
984 burtlemix(a,b,c);
985 /*-------------------------------------------- report the result */
986 return c;
987}
988
989
915b0c39 990bool setSocketTimestamps(int fd)
9ae194e2 991{
eb4c1792 992#ifdef SO_TIMESTAMP
9ae194e2 993 int on=1;
915b0c39 994 return setsockopt(fd, SOL_SOCKET, SO_TIMESTAMP, (char*)&on, sizeof(on)) == 0;
eb4c1792 995#endif
915b0c39 996 return true; // we pretend this happened.
9ae194e2 997}
58044407 998
883a30a7 999bool setTCPNoDelay(int sock)
149d0144 1000{
1001 int flag = 1;
883a30a7
RG
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 */
149d0144 1007}
1008
1009
3897b9e1 1010bool setNonBlocking(int sock)
1011{
3ddb9247 1012 int flags=fcntl(sock,F_GETFL,0);
3897b9e1 1013 if(flags<0 || fcntl(sock, F_SETFL,flags|O_NONBLOCK) <0)
1014 return false;
1015 return true;
1016}
1017
1018bool setBlocking(int sock)
1019{
3ddb9247 1020 int flags=fcntl(sock,F_GETFL,0);
3897b9e1 1021 if(flags<0 || fcntl(sock, F_SETFL,flags&(~O_NONBLOCK)) <0)
1022 return false;
1023 return true;
1024}
1025
18861f97
RG
1026bool isNonBlocking(int sock)
1027{
1028 int flags=fcntl(sock,F_GETFL,0);
1029 return flags & O_NONBLOCK;
1030}
1031
3897b9e1 1032// Closes a socket.
1033int closesocket( int socket )
1034{
1035 int ret=::close(socket);
1036 if(ret < 0 && errno == ECONNRESET) // see ticket 192, odd BSD behaviour
1037 return 0;
3ddb9247 1038 if(ret < 0)
3897b9e1 1039 throw PDNSException("Error closing socket: "+stringerror());
1040 return ret;
1041}
1042
1043bool setCloseOnExec(int sock)
1044{
3ddb9247 1045 int flags=fcntl(sock,F_GETFD,0);
3897b9e1 1046 if(flags<0 || fcntl(sock, F_SETFD,flags|FD_CLOEXEC) <0)
1047 return false;
1048 return true;
1049}
1050
6907f014 1051string 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
8290ad9f 1077uint64_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")
335da0ba 1091 return std::stoull(parts[5]);
8290ad9f 1092 else if(str=="udp-sndbuf-errors")
335da0ba 1093 return std::stoull(parts[6]);
8290ad9f 1094 else if(str=="udp-noport-errors")
335da0ba 1095 return std::stoull(parts[2]);
8290ad9f 1096 else if(str=="udp-in-errors")
335da0ba 1097 return std::stoull(parts[3]);
8290ad9f 1098 else
1099 return 0;
1100 }
1101 }
1102#endif
1103 return 0;
1104}
da15912b 1105
21a3792f 1106bool getTSIGHashEnum(const DNSName& algoName, TSIGHashEnum& algoEnum)
da15912b 1107{
2330c421 1108 if (algoName == DNSName("hmac-md5.sig-alg.reg.int") || algoName == DNSName("hmac-md5"))
da15912b 1109 algoEnum = TSIG_MD5;
2330c421 1110 else if (algoName == DNSName("hmac-sha1"))
da15912b 1111 algoEnum = TSIG_SHA1;
2330c421 1112 else if (algoName == DNSName("hmac-sha224"))
da15912b 1113 algoEnum = TSIG_SHA224;
2330c421 1114 else if (algoName == DNSName("hmac-sha256"))
da15912b 1115 algoEnum = TSIG_SHA256;
2330c421 1116 else if (algoName == DNSName("hmac-sha384"))
da15912b 1117 algoEnum = TSIG_SHA384;
2330c421 1118 else if (algoName == DNSName("hmac-sha512"))
da15912b 1119 algoEnum = TSIG_SHA512;
2330c421 1120 else if (algoName == DNSName("gss-tsig"))
bcb5b94e 1121 algoEnum = TSIG_GSS;
da15912b
AT
1122 else {
1123 return false;
1124 }
1125 return true;
1126}
bfd4efae 1127
21a3792f 1128DNSName getTSIGAlgoName(TSIGHashEnum& algoEnum)
bfd4efae
AT
1129{
1130 switch(algoEnum) {
8171ab83 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.");
bfd4efae
AT
1138 }
1139 throw PDNSException("getTSIGAlgoName does not understand given algorithm, please fix!");
1140}
a1a787dc 1141
a9b6db56 1142uint64_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))) {
335da0ba
AT
1152 uint32_t num;
1153 try {
1154 num = pdns_stou(entry->d_name);
1155 } catch (...) {
1156 continue; // was not a number.
1157 }
a9b6db56 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
a1a787dc 1169uint64_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)) {
335da0ba 1180 bytes += std::stoull(line.substr(header.length() + 1))*1024;
a1a787dc 1181 }
1182 }
1183 return bytes;
1184#else
1185 return 0;
1186#endif
1187}
4f99f3d3
RG
1188
1189uint64_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
1196uint64_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}
3fcaeeac 1202
1203double 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
1215double 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}
ffb07158 1226
ffb07158 1227uid_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) {
e805cba5 1234 long long val;
ffb07158 1235
e805cba5
RG
1236 try {
1237 val = stoll(str);
ffb07158 1238 }
e805cba5
RG
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() );
ffb07158 1245 }
e805cba5
RG
1246
1247 result = static_cast<uid_t>(val);
ffb07158 1248 }
1249 else {
1250 result = pwd->pw_uid;
1251 }
1252
1253 return result;
1254}
1255
1256gid_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) {
e805cba5 1263 long long val;
ffb07158 1264
e805cba5
RG
1265 try {
1266 val = stoll(str);
ffb07158 1267 }
e805cba5
RG
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() );
ffb07158 1274 }
e805cba5
RG
1275
1276 result = static_cast<gid_t>(val);
ffb07158 1277 }
1278 else {
1279 result = grp->gr_gid;
1280 }
1281
1282 return result;
1283}
1284
335da0ba 1285unsigned int pdns_stou(const std::string& str, size_t * idx, int base)
a5c4e4a6
AT
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