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