/
iputils.hh
1906 lines (1678 loc) · 51.1 KB
/
iputils.hh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of PowerDNS or dnsdist.
* Copyright -- PowerDNS.COM B.V. and its contributors
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* In addition, for the avoidance of any doubt, permission is granted to
* link this program with OpenSSL and to (re)distribute the binaries
* produced as the result of such linking.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include <string>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
#include <cstdio>
#include <functional>
#include <bitset>
#include "pdnsexception.hh"
#include "misc.hh"
#include <netdb.h>
#include <sstream>
#include "namespaces.hh"
#ifdef __APPLE__
#include <libkern/OSByteOrder.h>
#define htobe16(x) OSSwapHostToBigInt16(x)
#define htole16(x) OSSwapHostToLittleInt16(x)
#define be16toh(x) OSSwapBigToHostInt16(x)
#define le16toh(x) OSSwapLittleToHostInt16(x)
#define htobe32(x) OSSwapHostToBigInt32(x)
#define htole32(x) OSSwapHostToLittleInt32(x)
#define be32toh(x) OSSwapBigToHostInt32(x)
#define le32toh(x) OSSwapLittleToHostInt32(x)
#define htobe64(x) OSSwapHostToBigInt64(x)
#define htole64(x) OSSwapHostToLittleInt64(x)
#define be64toh(x) OSSwapBigToHostInt64(x)
#define le64toh(x) OSSwapLittleToHostInt64(x)
#endif
#ifdef __sun
#define htobe16(x) BE_16(x)
#define htole16(x) LE_16(x)
#define be16toh(x) BE_IN16(&(x))
#define le16toh(x) LE_IN16(&(x))
#define htobe32(x) BE_32(x)
#define htole32(x) LE_32(x)
#define be32toh(x) BE_IN32(&(x))
#define le32toh(x) LE_IN32(&(x))
#define htobe64(x) BE_64(x)
#define htole64(x) LE_64(x)
#define be64toh(x) BE_IN64(&(x))
#define le64toh(x) LE_IN64(&(x))
#endif
#ifdef __FreeBSD__
#include <sys/endian.h>
#endif
#if defined(__NetBSD__) && defined(IP_PKTINFO) && !defined(IP_SENDSRCADDR)
// The IP_PKTINFO option in NetBSD was incompatible with Linux until a
// change that also introduced IP_SENDSRCADDR for FreeBSD compatibility.
#undef IP_PKTINFO
#endif
union ComboAddress
{
sockaddr_in sin4{};
sockaddr_in6 sin6;
bool operator==(const ComboAddress& rhs) const
{
if (std::tie(sin4.sin_family, sin4.sin_port) != std::tie(rhs.sin4.sin_family, rhs.sin4.sin_port)) {
return false;
}
if (sin4.sin_family == AF_INET) {
return sin4.sin_addr.s_addr == rhs.sin4.sin_addr.s_addr;
}
return memcmp(&sin6.sin6_addr.s6_addr, &rhs.sin6.sin6_addr.s6_addr, sizeof(sin6.sin6_addr.s6_addr)) == 0;
}
bool operator!=(const ComboAddress& rhs) const
{
return (!operator==(rhs));
}
bool operator<(const ComboAddress& rhs) const
{
if (sin4.sin_family == 0) {
return false;
}
if (std::tie(sin4.sin_family, sin4.sin_port) < std::tie(rhs.sin4.sin_family, rhs.sin4.sin_port)) {
return true;
}
if (std::tie(sin4.sin_family, sin4.sin_port) > std::tie(rhs.sin4.sin_family, rhs.sin4.sin_port)) {
return false;
}
if (sin4.sin_family == AF_INET) {
return sin4.sin_addr.s_addr < rhs.sin4.sin_addr.s_addr;
}
return memcmp(&sin6.sin6_addr.s6_addr, &rhs.sin6.sin6_addr.s6_addr, sizeof(sin6.sin6_addr.s6_addr)) < 0;
}
bool operator>(const ComboAddress& rhs) const
{
return rhs.operator<(*this);
}
struct addressPortOnlyHash
{
uint32_t operator()(const ComboAddress& address) const
{
// NOLINTBEGIN(cppcoreguidelines-pro-type-reinterpret-cast)
if (address.sin4.sin_family == AF_INET) {
const auto* start = reinterpret_cast<const unsigned char*>(&address.sin4.sin_addr.s_addr);
auto tmp = burtle(start, 4, 0);
return burtle(reinterpret_cast<const uint8_t*>(&address.sin4.sin_port), 2, tmp);
}
const auto* start = reinterpret_cast<const unsigned char*>(&address.sin6.sin6_addr.s6_addr);
auto tmp = burtle(start, 16, 0);
return burtle(reinterpret_cast<const unsigned char*>(&address.sin6.sin6_port), 2, tmp);
// NOLINTEND(cppcoreguidelines-pro-type-reinterpret-cast)
}
};
struct addressOnlyHash
{
uint32_t operator()(const ComboAddress& address) const
{
const unsigned char* start = nullptr;
uint32_t len = 0;
// NOLINTBEGIN(cppcoreguidelines-pro-type-reinterpret-cast)
if (address.sin4.sin_family == AF_INET) {
start = reinterpret_cast<const unsigned char*>(&address.sin4.sin_addr.s_addr);
len = 4;
}
else {
start = reinterpret_cast<const unsigned char*>(&address.sin6.sin6_addr.s6_addr);
len = 16;
}
// NOLINTEND(cppcoreguidelines-pro-type-reinterpret-cast)
return burtle(start, len, 0);
}
};
struct addressOnlyLessThan
{
bool operator()(const ComboAddress& lhs, const ComboAddress& rhs) const
{
if (lhs.sin4.sin_family < rhs.sin4.sin_family) {
return true;
}
if (lhs.sin4.sin_family > rhs.sin4.sin_family) {
return false;
}
if (lhs.sin4.sin_family == AF_INET) {
return lhs.sin4.sin_addr.s_addr < rhs.sin4.sin_addr.s_addr;
}
return memcmp(&lhs.sin6.sin6_addr.s6_addr, &rhs.sin6.sin6_addr.s6_addr, sizeof(lhs.sin6.sin6_addr.s6_addr)) < 0;
}
};
struct addressOnlyEqual
{
bool operator()(const ComboAddress& lhs, const ComboAddress& rhs) const
{
if (lhs.sin4.sin_family != rhs.sin4.sin_family) {
return false;
}
if (lhs.sin4.sin_family == AF_INET) {
return lhs.sin4.sin_addr.s_addr == rhs.sin4.sin_addr.s_addr;
}
return memcmp(&lhs.sin6.sin6_addr.s6_addr, &rhs.sin6.sin6_addr.s6_addr, sizeof(lhs.sin6.sin6_addr.s6_addr)) == 0;
}
};
[[nodiscard]] socklen_t getSocklen() const
{
if (sin4.sin_family == AF_INET) {
return sizeof(sin4);
}
return sizeof(sin6);
}
ComboAddress()
{
sin4.sin_family = AF_INET;
sin4.sin_addr.s_addr = 0;
sin4.sin_port = 0;
sin6.sin6_scope_id = 0;
sin6.sin6_flowinfo = 0;
}
ComboAddress(const struct sockaddr* socketAddress, socklen_t salen)
{
setSockaddr(socketAddress, salen);
};
ComboAddress(const struct sockaddr_in6* socketAddress)
{
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
setSockaddr(reinterpret_cast<const struct sockaddr*>(socketAddress), sizeof(struct sockaddr_in6));
};
ComboAddress(const struct sockaddr_in* socketAddress)
{
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
setSockaddr(reinterpret_cast<const struct sockaddr*>(socketAddress), sizeof(struct sockaddr_in));
};
void setSockaddr(const struct sockaddr* socketAddress, socklen_t salen)
{
if (salen > sizeof(struct sockaddr_in6)) {
throw PDNSException("ComboAddress can't handle other than sockaddr_in or sockaddr_in6");
}
memcpy(this, socketAddress, salen);
}
// 'port' sets a default value in case 'str' does not set a port
explicit ComboAddress(const string& str, uint16_t port = 0)
{
memset(&sin6, 0, sizeof(sin6));
sin4.sin_family = AF_INET;
sin4.sin_port = 0;
if (makeIPv4sockaddr(str, &sin4) != 0) {
sin6.sin6_family = AF_INET6;
if (makeIPv6sockaddr(str, &sin6) < 0) {
throw PDNSException("Unable to convert presentation address '" + str + "'");
}
}
if (sin4.sin_port == 0) { // 'str' overrides port!
sin4.sin_port = htons(port);
}
}
[[nodiscard]] bool isIPv6() const
{
return sin4.sin_family == AF_INET6;
}
[[nodiscard]] bool isIPv4() const
{
return sin4.sin_family == AF_INET;
}
[[nodiscard]] bool isMappedIPv4() const
{
if (sin4.sin_family != AF_INET6) {
return false;
}
int iter = 0;
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
const auto* ptr = reinterpret_cast<const unsigned char*>(&sin6.sin6_addr.s6_addr);
for (iter = 0; iter < 10; ++iter) {
if (ptr[iter] != 0) { // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
return false;
}
}
for (; iter < 12; ++iter) {
if (ptr[iter] != 0xff) { // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
return false;
}
}
return true;
}
[[nodiscard]] ComboAddress mapToIPv4() const
{
if (!isMappedIPv4()) {
throw PDNSException("ComboAddress can't map non-mapped IPv6 address back to IPv4");
}
ComboAddress ret;
ret.sin4.sin_family = AF_INET;
ret.sin4.sin_port = sin4.sin_port;
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
const auto* ptr = reinterpret_cast<const unsigned char*>(&sin6.sin6_addr.s6_addr);
ptr += (sizeof(sin6.sin6_addr.s6_addr) - sizeof(ret.sin4.sin_addr.s_addr)); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
memcpy(&ret.sin4.sin_addr.s_addr, ptr, sizeof(ret.sin4.sin_addr.s_addr));
return ret;
}
[[nodiscard]] string toString() const
{
std::array<char, 1024> host{};
if (sin4.sin_family != 0) {
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
int retval = getnameinfo(reinterpret_cast<const struct sockaddr*>(this), getSocklen(), host.data(), host.size(), nullptr, 0, NI_NUMERICHOST);
if (retval == 0) {
return host.data();
}
return "invalid " + string(gai_strerror(retval));
}
return "invalid";
}
//! Ignores any interface specifiers possibly available in the sockaddr data.
[[nodiscard]] string toStringNoInterface() const
{
std::array<char, 1024> host{};
if (sin4.sin_family == AF_INET) {
const auto* ret = inet_ntop(sin4.sin_family, &sin4.sin_addr, host.data(), host.size());
if (ret != nullptr) {
return host.data();
}
}
else if (sin4.sin_family == AF_INET6) {
const auto* ret = inet_ntop(sin4.sin_family, &sin6.sin6_addr, host.data(), host.size());
if (ret != nullptr) {
return host.data();
}
}
return "invalid " + stringerror();
}
[[nodiscard]] string toStringReversed() const
{
if (isIPv4()) {
const auto address = ntohl(sin4.sin_addr.s_addr);
auto aaa = (address >> 0) & 0xFF;
auto bbb = (address >> 8) & 0xFF;
auto ccc = (address >> 16) & 0xFF;
auto ddd = (address >> 24) & 0xFF;
return std::to_string(aaa) + "." + std::to_string(bbb) + "." + std::to_string(ccc) + "." + std::to_string(ddd);
}
const auto* addr = &sin6.sin6_addr;
std::stringstream res{};
res << std::hex;
for (int i = 15; i >= 0; i--) {
auto byte = addr->s6_addr[i]; // NOLINT(cppcoreguidelines-pro-bounds-constant-array-index)
res << ((byte >> 0) & 0xF) << ".";
res << ((byte >> 4) & 0xF);
if (i != 0) {
res << ".";
}
}
return res.str();
}
[[nodiscard]] string toStringWithPort() const
{
if (sin4.sin_family == AF_INET) {
return toString() + ":" + std::to_string(ntohs(sin4.sin_port));
}
return "[" + toString() + "]:" + std::to_string(ntohs(sin4.sin_port));
}
[[nodiscard]] string toStringWithPortExcept(int port) const
{
if (ntohs(sin4.sin_port) == port) {
return toString();
}
if (sin4.sin_family == AF_INET) {
return toString() + ":" + std::to_string(ntohs(sin4.sin_port));
}
return "[" + toString() + "]:" + std::to_string(ntohs(sin4.sin_port));
}
[[nodiscard]] string toLogString() const
{
return toStringWithPortExcept(53);
}
[[nodiscard]] string toStructuredLogString() const
{
return toStringWithPort();
}
[[nodiscard]] string toByteString() const
{
// NOLINTBEGIN(cppcoreguidelines-pro-type-reinterpret-cast)
if (isIPv4()) {
return {reinterpret_cast<const char*>(&sin4.sin_addr.s_addr), sizeof(sin4.sin_addr.s_addr)};
}
return {reinterpret_cast<const char*>(&sin6.sin6_addr.s6_addr), sizeof(sin6.sin6_addr.s6_addr)};
// NOLINTEND(cppcoreguidelines-pro-type-reinterpret-cast)
}
void truncate(unsigned int bits) noexcept;
[[nodiscard]] uint16_t getNetworkOrderPort() const noexcept
{
return sin4.sin_port;
}
[[nodiscard]] uint16_t getPort() const noexcept
{
return ntohs(getNetworkOrderPort());
}
void setPort(uint16_t port)
{
sin4.sin_port = htons(port);
}
void reset()
{
memset(&sin4, 0, sizeof(sin4));
memset(&sin6, 0, sizeof(sin6));
}
//! Get the total number of address bits (either 32 or 128 depending on IP version)
[[nodiscard]] uint8_t getBits() const
{
if (isIPv4()) {
return 32;
}
if (isIPv6()) {
return 128;
}
return 0;
}
/** Get the value of the bit at the provided bit index. When the index >= 0,
the index is relative to the LSB starting at index zero. When the index < 0,
the index is relative to the MSB starting at index -1 and counting down.
*/
[[nodiscard]] bool getBit(int index) const
{
if (isIPv4()) {
if (index >= 32) {
return false;
}
if (index < 0) {
if (index < -32) {
return false;
}
index = 32 + index;
}
uint32_t ls_addr = ntohl(sin4.sin_addr.s_addr);
return ((ls_addr & (1U << index)) != 0x00000000);
}
if (isIPv6()) {
if (index >= 128) {
return false;
}
if (index < 0) {
if (index < -128) {
return false;
}
index = 128 + index;
}
const auto* ls_addr = reinterpret_cast<const uint8_t*>(sin6.sin6_addr.s6_addr); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
uint8_t byte_idx = index / 8;
uint8_t bit_idx = index % 8;
return ((ls_addr[15 - byte_idx] & (1U << bit_idx)) != 0x00); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
}
return false;
}
/*! Returns a comma-separated string of IP addresses
*
* \param c An stl container with ComboAddresses
* \param withPort Also print the port (default true)
* \param portExcept Print the port, except when this is the port (default 53)
*/
template <template <class...> class Container, class... Args>
static string caContainerToString(const Container<ComboAddress, Args...>& container, const bool withPort = true, const uint16_t portExcept = 53)
{
vector<string> strs;
for (const auto& address : container) {
if (withPort) {
strs.push_back(address.toStringWithPortExcept(portExcept));
continue;
}
strs.push_back(address.toString());
}
return boost::join(strs, ",");
};
};
/** This exception is thrown by the Netmask class and by extension by the NetmaskGroup class */
class NetmaskException : public PDNSException
{
public:
NetmaskException(const string& arg) :
PDNSException(arg) {}
};
inline ComboAddress makeComboAddress(const string& str)
{
ComboAddress address;
address.sin4.sin_family = AF_INET;
if (inet_pton(AF_INET, str.c_str(), &address.sin4.sin_addr) <= 0) {
address.sin4.sin_family = AF_INET6;
if (makeIPv6sockaddr(str, &address.sin6) < 0) {
throw NetmaskException("Unable to convert '" + str + "' to a netmask");
}
}
return address;
}
inline ComboAddress makeComboAddressFromRaw(uint8_t version, const char* raw, size_t len)
{
ComboAddress address;
if (version == 4) {
address.sin4.sin_family = AF_INET;
if (len != sizeof(address.sin4.sin_addr)) {
throw NetmaskException("invalid raw address length");
}
memcpy(&address.sin4.sin_addr, raw, sizeof(address.sin4.sin_addr));
}
else if (version == 6) {
address.sin6.sin6_family = AF_INET6;
if (len != sizeof(address.sin6.sin6_addr)) {
throw NetmaskException("invalid raw address length");
}
memcpy(&address.sin6.sin6_addr, raw, sizeof(address.sin6.sin6_addr));
}
else {
throw NetmaskException("invalid address family");
}
return address;
}
inline ComboAddress makeComboAddressFromRaw(uint8_t version, const string& str)
{
return makeComboAddressFromRaw(version, str.c_str(), str.size());
}
/** This class represents a netmask and can be queried to see if a certain
IP address is matched by this mask */
class Netmask
{
public:
Netmask()
{
d_network.sin4.sin_family = 0; // disable this doing anything useful
d_network.sin4.sin_port = 0; // this guarantees d_network compares identical
}
Netmask(const ComboAddress& network, uint8_t bits = 0xff) :
d_network(network)
{
d_network.sin4.sin_port = 0;
setBits(bits);
}
Netmask(const sockaddr_in* network, uint8_t bits = 0xff) :
d_network(network)
{
d_network.sin4.sin_port = 0;
setBits(bits);
}
Netmask(const sockaddr_in6* network, uint8_t bits = 0xff) :
d_network(network)
{
d_network.sin4.sin_port = 0;
setBits(bits);
}
void setBits(uint8_t value)
{
d_bits = d_network.isIPv4() ? std::min(value, static_cast<uint8_t>(32U)) : std::min(value, static_cast<uint8_t>(128U));
if (d_bits < 32) {
d_mask = ~(0xFFFFFFFF >> d_bits);
}
else {
// note that d_mask is unused for IPv6
d_mask = 0xFFFFFFFF;
}
if (isIPv4()) {
d_network.sin4.sin_addr.s_addr = htonl(ntohl(d_network.sin4.sin_addr.s_addr) & d_mask);
}
else if (isIPv6()) {
uint8_t bytes = d_bits / 8;
auto* address = reinterpret_cast<uint8_t*>(&d_network.sin6.sin6_addr.s6_addr); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
uint8_t bits = d_bits % 8;
auto mask = static_cast<uint8_t>(~(0xFF >> bits));
if (bytes < sizeof(d_network.sin6.sin6_addr.s6_addr)) {
address[bytes] &= mask; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
}
for (size_t idx = bytes + 1; idx < sizeof(d_network.sin6.sin6_addr.s6_addr); ++idx) {
address[idx] = 0; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
}
}
}
//! Constructor supplies the mask, which cannot be changed
Netmask(const string& mask)
{
pair<string, string> split = splitField(mask, '/');
d_network = makeComboAddress(split.first);
if (!split.second.empty()) {
setBits(pdns::checked_stoi<uint8_t>(split.second));
}
else if (d_network.sin4.sin_family == AF_INET) {
setBits(32);
}
else {
setBits(128);
}
}
[[nodiscard]] bool match(const ComboAddress& address) const
{
return match(&address);
}
//! If this IP address in socket address matches
bool match(const ComboAddress* address) const
{
if (d_network.sin4.sin_family != address->sin4.sin_family) {
return false;
}
if (d_network.sin4.sin_family == AF_INET) {
return match4(htonl((unsigned int)address->sin4.sin_addr.s_addr));
}
if (d_network.sin6.sin6_family == AF_INET6) {
uint8_t bytes = d_bits / 8;
uint8_t index = 0;
// NOLINTBEGIN(cppcoreguidelines-pro-type-reinterpret-cast)
const auto* lhs = reinterpret_cast<const uint8_t*>(&d_network.sin6.sin6_addr.s6_addr);
const auto* rhs = reinterpret_cast<const uint8_t*>(&address->sin6.sin6_addr.s6_addr);
// NOLINTEND(cppcoreguidelines-pro-type-reinterpret-cast)
// NOLINTBEGIN(cppcoreguidelines-pro-bounds-pointer-arithmetic)
for (index = 0; index < bytes; ++index) {
if (lhs[index] != rhs[index]) {
return false;
}
}
// still here, now match remaining bits
uint8_t bits = d_bits % 8;
auto mask = static_cast<uint8_t>(~(0xFF >> bits));
return ((lhs[index]) == (rhs[index] & mask));
// NOLINTEND(cppcoreguidelines-pro-bounds-pointer-arithmetic)
}
return false;
}
//! If this ASCII IP address matches
[[nodiscard]] bool match(const string& arg) const
{
ComboAddress address = makeComboAddress(arg);
return match(&address);
}
//! If this IP address in native format matches
[[nodiscard]] bool match4(uint32_t arg) const
{
return (arg & d_mask) == (ntohl(d_network.sin4.sin_addr.s_addr));
}
[[nodiscard]] string toString() const
{
return d_network.toStringNoInterface() + "/" + std::to_string((unsigned int)d_bits);
}
[[nodiscard]] string toStringNoMask() const
{
return d_network.toStringNoInterface();
}
[[nodiscard]] const ComboAddress& getNetwork() const
{
return d_network;
}
[[nodiscard]] const ComboAddress& getMaskedNetwork() const
{
return getNetwork();
}
[[nodiscard]] uint8_t getBits() const
{
return d_bits;
}
[[nodiscard]] bool isIPv6() const
{
return d_network.sin6.sin6_family == AF_INET6;
}
[[nodiscard]] bool isIPv4() const
{
return d_network.sin4.sin_family == AF_INET;
}
bool operator<(const Netmask& rhs) const
{
if (empty() && !rhs.empty()) {
return false;
}
if (!empty() && rhs.empty()) {
return true;
}
if (d_bits > rhs.d_bits) {
return true;
}
if (d_bits < rhs.d_bits) {
return false;
}
return d_network < rhs.d_network;
}
bool operator>(const Netmask& rhs) const
{
return rhs.operator<(*this);
}
bool operator==(const Netmask& rhs) const
{
return std::tie(d_network, d_bits) == std::tie(rhs.d_network, rhs.d_bits);
}
[[nodiscard]] bool empty() const
{
return d_network.sin4.sin_family == 0;
}
//! Get normalized version of the netmask. This means that all address bits below the network bits are zero.
[[nodiscard]] Netmask getNormalized() const
{
return {getMaskedNetwork(), d_bits};
}
//! Get Netmask for super network of this one (i.e. with fewer network bits)
[[nodiscard]] Netmask getSuper(uint8_t bits) const
{
return {d_network, std::min(d_bits, bits)};
}
//! Get the total number of address bits for this netmask (either 32 or 128 depending on IP version)
[[nodiscard]] uint8_t getFullBits() const
{
return d_network.getBits();
}
/** Get the value of the bit at the provided bit index. When the index >= 0,
the index is relative to the LSB starting at index zero. When the index < 0,
the index is relative to the MSB starting at index -1 and counting down.
When the index points outside the network bits, it always yields zero.
*/
[[nodiscard]] bool getBit(int bit) const
{
if (bit < -d_bits) {
return false;
}
if (bit >= 0) {
if (isIPv4()) {
if (bit >= 32 || bit < (32 - d_bits)) {
return false;
}
}
if (isIPv6()) {
if (bit >= 128 || bit < (128 - d_bits)) {
return false;
}
}
}
return d_network.getBit(bit);
}
struct Hash
{
size_t operator()(const Netmask& netmask) const
{
return burtle(&netmask.d_bits, 1, ComboAddress::addressOnlyHash()(netmask.d_network));
}
};
private:
ComboAddress d_network;
uint32_t d_mask{0};
uint8_t d_bits{0};
};
namespace std
{
template <>
struct hash<Netmask>
{
auto operator()(const Netmask& netmask) const
{
return Netmask::Hash{}(netmask);
}
};
}
/** Binary tree map implementation with <Netmask,T> pair.
*
* This is an binary tree implementation for storing attributes for IPv4 and IPv6 prefixes.
* The most simple use case is simple NetmaskTree<bool> used by NetmaskGroup, which only
* wants to know if given IP address is matched in the prefixes stored.
*
* This element is useful for anything that needs to *STORE* prefixes, and *MATCH* IP addresses
* to a *LIST* of *PREFIXES*. Not the other way round.
*
* You can store IPv4 and IPv6 addresses to same tree, separate payload storage is kept per AFI.
* Network prefixes (Netmasks) are always recorded in normalized fashion, meaning that only
* the network bits are set. This is what is returned in the insert() and lookup() return
* values.
*
* Use swap if you need to move the tree to another NetmaskTree instance, it is WAY faster
* than using copy ctor or assignment operator, since it moves the nodes and tree root to
* new home instead of actually recreating the tree.
*
* Please see NetmaskGroup for example of simple use case. Other usecases can be found
* from GeoIPBackend and Sortlist, and from dnsdist.
*/
template <typename T, class K = Netmask>
class NetmaskTree
{
public:
class Iterator;
using key_type = K;
using value_type = T;
using node_type = std::pair<const key_type, value_type>;
using size_type = size_t;
using iterator = class Iterator;
private:
/** Single node in tree, internal use only.
*/
class TreeNode : boost::noncopyable
{
public:
explicit TreeNode() noexcept :
parent(nullptr), node(), assigned(false), d_bits(0)
{
}
explicit TreeNode(const key_type& key) :
parent(nullptr), node({key.getNormalized(), value_type()}), assigned(false), d_bits(key.getFullBits())
{
}
//<! Makes a left leaf node with specified key.
TreeNode* make_left(const key_type& key)
{
d_bits = node.first.getBits();
left = make_unique<TreeNode>(key);
left->parent = this;
return left.get();
}
//<! Makes a right leaf node with specified key.
TreeNode* make_right(const key_type& key)
{
d_bits = node.first.getBits();
right = make_unique<TreeNode>(key);
right->parent = this;
return right.get();
}
//<! Splits branch at indicated bit position by inserting key
TreeNode* split(const key_type& key, int bits)
{
if (parent == nullptr) {
// not to be called on the root node
throw std::logic_error(
"NetmaskTree::TreeNode::split(): must not be called on root node");
}
// determine reference from parent
unique_ptr<TreeNode>& parent_ref = (parent->left.get() == this ? parent->left : parent->right);
if (parent_ref.get() != this) {
throw std::logic_error(
"NetmaskTree::TreeNode::split(): parent node reference is invalid");
}
// create new tree node for the new key and
// attach the new node under our former parent
auto new_child = make_unique<TreeNode>(key);
auto* new_node = new_child.get();
new_node->d_bits = bits;
std::swap(parent_ref, new_child); // hereafter new_child points to "this"
new_node->parent = parent;
// attach "this" node below the new node
// (left or right depending on bit)
new_child->parent = new_node;
if (new_child->node.first.getBit(-1 - bits)) {
std::swap(new_node->right, new_child);
}
else {
std::swap(new_node->left, new_child);
}
return new_node;
}
//<! Forks branch for new key at indicated bit position
TreeNode* fork(const key_type& key, int bits)
{
if (parent == nullptr) {
// not to be called on the root node
throw std::logic_error(
"NetmaskTree::TreeNode::fork(): must not be called on root node");
}
// determine reference from parent
unique_ptr<TreeNode>& parent_ref = (parent->left.get() == this ? parent->left : parent->right);
if (parent_ref.get() != this) {
throw std::logic_error(
"NetmaskTree::TreeNode::fork(): parent node reference is invalid");
}
// create new tree node for the branch point
// the current node will now be a child of the new branch node
// (hereafter new_child1 points to "this")
unique_ptr<TreeNode> new_child1 = std::move(parent_ref);
// attach the branch node under our former parent
parent_ref = make_unique<TreeNode>(node.first.getSuper(bits));
auto* branch_node = parent_ref.get();
branch_node->d_bits = bits;
branch_node->parent = parent;
// create second new leaf node for the new key
unique_ptr<TreeNode> new_child2 = make_unique<TreeNode>(key);
TreeNode* new_node = new_child2.get();
// attach the new child nodes below the branch node
// (left or right depending on bit)
new_child1->parent = branch_node;
new_child2->parent = branch_node;
if (new_child1->node.first.getBit(-1 - bits)) {
branch_node->right = std::move(new_child1);
branch_node->left = std::move(new_child2);
}
else {
branch_node->right = std::move(new_child2);
branch_node->left = std::move(new_child1);
}
// now we have attached the new unique pointers to the tree:
// - branch_node is below its parent
// - new_child1 (ourselves) is below branch_node
// - new_child2, the new leaf node, is below branch_node as well
return new_node;
}
//<! Traverse left branch depth-first
TreeNode* traverse_l()
{
TreeNode* tnode = this;
while (tnode->left) {
tnode = tnode->left.get();
}
return tnode;
}
//<! Traverse tree depth-first and in-order (L-N-R)
TreeNode* traverse_lnr()
{
TreeNode* tnode = this;
// precondition: descended left as deep as possible
if (tnode->right) {
// descend right
tnode = tnode->right.get();
// descend left as deep as possible and return next node
return tnode->traverse_l();
}
// ascend to parent
while (tnode->parent != nullptr) {
TreeNode* prev_child = tnode;
tnode = tnode->parent;
// return this node, but only when we come from the left child branch
if (tnode->left && tnode->left.get() == prev_child) {
return tnode;
}
}
return nullptr;
}
//<! Traverse only assigned nodes