]> git.ipfire.org Git - thirdparty/pdns.git/blob - pdns/misc.hh
dnsdist: Add TCP management options from rfc7766 section 10
[thirdparty/pdns.git] / pdns / misc.hh
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 #pragma once
23 #include <errno.h>
24 #include <inttypes.h>
25 #include <cstring>
26 #include <cstdio>
27 #include <regex.h>
28 #include <limits.h>
29 #include <type_traits>
30 #include <boost/algorithm/string.hpp>
31 #include <boost/multi_index_container.hpp>
32 #include <boost/multi_index/ordered_index.hpp>
33 #include <boost/tuple/tuple_comparison.hpp>
34 #include <boost/multi_index/key_extractors.hpp>
35 #include <boost/multi_index/sequenced_index.hpp>
36
37 using namespace ::boost::multi_index;
38
39 #include "dns.hh"
40 #include <atomic>
41 #include <sys/time.h>
42 #include <sys/types.h>
43 #include <sys/socket.h>
44 #include <time.h>
45 #include <syslog.h>
46 #include <deque>
47 #include <stdexcept>
48 #include <string>
49 #include <ctype.h>
50 #include <vector>
51
52 #include "namespaces.hh"
53 #include "dnsname.hh"
54
55 typedef enum { TSIG_MD5, TSIG_SHA1, TSIG_SHA224, TSIG_SHA256, TSIG_SHA384, TSIG_SHA512, TSIG_GSS } TSIGHashEnum;
56
57 string nowTime();
58 const string unquotify(const string &item);
59 string humanDuration(time_t passed);
60 bool stripDomainSuffix(string *qname, const string &domain);
61 void stripLine(string &line);
62 string getHostname();
63 string urlEncode(const string &text);
64 int waitForData(int fd, int seconds, int useconds=0);
65 int waitFor2Data(int fd1, int fd2, int seconds, int useconds, int* fd);
66 int waitForRWData(int fd, bool waitForRead, int seconds, int useconds, bool* error=nullptr, bool* disconnected=nullptr);
67 uint16_t getShort(const unsigned char *p);
68 uint16_t getShort(const char *p);
69 uint32_t getLong(const unsigned char *p);
70 uint32_t getLong(const char *p);
71 bool getTSIGHashEnum(const DNSName& algoName, TSIGHashEnum& algoEnum);
72 DNSName getTSIGAlgoName(TSIGHashEnum& algoEnum);
73
74 int logFacilityToLOG(unsigned int facility);
75
76 struct ServiceTuple
77 {
78 string host;
79 uint16_t port;
80 };
81 void parseService(const string &descr, ServiceTuple &st);
82
83 template <typename Container>
84 void
85 stringtok (Container &container, string const &in,
86 const char * const delimiters = " \t\n")
87 {
88 const string::size_type len = in.length();
89 string::size_type i = 0;
90
91 while (i<len) {
92 // eat leading whitespace
93 i = in.find_first_not_of (delimiters, i);
94 if (i == string::npos)
95 return; // nothing left but white space
96
97 // find the end of the token
98 string::size_type j = in.find_first_of (delimiters, i);
99
100 // push token
101 if (j == string::npos) {
102 container.push_back (in.substr(i));
103 return;
104 } else
105 container.push_back (in.substr(i, j-i));
106
107 // set up for next loop
108 i = j + 1;
109 }
110 }
111
112 template<typename T> bool rfc1982LessThan(T a, T b)
113 {
114 return ((signed)(a - b)) < 0;
115 }
116
117 // fills container with ranges, so {posbegin,posend}
118 template <typename Container>
119 void
120 vstringtok (Container &container, string const &in,
121 const char * const delimiters = " \t\n")
122 {
123 const string::size_type len = in.length();
124 string::size_type i = 0;
125
126 while (i<len) {
127 // eat leading whitespace
128 i = in.find_first_not_of (delimiters, i);
129 if (i == string::npos)
130 return; // nothing left but white space
131
132 // find the end of the token
133 string::size_type j = in.find_first_of (delimiters, i);
134
135 // push token
136 if (j == string::npos) {
137 container.push_back (make_pair(i, len));
138 return;
139 } else
140 container.push_back (make_pair(i, j));
141
142 // set up for next loop
143 i = j + 1;
144 }
145 }
146
147 size_t writen2(int fd, const void *buf, size_t count);
148 inline size_t writen2(int fd, const std::string &s) { return writen2(fd, s.data(), s.size()); }
149 size_t readn2(int fd, void* buffer, size_t len);
150 size_t readn2WithTimeout(int fd, void* buffer, size_t len, int idleTimeout, int totalTimeout=0);
151 size_t writen2WithTimeout(int fd, const void * buffer, size_t len, int timeout);
152
153 const string toLower(const string &upper);
154 const string toLowerCanonic(const string &upper);
155 bool IpToU32(const string &str, uint32_t *ip);
156 string U32ToIP(uint32_t);
157 string stringerror();
158 string netstringerror();
159 string itoa(int i);
160 string uitoa(unsigned int i);
161 string bitFlip(const string &str);
162
163 void dropPrivs(int uid, int gid);
164 int makeGidNumeric(const string &group);
165 int makeUidNumeric(const string &user);
166 void cleanSlashes(string &str);
167
168 #if defined(_POSIX_THREAD_CPUTIME) && defined(CLOCK_THREAD_CPUTIME_ID)
169 /** CPUTime measurements */
170 class CPUTime
171 {
172 public:
173 void start()
174 {
175 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &d_start);
176 }
177 uint64_t ndiff()
178 {
179 struct timespec now;
180 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
181 return 1000000000ULL*(now.tv_sec - d_start.tv_sec) + (now.tv_nsec - d_start.tv_nsec);
182 }
183 private:
184 struct timespec d_start;
185 };
186 #endif
187
188 /** The DTime class can be used for timing statistics with microsecond resolution.
189 On 32 bits systems this means that 2147 seconds is the longest time that can be measured. */
190 class DTime
191 {
192 public:
193 DTime(); //!< Does not set the timer for you! Saves lots of gettimeofday() calls
194 DTime(const DTime &dt);
195 time_t time();
196 inline void set(); //!< Reset the timer
197 inline int udiff(); //!< Return the number of microseconds since the timer was last set.
198 inline int udiffNoReset(); //!< Return the number of microseconds since the timer was last set.
199 void setTimeval(const struct timeval& tv)
200 {
201 d_set=tv;
202 }
203 struct timeval getTimeval()
204 {
205 return d_set;
206 }
207 private:
208 struct timeval d_set;
209 };
210
211 inline void DTime::set()
212 {
213 gettimeofday(&d_set,0);
214 }
215
216 inline int DTime::udiff()
217 {
218 int res=udiffNoReset();
219 gettimeofday(&d_set,0);
220 return res;
221 }
222
223 inline int DTime::udiffNoReset()
224 {
225 struct timeval now;
226
227 gettimeofday(&now,0);
228 int ret=1000000*(now.tv_sec-d_set.tv_sec)+(now.tv_usec-d_set.tv_usec);
229 return ret;
230 }
231
232
233 inline bool dns_isspace(char c)
234 {
235 return c==' ' || c=='\t' || c=='\r' || c=='\n';
236 }
237
238 inline char dns_tolower(char c)
239 {
240 if(c>='A' && c<='Z')
241 c+='a'-'A';
242 return c;
243 }
244
245 inline char dns_toupper(char c)
246 {
247 if(c>='a' && c<='z')
248 c+='A'-'a';
249 return c;
250 }
251
252 inline const string toLower(const string &upper)
253 {
254 string reply(upper);
255 char c;
256 for(unsigned int i = 0; i < reply.length(); i++) {
257 c = dns_tolower(upper[i]);
258 if( c != upper[i])
259 reply[i] = c;
260 }
261 return reply;
262 }
263
264 inline const string toLowerCanonic(const string &upper)
265 {
266 string reply(upper);
267 if(!upper.empty()) {
268 unsigned int i, limit= ( unsigned int ) reply.length();
269 char c;
270 for(i = 0; i < limit ; i++) {
271 c = dns_tolower(upper[i]);
272 if(c != upper[i])
273 reply[i] = c;
274 }
275 if(upper[i-1]=='.')
276 reply.resize(i-1);
277 }
278
279 return reply;
280 }
281
282
283
284 // Make s uppercase:
285 inline string toUpper( const string& s )
286 {
287 string r(s);
288 for( unsigned int i = 0; i < s.length(); i++ ) {
289 r[i] = dns_toupper(r[i]);
290 }
291 return r;
292 }
293
294 inline double getTime()
295 {
296 struct timeval now;
297 gettimeofday(&now,0);
298
299 return now.tv_sec+now.tv_usec/1000000.0;
300 }
301
302 inline void unixDie(const string &why)
303 {
304 throw runtime_error(why+": "+strerror(errno));
305 }
306
307 string makeHexDump(const string& str);
308 void shuffle(vector<DNSRecord>& rrs);
309 struct DNSZoneRecord;
310 void shuffle(vector<DNSZoneRecord>& rrs);
311
312 void orderAndShuffle(vector<DNSRecord>& rrs);
313
314 void normalizeTV(struct timeval& tv);
315 const struct timeval operator+(const struct timeval& lhs, const struct timeval& rhs);
316 const struct timeval operator-(const struct timeval& lhs, const struct timeval& rhs);
317 inline float makeFloat(const struct timeval& tv)
318 {
319 return tv.tv_sec + tv.tv_usec/1000000.0f;
320 }
321
322 inline bool operator<(const struct timeval& lhs, const struct timeval& rhs)
323 {
324 return make_pair(lhs.tv_sec, lhs.tv_usec) < make_pair(rhs.tv_sec, rhs.tv_usec);
325 }
326
327 inline bool operator<(const struct timespec& lhs, const struct timespec& rhs)
328 {
329 return tie(lhs.tv_sec, lhs.tv_nsec) < tie(rhs.tv_sec, rhs.tv_nsec);
330 }
331
332
333 inline bool pdns_ilexicographical_compare(const std::string& a, const std::string& b) __attribute__((pure));
334 inline bool pdns_ilexicographical_compare(const std::string& a, const std::string& b)
335 {
336 const unsigned char *aPtr = (const unsigned char*)a.c_str(), *bPtr = (const unsigned char*)b.c_str();
337 const unsigned char *aEptr = aPtr + a.length(), *bEptr = bPtr + b.length();
338 while(aPtr != aEptr && bPtr != bEptr) {
339 if ((*aPtr != *bPtr) && (dns_tolower(*aPtr) - dns_tolower(*bPtr)))
340 return (dns_tolower(*aPtr) - dns_tolower(*bPtr)) < 0;
341 aPtr++;
342 bPtr++;
343 }
344 if(aPtr == aEptr && bPtr == bEptr) // strings are equal (in length)
345 return false;
346 return aPtr == aEptr; // true if first string was shorter
347 }
348
349 inline bool pdns_iequals(const std::string& a, const std::string& b) __attribute__((pure));
350 inline bool pdns_iequals(const std::string& a, const std::string& b)
351 {
352 if (a.length() != b.length())
353 return false;
354
355 const char *aPtr = a.c_str(), *bPtr = b.c_str();
356 const char *aEptr = aPtr + a.length();
357 while(aPtr != aEptr) {
358 if((*aPtr != *bPtr) && (dns_tolower(*aPtr) != dns_tolower(*bPtr)))
359 return false;
360 aPtr++;
361 bPtr++;
362 }
363 return true;
364 }
365
366 inline bool pdns_iequals_ch(const char a, const char b) __attribute__((pure));
367 inline bool pdns_iequals_ch(const char a, const char b)
368 {
369 if ((a != b) && (dns_tolower(a) != dns_tolower(b)))
370 return false;
371
372 return true;
373 }
374
375
376 typedef std::atomic<unsigned long> AtomicCounter ;
377
378 // FIXME400 this should probably go?
379 struct CIStringCompare: public std::binary_function<string, string, bool>
380 {
381 bool operator()(const string& a, const string& b) const
382 {
383 return pdns_ilexicographical_compare(a, b);
384 }
385 };
386
387 struct CIStringComparePOSIX
388 {
389 bool operator() (const std::string& lhs, const std::string& rhs)
390 {
391 std::string::const_iterator a,b;
392 const std::locale &loc = std::locale("POSIX");
393 a=lhs.begin();b=rhs.begin();
394 while(a!=lhs.end()) {
395 if (b==rhs.end() || std::tolower(*b,loc)<std::tolower(*a,loc)) return false;
396 else if (std::tolower(*a,loc)<std::tolower(*b,loc)) return true;
397 a++;b++;
398 }
399 return (b!=rhs.end());
400 }
401 };
402
403 struct CIStringPairCompare: public std::binary_function<pair<string, uint16_t>, pair<string,uint16_t>, bool>
404 {
405 bool operator()(const pair<string, uint16_t>& a, const pair<string, uint16_t>& b) const
406 {
407 if(pdns_ilexicographical_compare(a.first, b.first))
408 return true;
409 if(pdns_ilexicographical_compare(b.first, a.first))
410 return false;
411 return a.second < b.second;
412 }
413 };
414
415 inline size_t pdns_ci_find(const string& haystack, const string& needle)
416 {
417 string::const_iterator it = std::search(haystack.begin(), haystack.end(),
418 needle.begin(), needle.end(), pdns_iequals_ch);
419 if (it == haystack.end()) {
420 // not found
421 return string::npos;
422 } else {
423 return it - haystack.begin();
424 }
425 }
426
427 pair<string, string> splitField(const string& inp, char sepa);
428
429 inline bool isCanonical(const string& qname)
430 {
431 if(qname.empty())
432 return false;
433 return qname[qname.size()-1]=='.';
434 }
435
436 inline DNSName toCanonic(const DNSName& zone, const string& qname)
437 {
438 if(qname.size()==1 && qname[0]=='@')
439 return zone;
440 if(isCanonical(qname))
441 return DNSName(qname);
442 return DNSName(qname) += zone;
443 }
444
445 string stripDot(const string& dom);
446
447 void seedRandom(const string& source);
448 int makeIPv6sockaddr(const std::string& addr, struct sockaddr_in6* ret);
449 int makeIPv4sockaddr(const std::string& str, struct sockaddr_in* ret);
450 int makeUNsockaddr(const std::string& path, struct sockaddr_un* ret);
451 bool stringfgets(FILE* fp, std::string& line);
452
453 template<typename Index>
454 std::pair<typename Index::iterator,bool>
455 replacing_insert(Index& i,const typename Index::value_type& x)
456 {
457 std::pair<typename Index::iterator,bool> res=i.insert(x);
458 if(!res.second)res.second=i.replace(res.first,x);
459 return res;
460 }
461
462 /** very small regex wrapper */
463 class Regex
464 {
465 public:
466 /** constructor that accepts the expression to regex */
467 Regex(const string &expr);
468
469 ~Regex()
470 {
471 regfree(&d_preg);
472 }
473 /** call this to find out if 'line' matches your expression */
474 bool match(const string &line) const
475 {
476 return regexec(&d_preg,line.c_str(),0,0,0)==0;
477 }
478 bool match(const DNSName& name) const
479 {
480 return match(name.toStringNoDot());
481 }
482
483 private:
484 regex_t d_preg;
485 };
486
487 class SimpleMatch
488 {
489 public:
490 SimpleMatch(const string &mask, bool caseFold = false)
491 {
492 this->d_mask = mask;
493 this->d_fold = caseFold;
494 }
495
496 bool match(string::const_iterator mi, string::const_iterator mend, string::const_iterator vi, string::const_iterator vend)
497 {
498 for(;;mi++) {
499 if (mi == mend) {
500 return vi == vend;
501 } else if (*mi == '?') {
502 if (vi == vend) return false;
503 vi++;
504 } else if (*mi == '*') {
505 while(*mi == '*') mi++;
506 if (mi == d_mask.end()) return true;
507 while(vi != vend) {
508 if (match(mi,mend,vi,vend)) return true;
509 vi++;
510 }
511 return false;
512 } else {
513 if ((mi == mend && vi != vend)||
514 (mi != mend && vi == vend)) return false;
515 if (d_fold) {
516 if (dns_tolower(*mi) != dns_tolower(*vi)) return false;
517 } else {
518 if (*mi != *vi) return false;
519 }
520 vi++;
521 }
522 }
523 }
524
525 bool match(const string& value) {
526 return match(d_mask.begin(), d_mask.end(), value.begin(), value.end());
527 }
528
529 bool match(const DNSName& name) {
530 return match(name.toStringNoDot());
531 }
532
533 private:
534 string d_mask;
535 bool d_fold;
536 };
537
538 union ComboAddress;
539 /* itfIndex is an interface index, as returned by if_nametoindex(). 0 means default. */
540 void addCMsgSrcAddr(struct msghdr* msgh, void* cmsgbuf, const ComboAddress* source, int itfIndex);
541
542 unsigned int getFilenumLimit(bool hardOrSoft=0);
543 void setFilenumLimit(unsigned int lim);
544 bool readFileIfThere(const char* fname, std::string* line);
545 uint32_t burtle(const unsigned char* k, uint32_t lengh, uint32_t init);
546 bool setSocketTimestamps(int fd);
547
548 //! Sets the socket into blocking mode.
549 bool setBlocking( int sock );
550
551 //! Sets the socket into non-blocking mode.
552 bool setNonBlocking( int sock );
553 bool setTCPNoDelay(int sock);
554 bool isNonBlocking(int sock);
555 int closesocket(int fd);
556 bool setCloseOnExec(int sock);
557 uint64_t udpErrorStats(const std::string& str);
558
559 uint64_t getRealMemoryUsage(const std::string&);
560 uint64_t getOpenFileDescriptors(const std::string&);
561 uint64_t getCPUTimeUser(const std::string&);
562 uint64_t getCPUTimeSystem(const std::string&);
563 std::string getMACAddress(const ComboAddress& ca);
564 template<typename T, typename... Args>
565 std::unique_ptr<T> make_unique(Args&&... args)
566 {
567 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
568 }
569
570
571 template<typename T>
572 const T& defTer(const T& a, const T& b)
573 {
574 return a ? a : b;
575 }
576
577 template<typename P, typename T>
578 T valueOrEmpty(const P val) {
579 if (!val) return T{};
580 return T(val);
581 }
582
583
584 // I'm not very OCD, but I appreciate loglines like "processing 1 delta", "processing 2 deltas" :-)
585 template <typename Integer>
586 const char* addS(Integer siz, typename std::enable_if<std::is_integral<Integer>::value>::type*P=0)
587 {
588 if(!siz || siz > 1)
589 return "s";
590 else return "";
591 }
592
593 template<typename C>
594 const char* addS(const C& c, typename std::enable_if<std::is_class<C>::value>::type*P=0)
595 {
596 return addS(c.size());
597 }
598
599 template<typename C>
600 const typename C::value_type::second_type* rplookup(const C& c, const typename C::value_type::first_type& key)
601 {
602 auto fnd = c.find(key);
603 if(fnd == c.end())
604 return 0;
605 return &fnd->second;
606 }
607
608 double DiffTime(const struct timespec& first, const struct timespec& second);
609 double DiffTime(const struct timeval& first, const struct timeval& second);
610 uid_t strToUID(const string &str);
611 gid_t strToGID(const string &str);
612
613 unsigned int pdns_stou(const std::string& str, size_t * idx = 0, int base = 10);