]> git.ipfire.org Git - thirdparty/pdns.git/blame - pdns/iputils.hh
Merge pull request #7807 from ahupowerdns/lmdb-sync-mode
[thirdparty/pdns.git] / pdns / iputils.hh
CommitLineData
12c86877 1/*
12471842
PL
2 * This file is part of PowerDNS or dnsdist.
3 * Copyright -- PowerDNS.COM B.V. and its contributors
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of version 2 of the GNU General Public License as
7 * published by the Free Software Foundation.
8 *
9 * In addition, for the avoidance of any doubt, permission is granted to
10 * link this program with OpenSSL and to (re)distribute the binaries
11 * produced as the result of such linking.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 */
12c86877
BH
22#ifndef PDNS_IPUTILSHH
23#define PDNS_IPUTILSHH
24
25#include <string>
092f210a
BH
26#include <sys/socket.h>
27#include <netinet/in.h>
28#include <arpa/inet.h>
12c86877
BH
29#include <iostream>
30#include <stdio.h>
31#include <functional>
44845aab 32#include <bitset>
5c409fa2 33#include "pdnsexception.hh"
809fe23f 34#include "misc.hh"
506a9050
BH
35#include <sys/socket.h>
36#include <netdb.h>
335da0ba 37#include <sstream>
fd4ed0ab
BH
38#include <boost/tuple/tuple.hpp>
39#include <boost/tuple/tuple_comparison.hpp>
40
10f4eea8 41#include "namespaces.hh"
12c86877 42
323c477a
PD
43#ifdef __APPLE__
44#include <libkern/OSByteOrder.h>
45
46#define htobe16(x) OSSwapHostToBigInt16(x)
47#define htole16(x) OSSwapHostToLittleInt16(x)
48#define be16toh(x) OSSwapBigToHostInt16(x)
49#define le16toh(x) OSSwapLittleToHostInt16(x)
50
51#define htobe32(x) OSSwapHostToBigInt32(x)
52#define htole32(x) OSSwapHostToLittleInt32(x)
53#define be32toh(x) OSSwapBigToHostInt32(x)
54#define le32toh(x) OSSwapLittleToHostInt32(x)
55
56#define htobe64(x) OSSwapHostToBigInt64(x)
57#define htole64(x) OSSwapHostToLittleInt64(x)
58#define be64toh(x) OSSwapBigToHostInt64(x)
59#define le64toh(x) OSSwapLittleToHostInt64(x)
60#endif
61
28fe507d 62#ifdef __sun
b0228347
AT
63
64#define htobe16(x) BE_16(x)
65#define htole16(x) LE_16(x)
28fe507d
RD
66#define be16toh(x) BE_IN16(&(x))
67#define le16toh(x) LE_IN16(&(x))
b0228347
AT
68
69#define htobe32(x) BE_32(x)
70#define htole32(x) LE_32(x)
28fe507d
RD
71#define be32toh(x) BE_IN32(&(x))
72#define le32toh(x) LE_IN32(&(x))
b0228347
AT
73
74#define htobe64(x) BE_64(x)
75#define htole64(x) LE_64(x)
28fe507d
RD
76#define be64toh(x) BE_IN64(&(x))
77#define le64toh(x) LE_IN64(&(x))
b0228347
AT
78
79#endif
80
e95bd1ae
RK
81#ifdef __FreeBSD__
82#include <sys/endian.h>
83#endif
84
4d39d7f3
TIH
85#if defined(__NetBSD__) && defined(IP_PKTINFO) && !defined(IP_SENDSRCADDR)
86// The IP_PKTINFO option in NetBSD was incompatible with Linux until a
87// change that also introduced IP_SENDSRCADDR for FreeBSD compatibility.
88#undef IP_PKTINFO
89#endif
90
37d3f960
BH
91union ComboAddress {
92 struct sockaddr_in sin4;
93 struct sockaddr_in6 sin6;
94
fd4ed0ab
BH
95 bool operator==(const ComboAddress& rhs) const
96 {
97 if(boost::tie(sin4.sin_family, sin4.sin_port) != boost::tie(rhs.sin4.sin_family, rhs.sin4.sin_port))
98 return false;
99 if(sin4.sin_family == AF_INET)
100 return sin4.sin_addr.s_addr == rhs.sin4.sin_addr.s_addr;
101 else
a683e8bd 102 return memcmp(&sin6.sin6_addr.s6_addr, &rhs.sin6.sin6_addr.s6_addr, sizeof(sin6.sin6_addr.s6_addr))==0;
fd4ed0ab
BH
103 }
104
bb6f86bd
PL
105 bool operator!=(const ComboAddress& rhs) const
106 {
107 return(!operator==(rhs));
108 }
109
37d3f960
BH
110 bool operator<(const ComboAddress& rhs) const
111 {
f563fff4 112 if(sin4.sin_family == 0) {
113 return false;
114 }
fd4ed0ab 115 if(boost::tie(sin4.sin_family, sin4.sin_port) < boost::tie(rhs.sin4.sin_family, rhs.sin4.sin_port))
37d3f960 116 return true;
fd4ed0ab 117 if(boost::tie(sin4.sin_family, sin4.sin_port) > boost::tie(rhs.sin4.sin_family, rhs.sin4.sin_port))
37d3f960
BH
118 return false;
119
120 if(sin4.sin_family == AF_INET)
121 return sin4.sin_addr.s_addr < rhs.sin4.sin_addr.s_addr;
122 else
a683e8bd 123 return memcmp(&sin6.sin6_addr.s6_addr, &rhs.sin6.sin6_addr.s6_addr, sizeof(sin6.sin6_addr.s6_addr)) < 0;
37d3f960
BH
124 }
125
fd4ed0ab
BH
126 bool operator>(const ComboAddress& rhs) const
127 {
5f15ee47 128 return rhs.operator<(*this);
fd4ed0ab
BH
129 }
130
545725f2 131 struct addressOnlyHash
132 {
133 uint32_t operator()(const ComboAddress& ca) const
134 {
135 const unsigned char* start;
136 int len;
137 if(ca.sin4.sin_family == AF_INET) {
138 start =(const unsigned char*)&ca.sin4.sin_addr.s_addr;
139 len=4;
140 }
141 else {
142 start =(const unsigned char*)&ca.sin6.sin6_addr.s6_addr;
143 len=16;
144 }
145 return burtle(start, len, 0);
146 }
147 };
148
662d5441 149 struct addressOnlyLessThan: public std::binary_function<ComboAddress, ComboAddress, bool>
11a7242f
BH
150 {
151 bool operator()(const ComboAddress& a, const ComboAddress& b) const
152 {
153 if(a.sin4.sin_family < b.sin4.sin_family)
4957a608 154 return true;
11a7242f 155 if(a.sin4.sin_family > b.sin4.sin_family)
4957a608 156 return false;
11a7242f 157 if(a.sin4.sin_family == AF_INET)
4957a608 158 return a.sin4.sin_addr.s_addr < b.sin4.sin_addr.s_addr;
11a7242f 159 else
a683e8bd 160 return memcmp(&a.sin6.sin6_addr.s6_addr, &b.sin6.sin6_addr.s6_addr, sizeof(a.sin6.sin6_addr.s6_addr)) < 0;
11a7242f
BH
161 }
162 };
fd4ed0ab 163
0940e4eb 164 struct addressOnlyEqual: public std::binary_function<ComboAddress, ComboAddress, bool>
165 {
166 bool operator()(const ComboAddress& a, const ComboAddress& b) const
167 {
168 if(a.sin4.sin_family != b.sin4.sin_family)
169 return false;
170 if(a.sin4.sin_family == AF_INET)
171 return a.sin4.sin_addr.s_addr == b.sin4.sin_addr.s_addr;
172 else
a683e8bd 173 return !memcmp(&a.sin6.sin6_addr.s6_addr, &b.sin6.sin6_addr.s6_addr, sizeof(a.sin6.sin6_addr.s6_addr));
0940e4eb 174 }
175 };
176
177
fd4ed0ab 178 socklen_t getSocklen() const
a9af3782
BH
179 {
180 if(sin4.sin_family == AF_INET)
181 return sizeof(sin4);
182 else
183 return sizeof(sin6);
184 }
fd4ed0ab
BH
185
186 ComboAddress()
187 {
188 sin4.sin_family=AF_INET;
189 sin4.sin_addr.s_addr=0;
190 sin4.sin_port=0;
5cc8371b
RG
191 sin6.sin6_scope_id = 0;
192 sin6.sin6_flowinfo = 0;
fd4ed0ab
BH
193 }
194
a7360cd9
AT
195 ComboAddress(const struct sockaddr *sa, socklen_t salen) {
196 setSockaddr(sa, salen);
197 };
198
199 ComboAddress(const struct sockaddr_in6 *sa) {
200 setSockaddr((const struct sockaddr*)sa, sizeof(struct sockaddr_in6));
201 };
202
203 ComboAddress(const struct sockaddr_in *sa) {
204 setSockaddr((const struct sockaddr*)sa, sizeof(struct sockaddr_in));
205 };
206
207 void setSockaddr(const struct sockaddr *sa, socklen_t salen) {
208 if (salen > sizeof(struct sockaddr_in6)) throw PDNSException("ComboAddress can't handle other than sockaddr_in or sockaddr_in6");
209 memcpy(this, sa, salen);
210 }
211
85db02c5 212 // 'port' sets a default value in case 'str' does not set a port
fd4ed0ab
BH
213 explicit ComboAddress(const string& str, uint16_t port=0)
214 {
215 memset(&sin6, 0, sizeof(sin6));
216 sin4.sin_family = AF_INET;
85db02c5
BH
217 sin4.sin_port = 0;
218 if(makeIPv4sockaddr(str, &sin4)) {
fd4ed0ab 219 sin6.sin6_family = AF_INET6;
f71bc087 220 if(makeIPv6sockaddr(str, &sin6) < 0)
3f81d239 221 throw PDNSException("Unable to convert presentation address '"+ str +"'");
b03c5a46 222
fd4ed0ab 223 }
85db02c5
BH
224 if(!sin4.sin_port) // 'str' overrides port!
225 sin4.sin_port=htons(port);
fd4ed0ab 226 }
a9af3782 227
a94673ea
RG
228 bool isIPv6() const
229 {
230 return sin4.sin_family == AF_INET6;
231 }
232 bool isIPv4() const
233 {
234 return sin4.sin_family == AF_INET;
235 }
236
eb5bae86 237 bool isMappedIPv4() const
2914b022
BH
238 {
239 if(sin4.sin_family!=AF_INET6)
240 return false;
241
242 int n=0;
243 const unsigned char*ptr = (unsigned char*) &sin6.sin6_addr.s6_addr;
244 for(n=0; n < 10; ++n)
245 if(ptr[n])
4957a608 246 return false;
2914b022
BH
247
248 for(; n < 12; ++n)
249 if(ptr[n]!=0xff)
4957a608 250 return false;
2914b022
BH
251
252 return true;
253 }
254
eb5bae86 255 ComboAddress mapToIPv4() const
2914b022
BH
256 {
257 if(!isMappedIPv4())
3f81d239 258 throw PDNSException("ComboAddress can't map non-mapped IPv6 address back to IPv4");
2914b022
BH
259 ComboAddress ret;
260 ret.sin4.sin_family=AF_INET;
11a7242f 261 ret.sin4.sin_port=sin4.sin_port;
2914b022
BH
262
263 const unsigned char*ptr = (unsigned char*) &sin6.sin6_addr.s6_addr;
a683e8bd
RG
264 ptr+=(sizeof(sin6.sin6_addr.s6_addr) - sizeof(ret.sin4.sin_addr.s_addr));
265 memcpy(&ret.sin4.sin_addr.s_addr, ptr, sizeof(ret.sin4.sin_addr.s_addr));
2914b022
BH
266 return ret;
267 }
268
37d3f960
BH
269 string toString() const
270 {
506a9050 271 char host[1024];
5cc8371b 272 int retval = 0;
f4352636 273 if(sin4.sin_family && !(retval = getnameinfo((struct sockaddr*) this, getSocklen(), host, sizeof(host),0, 0, NI_NUMERICHOST)))
bfbf6814 274 return string(host);
c44d3917 275 else
f4352636 276 return "invalid "+string(gai_strerror(retval));
37d3f960 277 }
b8c3ea84
BH
278
279 string toStringWithPort() const
280 {
281 if(sin4.sin_family==AF_INET)
335da0ba 282 return toString() + ":" + std::to_string(ntohs(sin4.sin_port));
b8c3ea84 283 else
335da0ba 284 return "["+toString() + "]:" + std::to_string(ntohs(sin4.sin_port));
b8c3ea84 285 }
22779196 286
d622042f 287 string toStringWithPortExcept(int port) const
288 {
289 if(ntohs(sin4.sin_port) == port)
290 return toString();
291 if(sin4.sin_family==AF_INET)
292 return toString() + ":" + std::to_string(ntohs(sin4.sin_port));
293 else
294 return "["+toString() + "]:" + std::to_string(ntohs(sin4.sin_port));
295 }
296
9b0f144f
KM
297 string toLogString() const
298 {
299 return toStringWithPortExcept(53);
300 }
301
5b6099b2 302 void truncate(unsigned int bits) noexcept;
0affb140
RG
303
304 uint16_t getPort() const
305 {
306 return ntohs(sin4.sin_port);
307 }
308
f43e6a40
KM
309 ComboAddress setPort(uint16_t port) const
310 {
311 ComboAddress ret(*this);
312 ret.sin4.sin_port=htons(port);
313 return ret;
314 }
315
d38e2ba9
RG
316 void reset()
317 {
318 memset(&sin4, 0, sizeof(sin4));
319 memset(&sin6, 0, sizeof(sin6));
320 }
321
37d3f960
BH
322};
323
12c86877 324/** This exception is thrown by the Netmask class and by extension by the NetmaskGroup class */
3f81d239 325class NetmaskException: public PDNSException
12c86877
BH
326{
327public:
3f81d239 328 NetmaskException(const string &a) : PDNSException(a) {}
12c86877
BH
329};
330
37d3f960
BH
331inline ComboAddress makeComboAddress(const string& str)
332{
333 ComboAddress address;
334 address.sin4.sin_family=AF_INET;
1e77c17c 335 if(inet_pton(AF_INET, str.c_str(), &address.sin4.sin_addr) <= 0) {
37d3f960 336 address.sin4.sin_family=AF_INET6;
f71bc087 337 if(makeIPv6sockaddr(str, &address.sin6) < 0)
4957a608 338 throw NetmaskException("Unable to convert '"+str+"' to a netmask");
37d3f960
BH
339 }
340 return address;
341}
342
5cc8371b 343inline ComboAddress makeComboAddressFromRaw(uint8_t version, const char* raw, size_t len)
f4352636
PD
344{
345 ComboAddress address;
f4352636 346
45fab880 347 if (version == 4) {
5cc8371b
RG
348 address.sin4.sin_family = AF_INET;
349 if (len != sizeof(address.sin4.sin_addr)) throw NetmaskException("invalid raw address length");
350 memcpy(&address.sin4.sin_addr, raw, sizeof(address.sin4.sin_addr));
45fab880
PD
351 }
352 else if (version == 6) {
5cc8371b
RG
353 address.sin6.sin6_family = AF_INET6;
354 if (len != sizeof(address.sin6.sin6_addr)) throw NetmaskException("invalid raw address length");
355 memcpy(&address.sin6.sin6_addr, raw, sizeof(address.sin6.sin6_addr));
45fab880 356 }
f4352636 357 else throw NetmaskException("invalid address family");
f4352636
PD
358
359 return address;
360}
361
5cc8371b
RG
362inline ComboAddress makeComboAddressFromRaw(uint8_t version, const string &str)
363{
364 return makeComboAddressFromRaw(version, str.c_str(), str.size());
365}
366
12c86877
BH
367/** This class represents a netmask and can be queried to see if a certain
368 IP address is matched by this mask */
12c86877
BH
369class Netmask
370{
371public:
6f97329b
BH
372 Netmask()
373 {
374 d_network.sin4.sin_family=0; // disable this doing anything useful
f563fff4 375 d_network.sin4.sin_port = 0; // this guarantees d_network compares identical
2fd2d93c
AT
376 d_mask=0;
377 d_bits=0;
6f97329b
BH
378 }
379
5708a729 380 Netmask(const ComboAddress& network, uint8_t bits=0xff): d_network(network)
6f97329b 381 {
0bdabe94 382 d_network.sin4.sin_port=0;
e1c8a4bb 383 if(bits > 128)
a4c8835f
BH
384 bits = (network.sin4.sin_family == AF_INET) ? 32 : 128;
385
6f97329b
BH
386 d_bits = bits;
387 if(d_bits<32)
388 d_mask=~(0xFFFFFFFF>>d_bits);
389 else
390 d_mask=0xFFFFFFFF; // not actually used for IPv6
391 }
392
12c86877
BH
393 //! Constructor supplies the mask, which cannot be changed
394 Netmask(const string &mask)
395 {
37d3f960
BH
396 pair<string,string> split=splitField(mask,'/');
397 d_network=makeComboAddress(split.first);
398
399 if(!split.second.empty()) {
a683e8bd 400 d_bits = (uint8_t)pdns_stou(split.second);
37d3f960 401 if(d_bits<32)
4957a608 402 d_mask=~(0xFFFFFFFF>>d_bits);
8519b8a2 403 else
4957a608 404 d_mask=0xFFFFFFFF;
37d3f960
BH
405 }
406 else if(d_network.sin4.sin_family==AF_INET) {
407 d_bits = 32;
408 d_mask = 0xFFFFFFFF;
409 }
5c1def57 410 else {
37d3f960 411 d_bits=128;
5c1def57
BH
412 d_mask=0; // silence silly warning - d_mask is unused for IPv6
413 }
12c86877
BH
414 }
415
2914b022
BH
416 bool match(const ComboAddress& ip) const
417 {
418 return match(&ip);
419 }
420
12c86877 421 //! If this IP address in socket address matches
37d3f960 422 bool match(const ComboAddress *ip) const
12c86877 423 {
37d3f960
BH
424 if(d_network.sin4.sin_family != ip->sin4.sin_family) {
425 return false;
426 }
427 if(d_network.sin4.sin_family == AF_INET) {
428 return match4(htonl((unsigned int)ip->sin4.sin_addr.s_addr));
429 }
430 if(d_network.sin6.sin6_family == AF_INET6) {
431 uint8_t bytes=d_bits/8, n;
432 const uint8_t *us=(const uint8_t*) &d_network.sin6.sin6_addr.s6_addr;
433 const uint8_t *them=(const uint8_t*) &ip->sin6.sin6_addr.s6_addr;
434
435 for(n=0; n < bytes; ++n) {
4957a608
BH
436 if(us[n]!=them[n]) {
437 return false;
438 }
37d3f960
BH
439 }
440 // still here, now match remaining bits
f0739fb6 441 uint8_t bits= d_bits % 8;
a683e8bd 442 uint8_t mask= (uint8_t) ~(0xFF>>bits);
f0739fb6 443
37d3f960
BH
444 return((us[n] & mask) == (them[n] & mask));
445 }
446 return false;
12c86877
BH
447 }
448
449 //! If this ASCII IP address matches
450 bool match(const string &ip) const
451 {
37d3f960
BH
452 ComboAddress address=makeComboAddress(ip);
453 return match(&address);
12c86877
BH
454 }
455
456 //! If this IP address in native format matches
37d3f960 457 bool match4(uint32_t ip) const
12c86877 458 {
37d3f960 459 return (ip & d_mask) == (ntohl(d_network.sin4.sin_addr.s_addr) & d_mask);
12c86877
BH
460 }
461
2c95fc65
BH
462 string toString() const
463 {
335da0ba 464 return d_network.toString()+"/"+std::to_string((unsigned int)d_bits);
2c95fc65
BH
465 }
466
a4c8835f
BH
467 string toStringNoMask() const
468 {
469 return d_network.toString();
470 }
9f84a557 471 const ComboAddress& getNetwork() const
a4c8835f
BH
472 {
473 return d_network;
474 }
e1c8a4bb
RG
475 const ComboAddress getMaskedNetwork() const
476 {
477 ComboAddress result(d_network);
478 if(isIpv4()) {
479 result.sin4.sin_addr.s_addr = htonl(ntohl(result.sin4.sin_addr.s_addr) & d_mask);
480 }
481 else if(isIpv6()) {
482 size_t idx;
483 uint8_t bytes=d_bits/8;
484 uint8_t *us=(uint8_t*) &result.sin6.sin6_addr.s6_addr;
485 uint8_t bits= d_bits % 8;
486 uint8_t mask= (uint8_t) ~(0xFF>>bits);
487
488 if (bytes < sizeof(result.sin6.sin6_addr.s6_addr)) {
489 us[bytes] &= mask;
490 }
491
492 for(idx = bytes + 1; idx < sizeof(result.sin6.sin6_addr.s6_addr); ++idx) {
493 us[idx] = 0;
494 }
495 }
496 return result;
497 }
8a3a3822 498 uint8_t getBits() const
a4c8835f
BH
499 {
500 return d_bits;
501 }
709ca59f
AT
502 bool isIpv6() const
503 {
504 return d_network.sin6.sin6_family == AF_INET6;
505 }
506 bool isIpv4() const
507 {
508 return d_network.sin4.sin_family == AF_INET;
509 }
644dd1da 510
511 bool operator<(const Netmask& rhs) const
512 {
a009559d
RG
513 if (empty() && !rhs.empty())
514 return false;
515
516 if (!empty() && rhs.empty())
517 return true;
518
519 if (d_bits > rhs.d_bits)
520 return true;
521 if (d_bits < rhs.d_bits)
522 return false;
523
524 return d_network < rhs.d_network;
525 }
526
527 bool operator>(const Netmask& rhs) const
528 {
529 return rhs.operator<(*this);
644dd1da 530 }
39ec5d29 531
532 bool operator==(const Netmask& rhs) const
533 {
534 return tie(d_network, d_bits) == tie(rhs.d_network, rhs.d_bits);
535 }
536
87e665b1 537 bool empty() const
538 {
539 return d_network.sin4.sin_family==0;
540 }
541
12c86877 542private:
37d3f960 543 ComboAddress d_network;
092f210a 544 uint32_t d_mask;
37d3f960 545 uint8_t d_bits;
12c86877
BH
546};
547
44845aab
AT
548/** Per-bit binary tree map implementation with <Netmask,T> pair.
549 *
550 * This is an binary tree implementation for storing attributes for IPv4 and IPv6 prefixes.
551 * The most simple use case is simple NetmaskTree<bool> used by NetmaskGroup, which only
552 * wants to know if given IP address is matched in the prefixes stored.
553 *
554 * This element is useful for anything that needs to *STORE* prefixes, and *MATCH* IP addresses
555 * to a *LIST* of *PREFIXES*. Not the other way round.
556 *
557 * You can store IPv4 and IPv6 addresses to same tree, separate payload storage is kept per AFI.
558 *
559 * To erase something copy values to new tree sans the value you want to erase.
560 *
561 * Use swap if you need to move the tree to another NetmaskTree instance, it is WAY faster
ba07e97e 562 * than using copy ctor or assignment operator, since it moves the nodes and tree root to
44845aab
AT
563 * new home instead of actually recreating the tree.
564 *
565 * Please see NetmaskGroup for example of simple use case. Other usecases can be found
566 * from GeoIPBackend and Sortlist, and from dnsdist.
567 */
568template <typename T>
569class NetmaskTree {
570public:
571 typedef Netmask key_type;
572 typedef T value_type;
573 typedef std::pair<key_type,value_type> node_type;
574 typedef size_t size_type;
575
576private:
577 /** Single node in tree, internal use only.
578 */
579 class TreeNode : boost::noncopyable {
580 public:
581 explicit TreeNode(int bits) noexcept : parent(NULL),d_bits(bits) {
582 }
583
584 //<! Makes a left node with one more bit than parent
585 TreeNode* make_left() {
586 if (!left) {
587 left = unique_ptr<TreeNode>(new TreeNode(d_bits+1));
588 left->parent = this;
589 }
590 return left.get();
591 }
592
593 //<! Makes a right node with one more bit than parent
594 TreeNode* make_right() {
595 if (!right) {
596 right = unique_ptr<TreeNode>(new TreeNode(d_bits+1));
597 right->parent = this;
598 }
599 return right.get();
600 }
601
602 unique_ptr<TreeNode> left;
603 unique_ptr<TreeNode> right;
604 TreeNode* parent;
605
606 unique_ptr<node_type> node4; //<! IPv4 value-pair
607 unique_ptr<node_type> node6; //<! IPv6 value-pair
608
609 int d_bits; //<! How many bits have been used so far
610 };
611
612public:
11f4719b 613 NetmaskTree() noexcept : NetmaskTree(false) {
44845aab
AT
614 }
615
11f4719b
RG
616 NetmaskTree(bool cleanup) noexcept : d_cleanup_tree(cleanup) {
617 }
618
619 NetmaskTree(const NetmaskTree& rhs): d_cleanup_tree(rhs.d_cleanup_tree) {
44845aab
AT
620 // it is easier to copy the nodes than tree.
621 // also acts as handy compactor
622 for(auto const& node: rhs._nodes)
623 insert(node->first).second = node->second;
624 }
625
626 NetmaskTree& operator=(const NetmaskTree& rhs) {
627 clear();
628 // see above.
629 for(auto const& node: rhs._nodes)
630 insert(node->first).second = node->second;
5708a729 631 d_cleanup_tree = rhs.d_cleanup_tree;
44845aab
AT
632 return *this;
633 }
634
462dd712
RG
635 const typename std::set<node_type*>::const_iterator begin() const { return _nodes.begin(); }
636 const typename std::set<node_type*>::const_iterator end() const { return _nodes.end(); }
44845aab 637
462dd712
RG
638 typename std::set<node_type*>::iterator begin() { return _nodes.begin(); }
639 typename std::set<node_type*>::iterator end() { return _nodes.end(); }
44845aab
AT
640
641 node_type& insert(const string &mask) {
642 return insert(key_type(mask));
643 }
644
645 //<! Creates new value-pair in tree and returns it.
646 node_type& insert(const key_type& key) {
647 // lazily initialize tree on first insert.
648 if (!root) root = unique_ptr<TreeNode>(new TreeNode(0));
649 TreeNode* node = root.get();
650 node_type* value = nullptr;
651
652 if (key.getNetwork().sin4.sin_family == AF_INET) {
653 std::bitset<32> addr(be32toh(key.getNetwork().sin4.sin_addr.s_addr));
654 int bits = 0;
655 // we turn left on 0 and right on 1
656 while(bits < key.getBits()) {
657 uint8_t val = addr[31-bits];
658 if (val)
659 node = node->make_right();
660 else
661 node = node->make_left();
662 bits++;
663 }
664 // only create node if not yet assigned
665 if (!node->node4) {
666 node->node4 = unique_ptr<node_type>(new node_type());
462dd712 667 _nodes.insert(node->node4.get());
44845aab
AT
668 }
669 value = node->node4.get();
670 } else {
89ae2052
OM
671 uint64_t addr[2];
672 memcpy(addr, key.getNetwork().sin6.sin6_addr.s6_addr, sizeof(addr));
44845aab
AT
673 std::bitset<64> addr_low(be64toh(addr[1]));
674 std::bitset<64> addr_high(be64toh(addr[0]));
675 int bits = 0;
676 while(bits < key.getBits()) {
677 uint8_t val;
678 // we use high address until we are
679 if (bits < 64) val = addr_high[63-bits];
680 // past 64 bits, and start using low address
681 else val = addr_low[127-bits];
682
683 // we turn left on 0 and right on 1
684 if (val)
685 node = node->make_right();
686 else
687 node = node->make_left();
688 bits++;
689 }
690 // only create node if not yet assigned
691 if (!node->node6) {
692 node->node6 = unique_ptr<node_type>(new node_type());
462dd712 693 _nodes.insert(node->node6.get());
44845aab
AT
694 }
695 value = node->node6.get();
696 }
697 // assign key
698 value->first = key;
699 return *value;
700 }
701
2dfbbc41 702 //<! Creates or updates value
44845aab
AT
703 void insert_or_assign(const key_type& mask, const value_type& value) {
704 insert(mask).second = value;
705 }
706
e6419866
AT
707 void insert_or_assign(const string& mask, const value_type& value) {
708 insert(key_type(mask)).second = value;
44845aab
AT
709 }
710
41d0adb7
AT
711 //<! check if given key is present in TreeMap
712 bool has_key(const key_type& key) const {
713 const node_type *ptr = lookup(key);
714 return ptr && ptr->first == key;
715 }
716
2dfbbc41 717 //<! Returns "best match" for key_type, which might not be value
44845aab
AT
718 const node_type* lookup(const key_type& value) const {
719 return lookup(value.getNetwork(), value.getBits());
720 }
721
2dfbbc41 722 //<! Perform best match lookup for value, using at most max_bits
44845aab
AT
723 const node_type* lookup(const ComboAddress& value, int max_bits = 128) const {
724 if (!root) return nullptr;
725
726 TreeNode *node = root.get();
727 node_type *ret = nullptr;
728
729 // exact same thing as above, except
730 if (value.sin4.sin_family == AF_INET) {
731 max_bits = std::max(0,std::min(max_bits,32));
732 std::bitset<32> addr(be32toh(value.sin4.sin_addr.s_addr));
733 int bits = 0;
734
735 while(bits < max_bits) {
736 // ...we keep track of last non-empty node
737 if (node->node4) ret = node->node4.get();
738 uint8_t val = addr[31-bits];
739 // ...and we don't create left/right hand
740 if (val) {
741 if (node->right) node = node->right.get();
742 // ..and we break when road ends
743 else break;
744 } else {
745 if (node->left) node = node->left.get();
746 else break;
747 }
748 bits++;
749 }
750 // needed if we did not find one in loop
751 if (node->node4) ret = node->node4.get();
752 } else {
89ae2052
OM
753 uint64_t addr[2];
754 memcpy(addr, value.sin6.sin6_addr.s6_addr, sizeof(addr));
44845aab
AT
755 max_bits = std::max(0,std::min(max_bits,128));
756 std::bitset<64> addr_low(be64toh(addr[1]));
757 std::bitset<64> addr_high(be64toh(addr[0]));
758 int bits = 0;
759 while(bits < max_bits) {
760 if (node->node6) ret = node->node6.get();
761 uint8_t val;
762 if (bits < 64) val = addr_high[63-bits];
763 else val = addr_low[127-bits];
764 if (val) {
765 if (node->right) node = node->right.get();
766 else break;
767 } else {
768 if (node->left) node = node->left.get();
769 else break;
770 }
771 bits++;
772 }
773 if (node->node6) ret = node->node6.get();
774 }
775
776 // this can be nullptr.
777 return ret;
778 }
779
11f4719b
RG
780 void cleanup_tree(TreeNode* node)
781 {
782 // only cleanup this node if it has no children and node4 and node6 are both empty
783 if (!(node->left || node->right || node->node6 || node->node4)) {
784 // get parent node ptr
785 TreeNode* parent = node->parent;
786 // delete this node
787 if (parent) {
788 if (parent->left.get() == node)
789 parent->left.reset();
790 else
791 parent->right.reset();
792 // now recurse up to the parent
793 cleanup_tree(parent);
794 }
795 }
796 }
797
2dfbbc41 798 //<! Removes key from TreeMap. This does not clean up the tree.
44845aab
AT
799 void erase(const key_type& key) {
800 TreeNode *node = root.get();
801
802 // no tree, no value
803 if ( node == nullptr ) return;
804
805 // exact same thing as above, except
806 if (key.getNetwork().sin4.sin_family == AF_INET) {
807 std::bitset<32> addr(be32toh(key.getNetwork().sin4.sin_addr.s_addr));
808 int bits = 0;
809 while(node && bits < key.getBits()) {
810 uint8_t val = addr[31-bits];
811 if (val) {
812 node = node->right.get();
813 } else {
814 node = node->left.get();
815 }
816 bits++;
817 }
818 if (node) {
462dd712 819 _nodes.erase(node->node4.get());
44845aab 820 node->node4.reset();
11f4719b
RG
821
822 if (d_cleanup_tree)
823 cleanup_tree(node);
44845aab
AT
824 }
825 } else {
89ae2052
OM
826 uint64_t addr[2];
827 memcpy(addr, key.getNetwork().sin6.sin6_addr.s6_addr, sizeof(addr));
44845aab
AT
828 std::bitset<64> addr_low(be64toh(addr[1]));
829 std::bitset<64> addr_high(be64toh(addr[0]));
830 int bits = 0;
831 while(node && bits < key.getBits()) {
832 uint8_t val;
833 if (bits < 64) val = addr_high[63-bits];
834 else val = addr_low[127-bits];
835 if (val) {
836 node = node->right.get();
837 } else {
838 node = node->left.get();
839 }
840 bits++;
841 }
842 if (node) {
462dd712 843 _nodes.erase(node->node6.get());
44845aab 844 node->node6.reset();
11f4719b
RG
845
846 if (d_cleanup_tree)
847 cleanup_tree(node);
44845aab
AT
848 }
849 }
850 }
851
852 void erase(const string& key) {
853 erase(key_type(key));
854 }
855
856 //<! checks whether the container is empty.
857 bool empty() const {
858 return _nodes.empty();
859 }
860
861 //<! returns the number of elements
862 size_type size() const {
863 return _nodes.size();
864 }
865
866 //<! See if given ComboAddress matches any prefix
867 bool match(const ComboAddress& value) const {
868 return (lookup(value) != nullptr);
869 }
870
871 bool match(const std::string& value) const {
872 return match(ComboAddress(value));
873 }
874
875 //<! Clean out the tree
876 void clear() {
877 _nodes.clear();
878 root.reset(nullptr);
879 }
880
881 //<! swaps the contents, rhs is left with nullptr.
882 void swap(NetmaskTree& rhs) {
883 root.swap(rhs.root);
884 _nodes.swap(rhs._nodes);
885 }
886
887private:
888 unique_ptr<TreeNode> root; //<! Root of our tree
462dd712 889 std::set<node_type*> _nodes; //<! Container for actual values
11f4719b 890 bool d_cleanup_tree; //<! Whether or not to cleanup the tree on erase
44845aab
AT
891};
892
12c86877
BH
893/** This class represents a group of supplemental Netmask classes. An IP address matchs
894 if it is matched by zero or more of the Netmask classes within.
895*/
896class NetmaskGroup
897{
898public:
11f4719b
RG
899 //! By default, initialise the tree to cleanup
900 NetmaskGroup() noexcept : NetmaskGroup(true) {
901 }
902
903 //! This allows control over whether to cleanup or not
904 NetmaskGroup(bool cleanup) noexcept : tree(cleanup) {
905 }
906
12c86877 907 //! If this IP address is matched by any of the classes within
60af67b8 908
1e77c17c 909 bool match(const ComboAddress *ip) const
12c86877 910 {
ee15a1e1
PD
911 const auto &ret = tree.lookup(*ip);
912 if(ret) return ret->second;
913 return false;
12c86877 914 }
60af67b8 915
1e77c17c 916 bool match(const ComboAddress& ip) const
60af67b8 917 {
918 return match(&ip);
919 }
920
11f4719b
RG
921 bool lookup(const ComboAddress* ip, Netmask* nmp) const
922 {
923 const auto &ret = tree.lookup(*ip);
924 if (ret) {
925 if (nmp != nullptr)
926 *nmp = ret->first;
927
928 return ret->second;
929 }
930 return false;
931 }
932
933 bool lookup(const ComboAddress& ip, Netmask* nmp) const
934 {
935 return lookup(&ip, nmp);
936 }
937
376effcf 938 //! Add this string to the list of possible matches
ee15a1e1 939 void addMask(const string &ip, bool positive=true)
12c86877 940 {
ee15a1e1
PD
941 if(!ip.empty() && ip[0] == '!') {
942 addMask(Netmask(ip.substr(1)), false);
943 } else {
944 addMask(Netmask(ip), positive);
945 }
12c86877 946 }
68b011bd 947
376effcf 948 //! Add this Netmask to the list of possible matches
ee15a1e1 949 void addMask(const Netmask& nm, bool positive=true)
376effcf 950 {
ee15a1e1 951 tree.insert(nm).second=positive;
376effcf 952 }
953
11f4719b
RG
954 //! Delete this Netmask from the list of possible matches
955 void deleteMask(const Netmask& nm)
956 {
957 tree.erase(nm);
958 }
959
960 void deleteMask(const std::string& ip)
961 {
962 if (!ip.empty())
963 deleteMask(Netmask(ip));
964 }
965
68b011bd
KM
966 void clear()
967 {
5ac553e1 968 tree.clear();
68b011bd
KM
969 }
970
5ac553e1 971 bool empty() const
12c86877 972 {
5ac553e1 973 return tree.empty();
12c86877
BH
974 }
975
5ac553e1 976 size_t size() const
2c95fc65 977 {
5ac553e1 978 return tree.size();
2c95fc65
BH
979 }
980
981 string toString() const
982 {
983 ostringstream str;
5ac553e1
AT
984 for(auto iter = tree.begin(); iter != tree.end(); ++iter) {
985 if(iter != tree.begin())
4957a608 986 str <<", ";
ee15a1e1
PD
987 if(!((*iter)->second))
988 str<<"!";
5ac553e1 989 str<<(*iter)->first.toString();
2c95fc65
BH
990 }
991 return str.str();
992 }
993
41942bb3
CH
994 void toStringVector(vector<string>* vec) const
995 {
ee15a1e1
PD
996 for(auto iter = tree.begin(); iter != tree.end(); ++iter) {
997 vec->push_back(((*iter)->second ? "" : "!") + (*iter)->first.toString());
998 }
41942bb3
CH
999 }
1000
68b011bd
KM
1001 void toMasks(const string &ips)
1002 {
1003 vector<string> parts;
1004 stringtok(parts, ips, ", \t");
1005
1006 for (vector<string>::const_iterator iter = parts.begin(); iter != parts.end(); ++iter)
1007 addMask(*iter);
1008 }
1009
12c86877 1010private:
5ac553e1 1011 NetmaskTree<bool> tree;
12c86877
BH
1012};
1013
002c970a 1014
60c8afa8 1015struct SComboAddress
1016{
1017 SComboAddress(const ComboAddress& orig) : ca(orig) {}
1018 ComboAddress ca;
1019 bool operator<(const SComboAddress& rhs) const
1020 {
1021 return ComboAddress::addressOnlyLessThan()(ca, rhs.ca);
1022 }
1023 operator const ComboAddress&()
1024 {
1025 return ca;
1026 }
1027};
1028
73ba5999
CHB
1029class NetworkError : public runtime_error
1030{
1031public:
1032 NetworkError(const string& why="Network Error") : runtime_error(why.c_str())
1033 {}
1034 NetworkError(const char *why="Network Error") : runtime_error(why)
1035 {}
1036};
60c8afa8 1037
002c970a 1038int SSocket(int family, int type, int flags);
1039int SConnect(int sockfd, const ComboAddress& remote);
51959320
RG
1040/* tries to connect to remote for a maximum of timeout seconds.
1041 sockfd should be set to non-blocking beforehand.
1042 returns 0 on success (the socket is writable), throw a
1043 runtime_error otherwise */
1044int SConnectWithTimeout(int sockfd, const ComboAddress& remote, int timeout);
002c970a 1045int SBind(int sockfd, const ComboAddress& local);
1046int SAccept(int sockfd, ComboAddress& remote);
1047int SListen(int sockfd, int limit);
1048int SSetsockopt(int sockfd, int level, int opname, int value);
90f9fbc0 1049void setSocketIgnorePMTU(int sockfd);
002c970a 1050
3e3f0358 1051#if defined(IP_PKTINFO)
1052 #define GEN_IP_PKTINFO IP_PKTINFO
1053#elif defined(IP_RECVDSTADDR)
1054 #define GEN_IP_PKTINFO IP_RECVDSTADDR
1055#endif
4d39d7f3 1056
3e3f0358 1057bool IsAnyAddress(const ComboAddress& addr);
2b3eefc3 1058bool HarvestDestinationAddress(const struct msghdr* msgh, ComboAddress* destination);
3e3f0358 1059bool HarvestTimestamp(struct msghdr* msgh, struct timeval* tv);
b71b60ee 1060void fillMSGHdr(struct msghdr* msgh, struct iovec* iov, char* cbuf, size_t cbufsize, char* data, size_t datalen, ComboAddress* addr);
a683e8bd 1061ssize_t sendfromto(int sock, const char* data, size_t len, int flags, const ComboAddress& from, const ComboAddress& to);
6714b6ac
RG
1062size_t sendMsgWithOptions(int fd, const char* buffer, size_t len, const ComboAddress* dest, const ComboAddress* local, unsigned int localItf, int flags);
1063
840ed663
RG
1064/* requires a non-blocking, connected TCP socket */
1065bool isTCPSocketUsable(int sock);
f9f9592e
AT
1066
1067extern template class NetmaskTree<bool>;
17bca36a
RG
1068
1069#endif