You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1596 lines
38 KiB

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