• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

PowerDNS / pdns / 12321902803

13 Dec 2024 07:34PM UTC coverage: 66.359% (+1.6%) from 64.78%
12321902803

Pull #14970

github

web-flow
Merge e3a7df61c into 3dfd8e317
Pull Request #14970: boost > std optional

26084 of 54744 branches covered (47.65%)

Branch coverage included in aggregate %.

14 of 15 new or added lines in 2 files covered. (93.33%)

1863 existing lines in 52 files now uncovered.

85857 of 113946 relevant lines covered (75.35%)

4412729.59 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

71.75
/pdns/iputils.hh
1
/*
2
 * This file is part of PowerDNS or dnsdist.
3
 * Copyright -- PowerDNS.COM B.V. and its contributors
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of version 2 of the GNU General Public License as
7
 * published by the Free Software Foundation.
8
 *
9
 * In addition, for the avoidance of any doubt, permission is granted to
10
 * link this program with OpenSSL and to (re)distribute the binaries
11
 * produced as the result of such linking.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
 */
22
#pragma once
23
#include <string>
24
#include <sys/socket.h>
25
#include <netinet/in.h>
26
#include <arpa/inet.h>
27
#include <iostream>
28
#include <cstdio>
29
#include <functional>
30
#include <bitset>
31
#include "pdnsexception.hh"
32
#include "misc.hh"
33
#include <netdb.h>
34
#include <sstream>
35

36
#include "namespaces.hh"
37

38
#ifdef __APPLE__
39
#include <libkern/OSByteOrder.h>
40

41
#define htobe16(x) OSSwapHostToBigInt16(x)
42
#define htole16(x) OSSwapHostToLittleInt16(x)
43
#define be16toh(x) OSSwapBigToHostInt16(x)
44
#define le16toh(x) OSSwapLittleToHostInt16(x)
45

46
#define htobe32(x) OSSwapHostToBigInt32(x)
47
#define htole32(x) OSSwapHostToLittleInt32(x)
48
#define be32toh(x) OSSwapBigToHostInt32(x)
49
#define le32toh(x) OSSwapLittleToHostInt32(x)
50

51
#define htobe64(x) OSSwapHostToBigInt64(x)
52
#define htole64(x) OSSwapHostToLittleInt64(x)
53
#define be64toh(x) OSSwapBigToHostInt64(x)
54
#define le64toh(x) OSSwapLittleToHostInt64(x)
55
#endif
56

57
#ifdef __sun
58

59
#define htobe16(x) BE_16(x)
60
#define htole16(x) LE_16(x)
61
#define be16toh(x) BE_IN16(&(x))
62
#define le16toh(x) LE_IN16(&(x))
63

64
#define htobe32(x) BE_32(x)
65
#define htole32(x) LE_32(x)
66
#define be32toh(x) BE_IN32(&(x))
67
#define le32toh(x) LE_IN32(&(x))
68

69
#define htobe64(x) BE_64(x)
70
#define htole64(x) LE_64(x)
71
#define be64toh(x) BE_IN64(&(x))
72
#define le64toh(x) LE_IN64(&(x))
73

74
#endif
75

76
#ifdef __FreeBSD__
77
#include <sys/endian.h>
78
#endif
79

80
#if defined(__NetBSD__) && defined(IP_PKTINFO) && !defined(IP_SENDSRCADDR)
81
// The IP_PKTINFO option in NetBSD was incompatible with Linux until a
82
// change that also introduced IP_SENDSRCADDR for FreeBSD compatibility.
83
#undef IP_PKTINFO
84
#endif
85

86
union ComboAddress
87
{
88
  sockaddr_in sin4{};
89
  sockaddr_in6 sin6;
90

91
  bool operator==(const ComboAddress& rhs) const
92
  {
19,252,606✔
93
    if (std::tie(sin4.sin_family, sin4.sin_port) != std::tie(rhs.sin4.sin_family, rhs.sin4.sin_port)) {
19,252,606✔
94
      return false;
9,319,339✔
95
    }
9,319,339✔
96
    if (sin4.sin_family == AF_INET) {
9,933,267✔
97
      return sin4.sin_addr.s_addr == rhs.sin4.sin_addr.s_addr;
3,254,899✔
98
    }
3,254,899✔
99
    return memcmp(&sin6.sin6_addr.s6_addr, &rhs.sin6.sin6_addr.s6_addr, sizeof(sin6.sin6_addr.s6_addr)) == 0;
6,678,368✔
100
  }
9,933,267✔
101

102
  bool operator!=(const ComboAddress& rhs) const
103
  {
293✔
104
    return (!operator==(rhs));
293✔
105
  }
293✔
106

107
  bool operator<(const ComboAddress& rhs) const
108
  {
1,473,298✔
109
    if (sin4.sin_family == 0) {
1,473,298✔
110
      return false;
53,657✔
111
    }
53,657✔
112
    if (std::tie(sin4.sin_family, sin4.sin_port) < std::tie(rhs.sin4.sin_family, rhs.sin4.sin_port)) {
1,419,641✔
113
      return true;
17,715✔
114
    }
17,715✔
115
    if (std::tie(sin4.sin_family, sin4.sin_port) > std::tie(rhs.sin4.sin_family, rhs.sin4.sin_port)) {
1,401,926✔
116
      return false;
7,615✔
117
    }
7,615✔
118
    if (sin4.sin_family == AF_INET) {
1,394,392✔
119
      return sin4.sin_addr.s_addr < rhs.sin4.sin_addr.s_addr;
1,037,768✔
120
    }
1,037,768✔
121
    return memcmp(&sin6.sin6_addr.s6_addr, &rhs.sin6.sin6_addr.s6_addr, sizeof(sin6.sin6_addr.s6_addr)) < 0;
2,147,840,266✔
122
  }
1,394,311✔
123

124
  bool operator>(const ComboAddress& rhs) const
125
  {
3✔
126
    return rhs.operator<(*this);
3✔
127
  }
3✔
128

129
  struct addressPortOnlyHash
130
  {
131
    uint32_t operator()(const ComboAddress& address) const
132
    {
×
UNCOV
133
      // NOLINTBEGIN(cppcoreguidelines-pro-type-reinterpret-cast)
×
134
      if (address.sin4.sin_family == AF_INET) {
×
135
        const auto* start = reinterpret_cast<const unsigned char*>(&address.sin4.sin_addr.s_addr);
×
136
        auto tmp = burtle(start, 4, 0);
×
137
        return burtle(reinterpret_cast<const uint8_t*>(&address.sin4.sin_port), 2, tmp);
×
138
      }
×
139
      const auto* start = reinterpret_cast<const unsigned char*>(&address.sin6.sin6_addr.s6_addr);
×
140
      auto tmp = burtle(start, 16, 0);
×
141
      return burtle(reinterpret_cast<const unsigned char*>(&address.sin6.sin6_port), 2, tmp);
×
UNCOV
142
      // NOLINTEND(cppcoreguidelines-pro-type-reinterpret-cast)
×
143
    }
×
144
  };
145

146
  struct addressOnlyHash
147
  {
148
    uint32_t operator()(const ComboAddress& address) const
UNCOV
149
    {
×
UNCOV
150
      const unsigned char* start = nullptr;
×
UNCOV
151
      uint32_t len = 0;
×
152
      // NOLINTBEGIN(cppcoreguidelines-pro-type-reinterpret-cast)
UNCOV
153
      if (address.sin4.sin_family == AF_INET) {
×
UNCOV
154
        start = reinterpret_cast<const unsigned char*>(&address.sin4.sin_addr.s_addr);
×
UNCOV
155
        len = 4;
×
UNCOV
156
      }
×
UNCOV
157
      else {
×
UNCOV
158
        start = reinterpret_cast<const unsigned char*>(&address.sin6.sin6_addr.s6_addr);
×
UNCOV
159
        len = 16;
×
UNCOV
160
      }
×
161
      // NOLINTEND(cppcoreguidelines-pro-type-reinterpret-cast)
UNCOV
162
      return burtle(start, len, 0);
×
UNCOV
163
    }
×
164
  };
165

166
  struct addressOnlyLessThan
167
  {
168
    bool operator()(const ComboAddress& lhs, const ComboAddress& rhs) const
169
    {
2,134✔
170
      if (lhs.sin4.sin_family < rhs.sin4.sin_family) {
2,134✔
171
        return true;
36✔
172
      }
36✔
173
      if (lhs.sin4.sin_family > rhs.sin4.sin_family) {
2,098✔
174
        return false;
4✔
175
      }
4✔
176
      if (lhs.sin4.sin_family == AF_INET) {
2,094✔
177
        return lhs.sin4.sin_addr.s_addr < rhs.sin4.sin_addr.s_addr;
2,038✔
178
      }
2,038✔
179
      return memcmp(&lhs.sin6.sin6_addr.s6_addr, &rhs.sin6.sin6_addr.s6_addr, sizeof(lhs.sin6.sin6_addr.s6_addr)) < 0;
56✔
180
    }
2,094✔
181
  };
182

183
  struct addressOnlyEqual
184
  {
185
    bool operator()(const ComboAddress& lhs, const ComboAddress& rhs) const
186
    {
19✔
187
      if (lhs.sin4.sin_family != rhs.sin4.sin_family) {
19!
188
        return false;
×
189
      }
×
190
      if (lhs.sin4.sin_family == AF_INET) {
19!
191
        return lhs.sin4.sin_addr.s_addr == rhs.sin4.sin_addr.s_addr;
19✔
192
      }
19✔
193
      return memcmp(&lhs.sin6.sin6_addr.s6_addr, &rhs.sin6.sin6_addr.s6_addr, sizeof(lhs.sin6.sin6_addr.s6_addr)) == 0;
×
194
    }
19✔
195
  };
196

197
  [[nodiscard]] socklen_t getSocklen() const
198
  {
1,730,476✔
199
    if (sin4.sin_family == AF_INET) {
1,730,476✔
200
      return sizeof(sin4);
417,067✔
201
    }
417,067✔
202
    return sizeof(sin6);
1,313,409✔
203
  }
1,730,476✔
204

205
  ComboAddress()
206
  {
10,892,986✔
207
    sin4.sin_family = AF_INET;
10,892,986✔
208
    sin4.sin_addr.s_addr = 0;
10,892,986✔
209
    sin4.sin_port = 0;
10,892,986✔
210
    sin6.sin6_scope_id = 0;
10,892,986✔
211
    sin6.sin6_flowinfo = 0;
10,892,986✔
212
  }
10,892,986✔
213

214
  ComboAddress(const struct sockaddr* socketAddress, socklen_t salen)
215
  {
126✔
216
    setSockaddr(socketAddress, salen);
126✔
217
  };
126✔
218

219
  ComboAddress(const struct sockaddr_in6* socketAddress)
UNCOV
220
  {
×
221
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
UNCOV
222
    setSockaddr(reinterpret_cast<const struct sockaddr*>(socketAddress), sizeof(struct sockaddr_in6));
×
UNCOV
223
  };
×
224

225
  ComboAddress(const struct sockaddr_in* socketAddress)
226
  {
×
227
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
228
    setSockaddr(reinterpret_cast<const struct sockaddr*>(socketAddress), sizeof(struct sockaddr_in));
×
229
  };
×
230

231
  void setSockaddr(const struct sockaddr* socketAddress, socklen_t salen)
232
  {
670✔
233
    if (salen > sizeof(struct sockaddr_in6)) {
670!
234
      throw PDNSException("ComboAddress can't handle other than sockaddr_in or sockaddr_in6");
×
235
    }
×
236
    memcpy(this, socketAddress, salen);
670✔
237
  }
670✔
238

239
  // 'port' sets a default value in case 'str' does not set a port
240
  explicit ComboAddress(const string& str, uint16_t port = 0)
241
  {
853,700✔
242
    memset(&sin6, 0, sizeof(sin6));
853,700✔
243
    sin4.sin_family = AF_INET;
853,700✔
244
    sin4.sin_port = 0;
853,700✔
245
    if (makeIPv4sockaddr(str, &sin4) != 0) {
853,700✔
246
      sin6.sin6_family = AF_INET6;
402,398✔
247
      if (makeIPv6sockaddr(str, &sin6) < 0) {
402,398✔
248
        throw PDNSException("Unable to convert presentation address '" + str + "'");
62✔
249
      }
62✔
250
    }
402,398✔
251
    if (sin4.sin_port == 0) { // 'str' overrides port!
853,638✔
252
      sin4.sin_port = htons(port);
850,533✔
253
    }
850,533✔
254
  }
853,638✔
255

256
  [[nodiscard]] bool isIPv6() const
257
  {
56,324,673✔
258
    return sin4.sin_family == AF_INET6;
56,324,673✔
259
  }
56,324,673✔
260
  [[nodiscard]] bool isIPv4() const
261
  {
104,557,264✔
262
    return sin4.sin_family == AF_INET;
104,557,264✔
263
  }
104,557,264✔
264

265
  [[nodiscard]] bool isMappedIPv4() const
266
  {
×
267
    if (sin4.sin_family != AF_INET6) {
×
268
      return false;
×
269
    }
×
270

271
    int iter = 0;
×
272
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
273
    const auto* ptr = reinterpret_cast<const unsigned char*>(&sin6.sin6_addr.s6_addr);
×
274
    for (iter = 0; iter < 10; ++iter) {
×
275
      if (ptr[iter] != 0) { // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
×
276
        return false;
×
277
      }
×
278
    }
×
279
    for (; iter < 12; ++iter) {
×
280
      if (ptr[iter] != 0xff) { // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
×
281
        return false;
×
282
      }
×
283
    }
×
284
    return true;
×
285
  }
×
286

287
  [[nodiscard]] ComboAddress mapToIPv4() const
288
  {
×
289
    if (!isMappedIPv4()) {
×
290
      throw PDNSException("ComboAddress can't map non-mapped IPv6 address back to IPv4");
×
291
    }
×
292
    ComboAddress ret;
×
293
    ret.sin4.sin_family = AF_INET;
×
294
    ret.sin4.sin_port = sin4.sin_port;
×
295

296
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
297
    const auto* ptr = reinterpret_cast<const unsigned char*>(&sin6.sin6_addr.s6_addr);
×
298
    ptr += (sizeof(sin6.sin6_addr.s6_addr) - sizeof(ret.sin4.sin_addr.s_addr)); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
×
299
    memcpy(&ret.sin4.sin_addr.s_addr, ptr, sizeof(ret.sin4.sin_addr.s_addr));
×
300
    return ret;
×
301
  }
×
302

303
  [[nodiscard]] string toString() const
304
  {
1,448,688✔
305
    std::array<char, 1024> host{};
1,448,688✔
306
    if (sin4.sin_family != 0) {
1,448,688✔
307
      // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
308
      int retval = getnameinfo(reinterpret_cast<const struct sockaddr*>(this), getSocklen(), host.data(), host.size(), nullptr, 0, NI_NUMERICHOST);
1,448,681✔
309
      if (retval == 0) {
1,448,687✔
310
        return host.data();
1,448,685✔
311
      }
1,448,685✔
312
      return "invalid " + string(gai_strerror(retval));
6,442,450,943✔
313
    }
1,448,681✔
314
    return "invalid";
7✔
315
  }
1,448,688✔
316

317
  //! Ignores any interface specifiers possibly available in the sockaddr data.
318
  [[nodiscard]] string toStringNoInterface() const
319
  {
2,493✔
320
    std::array<char, 1024> host{};
2,493✔
321
    if (sin4.sin_family == AF_INET) {
2,493✔
322
      const auto* ret = inet_ntop(sin4.sin_family, &sin4.sin_addr, host.data(), host.size());
1,931✔
323
      if (ret != nullptr) {
1,931!
324
        return host.data();
1,931✔
325
      }
1,931✔
326
    }
1,931✔
327
    else if (sin4.sin_family == AF_INET6) {
562✔
328
      const auto* ret = inet_ntop(sin4.sin_family, &sin6.sin6_addr, host.data(), host.size());
188✔
329
      if (ret != nullptr) {
188!
330
        return host.data();
188✔
331
      }
188✔
332
    }
188✔
333
    return "invalid " + stringerror();
374✔
334
  }
2,493✔
335

336
  [[nodiscard]] string toStringReversed() const
337
  {
58✔
338
    if (isIPv4()) {
58✔
339
      const auto address = ntohl(sin4.sin_addr.s_addr);
30✔
340
      auto aaa = (address >> 0) & 0xFF;
30✔
341
      auto bbb = (address >> 8) & 0xFF;
30✔
342
      auto ccc = (address >> 16) & 0xFF;
30✔
343
      auto ddd = (address >> 24) & 0xFF;
30✔
344
      return std::to_string(aaa) + "." + std::to_string(bbb) + "." + std::to_string(ccc) + "." + std::to_string(ddd);
30✔
345
    }
30✔
346
    const auto* addr = &sin6.sin6_addr;
28✔
347
    std::stringstream res{};
28✔
348
    res << std::hex;
28✔
349
    for (int i = 15; i >= 0; i--) {
476✔
350
      auto byte = addr->s6_addr[i]; // NOLINT(cppcoreguidelines-pro-bounds-constant-array-index)
448✔
351
      res << ((byte >> 0) & 0xF) << ".";
448✔
352
      res << ((byte >> 4) & 0xF);
448✔
353
      if (i != 0) {
448✔
354
        res << ".";
420✔
355
      }
420✔
356
    }
448✔
357
    return res.str();
28✔
358
  }
58✔
359

360
  [[nodiscard]] string toStringWithPort() const
361
  {
9,757✔
362
    if (sin4.sin_family == AF_INET) {
9,757✔
363
      return toString() + ":" + std::to_string(ntohs(sin4.sin_port));
8,981✔
364
    }
8,981✔
365
    return "[" + toString() + "]:" + std::to_string(ntohs(sin4.sin_port));
776✔
366
  }
9,757✔
367

368
  [[nodiscard]] string toStringWithPortExcept(int port) const
369
  {
99,474✔
370
    if (ntohs(sin4.sin_port) == port) {
99,474✔
371
      return toString();
280✔
372
    }
280✔
373
    if (sin4.sin_family == AF_INET) {
99,194✔
374
      return toString() + ":" + std::to_string(ntohs(sin4.sin_port));
99,173✔
375
    }
99,173✔
376
    return "[" + toString() + "]:" + std::to_string(ntohs(sin4.sin_port));
21✔
377
  }
99,194✔
378

379
  [[nodiscard]] string toLogString() const
380
  {
98,469✔
381
    return toStringWithPortExcept(53);
98,469✔
382
  }
98,469✔
383

384
  [[nodiscard]] string toStructuredLogString() const
385
  {
607✔
386
    return toStringWithPort();
607✔
387
  }
607✔
388

389
  [[nodiscard]] string toByteString() const
390
  {
5✔
391
    // NOLINTBEGIN(cppcoreguidelines-pro-type-reinterpret-cast)
392
    if (isIPv4()) {
5!
393
      return {reinterpret_cast<const char*>(&sin4.sin_addr.s_addr), sizeof(sin4.sin_addr.s_addr)};
5✔
394
    }
5✔
395
    return {reinterpret_cast<const char*>(&sin6.sin6_addr.s6_addr), sizeof(sin6.sin6_addr.s6_addr)};
×
396
    // NOLINTEND(cppcoreguidelines-pro-type-reinterpret-cast)
397
  }
5✔
398

399
  void truncate(unsigned int bits) noexcept;
400

401
  [[nodiscard]] uint16_t getNetworkOrderPort() const noexcept
402
  {
17,852✔
403
    return sin4.sin_port;
17,852✔
404
  }
17,852✔
405
  [[nodiscard]] uint16_t getPort() const noexcept
406
  {
17,852✔
407
    return ntohs(getNetworkOrderPort());
17,852✔
408
  }
17,852✔
409
  void setPort(uint16_t port)
410
  {
331✔
411
    sin4.sin_port = htons(port);
331✔
412
  }
331✔
413

414
  void reset()
415
  {
727,349✔
416
    memset(&sin4, 0, sizeof(sin4));
727,349✔
417
    memset(&sin6, 0, sizeof(sin6));
727,349✔
418
  }
727,349✔
419

420
  //! Get the total number of address bits (either 32 or 128 depending on IP version)
421
  [[nodiscard]] uint8_t getBits() const
422
  {
1,833,641✔
423
    if (isIPv4()) {
1,833,641✔
424
      return 32;
1,009,677✔
425
    }
1,009,677✔
426
    if (isIPv6()) {
823,971✔
427
      return 128;
823,967✔
428
    }
823,967✔
429
    return 0;
2,147,483,647✔
430
  }
823,964✔
431
  /** Get the value of the bit at the provided bit index. When the index >= 0,
432
      the index is relative to the LSB starting at index zero. When the index < 0,
433
      the index is relative to the MSB starting at index -1 and counting down.
434
   */
435
  [[nodiscard]] bool getBit(int index) const
436
  {
79,458,320✔
437
    if (isIPv4()) {
79,458,320✔
438
      if (index >= 32) {
23,958,112!
439
        return false;
×
440
      }
×
441
      if (index < 0) {
23,958,118✔
442
        if (index < -32) {
23,958,116!
443
          return false;
×
444
        }
×
445
        index = 32 + index;
23,958,116✔
446
      }
23,958,116✔
447

448
      uint32_t ls_addr = ntohl(sin4.sin_addr.s_addr);
23,958,112✔
449

450
      return ((ls_addr & (1U << index)) != 0x00000000);
23,958,112✔
451
    }
23,958,112✔
452
    if (isIPv6()) {
55,500,214✔
453
      if (index >= 128) {
55,500,210!
454
        return false;
×
455
      }
×
456
      if (index < 0) {
55,500,210!
457
        if (index < -128) {
55,500,210!
458
          return false;
×
459
        }
×
460
        index = 128 + index;
55,500,210✔
461
      }
55,500,210✔
462

463
      const auto* ls_addr = reinterpret_cast<const uint8_t*>(sin6.sin6_addr.s6_addr); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
55,500,210✔
464
      uint8_t byte_idx = index / 8;
55,500,210✔
465
      uint8_t bit_idx = index % 8;
55,500,210✔
466

467
      return ((ls_addr[15 - byte_idx] & (1U << bit_idx)) != 0x00); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
55,500,210✔
468
    }
55,500,210✔
469
    return false;
2,147,483,647✔
470
  }
55,500,208✔
471

472
  /*! Returns a comma-separated string of IP addresses
473
   *
474
   * \param c  An stl container with ComboAddresses
475
   * \param withPort  Also print the port (default true)
476
   * \param portExcept  Print the port, except when this is the port (default 53)
477
   */
478
  template <template <class...> class Container, class... Args>
479
  static string caContainerToString(const Container<ComboAddress, Args...>& container, const bool withPort = true, const uint16_t portExcept = 53)
480
  {
93✔
481
    vector<string> strs;
93✔
482
    for (const auto& address : container) {
189✔
483
      if (withPort) {
189✔
484
        strs.push_back(address.toStringWithPortExcept(portExcept));
48✔
485
        continue;
48✔
486
      }
48✔
487
      strs.push_back(address.toString());
141✔
488
    }
141✔
489
    return boost::join(strs, ",");
93✔
490
  };
93✔
491
};
492

493
/** This exception is thrown by the Netmask class and by extension by the NetmaskGroup class */
494
class NetmaskException : public PDNSException
495
{
496
public:
497
  NetmaskException(const string& arg) :
498
    PDNSException(arg) {}
14✔
499
};
500

501
inline ComboAddress makeComboAddress(const string& str)
502
{
423,836✔
503
  ComboAddress address;
423,836✔
504
  address.sin4.sin_family = AF_INET;
423,836✔
505
  if (inet_pton(AF_INET, str.c_str(), &address.sin4.sin_addr) <= 0) {
423,836✔
506
    address.sin4.sin_family = AF_INET6;
204,718✔
507
    if (makeIPv6sockaddr(str, &address.sin6) < 0) {
204,718✔
508
      throw NetmaskException("Unable to convert '" + str + "' to a netmask");
14✔
509
    }
14✔
510
  }
204,718✔
511
  return address;
423,822✔
512
}
423,836✔
513

514
inline ComboAddress makeComboAddressFromRaw(uint8_t version, const char* raw, size_t len)
515
{
137✔
516
  ComboAddress address;
137✔
517

518
  if (version == 4) {
137✔
519
    address.sin4.sin_family = AF_INET;
73✔
520
    if (len != sizeof(address.sin4.sin_addr)) {
73!
521
      throw NetmaskException("invalid raw address length");
×
522
    }
×
523
    memcpy(&address.sin4.sin_addr, raw, sizeof(address.sin4.sin_addr));
73✔
524
  }
73✔
525
  else if (version == 6) {
64!
526
    address.sin6.sin6_family = AF_INET6;
64✔
527
    if (len != sizeof(address.sin6.sin6_addr)) {
64!
528
      throw NetmaskException("invalid raw address length");
×
529
    }
×
530
    memcpy(&address.sin6.sin6_addr, raw, sizeof(address.sin6.sin6_addr));
64✔
531
  }
64✔
532
  else {
×
533
    throw NetmaskException("invalid address family");
×
534
  }
×
535

536
  return address;
137✔
537
}
137✔
538

539
inline ComboAddress makeComboAddressFromRaw(uint8_t version, const string& str)
540
{
35✔
541
  return makeComboAddressFromRaw(version, str.c_str(), str.size());
35✔
542
}
35✔
543

544
/** This class represents a netmask and can be queried to see if a certain
545
    IP address is matched by this mask */
546
class Netmask
547
{
548
public:
549
  Netmask()
550
  {
4,787,726✔
551
    d_network.sin4.sin_family = 0; // disable this doing anything useful
4,787,726✔
552
    d_network.sin4.sin_port = 0; // this guarantees d_network compares identical
4,787,726✔
553
  }
4,787,726✔
554

555
  Netmask(const ComboAddress& network, uint8_t bits = 0xff) :
556
    d_network(network)
557
  {
22,839,171✔
558
    d_network.sin4.sin_port = 0;
22,839,171✔
559
    setBits(bits);
22,839,171✔
560
  }
22,839,171✔
561

562
  Netmask(const sockaddr_in* network, uint8_t bits = 0xff) :
563
    d_network(network)
564
  {
×
565
    d_network.sin4.sin_port = 0;
×
566
    setBits(bits);
×
567
  }
×
568
  Netmask(const sockaddr_in6* network, uint8_t bits = 0xff) :
569
    d_network(network)
570
  {
×
571
    d_network.sin4.sin_port = 0;
×
572
    setBits(bits);
×
573
  }
×
574
  void setBits(uint8_t value)
575
  {
23,262,975✔
576
    d_bits = d_network.isIPv4() ? std::min(value, static_cast<uint8_t>(32U)) : std::min(value, static_cast<uint8_t>(128U));
23,262,975✔
577

578
    if (d_bits < 32) {
23,262,975✔
579
      d_mask = ~(0xFFFFFFFF >> d_bits);
5,316,479✔
580
    }
5,316,479✔
581
    else {
17,946,496✔
582
      // note that d_mask is unused for IPv6
583
      d_mask = 0xFFFFFFFF;
17,946,496✔
584
    }
17,946,496✔
585

586
    if (isIPv4()) {
23,262,975✔
587
      d_network.sin4.sin_addr.s_addr = htonl(ntohl(d_network.sin4.sin_addr.s_addr) & d_mask);
9,404,068✔
588
    }
9,404,068✔
589
    else if (isIPv6()) {
13,858,907✔
590
      uint8_t bytes = d_bits / 8;
12,613,438✔
591
      auto* address = reinterpret_cast<uint8_t*>(&d_network.sin6.sin6_addr.s6_addr); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
12,613,438✔
592
      uint8_t bits = d_bits % 8;
12,613,438✔
593
      auto mask = static_cast<uint8_t>(~(0xFF >> bits));
12,613,438✔
594

595
      if (bytes < sizeof(d_network.sin6.sin6_addr.s6_addr)) {
12,613,438✔
596
        address[bytes] &= mask; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
10,244,032✔
597
      }
10,244,032✔
598

599
      for (size_t idx = bytes + 1; idx < sizeof(d_network.sin6.sin6_addr.s6_addr); ++idx) {
94,112,634✔
600
        address[idx] = 0; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
81,499,196✔
601
      }
81,499,196✔
602
    }
12,613,438✔
603
  }
23,262,975✔
604

605
  //! Constructor supplies the mask, which cannot be changed
606
  Netmask(const string& mask)
607
  {
423,815✔
608
    pair<string, string> split = splitField(mask, '/');
423,815✔
609
    d_network = makeComboAddress(split.first);
423,815✔
610

611
    if (!split.second.empty()) {
423,815✔
612
      setBits(pdns::checked_stoi<uint8_t>(split.second));
222,433✔
613
    }
222,433✔
614
    else if (d_network.sin4.sin_family == AF_INET) {
201,382✔
615
      setBits(32);
199,128✔
616
    }
199,128✔
617
    else {
2,254✔
618
      setBits(128);
2,254✔
619
    }
2,254✔
620
  }
423,815✔
621

622
  [[nodiscard]] bool match(const ComboAddress& address) const
623
  {
37✔
624
    return match(&address);
37✔
625
  }
37✔
626

627
  //! If this IP address in socket address matches
628
  bool match(const ComboAddress* address) const
629
  {
58✔
630
    if (d_network.sin4.sin_family != address->sin4.sin_family) {
58!
631
      return false;
×
632
    }
×
633
    if (d_network.sin4.sin_family == AF_INET) {
58✔
634
      return match4(htonl((unsigned int)address->sin4.sin_addr.s_addr));
40✔
635
    }
40✔
636
    if (d_network.sin6.sin6_family == AF_INET6) {
18!
637
      uint8_t bytes = d_bits / 8;
18✔
638
      uint8_t index = 0;
18✔
639
      // NOLINTBEGIN(cppcoreguidelines-pro-type-reinterpret-cast)
640
      const auto* lhs = reinterpret_cast<const uint8_t*>(&d_network.sin6.sin6_addr.s6_addr);
18✔
641
      const auto* rhs = reinterpret_cast<const uint8_t*>(&address->sin6.sin6_addr.s6_addr);
18✔
642
      // NOLINTEND(cppcoreguidelines-pro-type-reinterpret-cast)
643

644
      // NOLINTBEGIN(cppcoreguidelines-pro-bounds-pointer-arithmetic)
645
      for (index = 0; index < bytes; ++index) {
96✔
646
        if (lhs[index] != rhs[index]) {
84✔
647
          return false;
6✔
648
        }
6✔
649
      }
84✔
650
      // still here, now match remaining bits
651
      uint8_t bits = d_bits % 8;
12✔
652
      auto mask = static_cast<uint8_t>(~(0xFF >> bits));
12✔
653

654
      return ((lhs[index]) == (rhs[index] & mask));
12✔
655
      // NOLINTEND(cppcoreguidelines-pro-bounds-pointer-arithmetic)
656
    }
18✔
657
    return false;
×
658
  }
18✔
659

660
  //! If this ASCII IP address matches
661
  [[nodiscard]] bool match(const string& arg) const
662
  {
21✔
663
    ComboAddress address = makeComboAddress(arg);
21✔
664
    return match(&address);
21✔
665
  }
21✔
666

667
  //! If this IP address in native format matches
668
  [[nodiscard]] bool match4(uint32_t arg) const
669
  {
40✔
670
    return (arg & d_mask) == (ntohl(d_network.sin4.sin_addr.s_addr));
40✔
671
  }
40✔
672

673
  [[nodiscard]] string toString() const
674
  {
932✔
675
    return d_network.toStringNoInterface() + "/" + std::to_string((unsigned int)d_bits);
932✔
676
  }
932✔
677

678
  [[nodiscard]] string toStringNoMask() const
679
  {
1,501✔
680
    return d_network.toStringNoInterface();
1,501✔
681
  }
1,501✔
682

683
  [[nodiscard]] const ComboAddress& getNetwork() const
684
  {
21,452,889✔
685
    return d_network;
21,452,889✔
686
  }
21,452,889✔
687

688
  [[nodiscard]] const ComboAddress& getMaskedNetwork() const
689
  {
21,448,697✔
690
    return getNetwork();
21,448,697✔
691
  }
21,448,697✔
692

693
  [[nodiscard]] uint8_t getBits() const
694
  {
56,213,501✔
695
    return d_bits;
56,213,501✔
696
  }
56,213,501✔
697

698
  [[nodiscard]] bool isIPv6() const
699
  {
14,497,811✔
700
    return d_network.sin6.sin6_family == AF_INET6;
14,497,811✔
701
  }
14,497,811✔
702

703
  [[nodiscard]] bool isIPv4() const
704
  {
24,729,835✔
705
    return d_network.sin4.sin_family == AF_INET;
24,729,835✔
706
  }
24,729,835✔
707

708
  bool operator<(const Netmask& rhs) const
709
  {
984,904✔
710
    if (empty() && !rhs.empty()) {
984,904✔
711
      return false;
6✔
712
    }
6✔
713
    if (!empty() && rhs.empty()) {
984,898✔
714
      return true;
3,146✔
715
    }
3,146✔
716
    if (d_bits > rhs.d_bits) {
981,752✔
717
      return true;
178,676✔
718
    }
178,676✔
719
    if (d_bits < rhs.d_bits) {
803,076✔
720
      return false;
92,943✔
721
    }
92,943✔
722

723
    return d_network < rhs.d_network;
710,133✔
724
  }
803,076✔
725

726
  bool operator>(const Netmask& rhs) const
727
  {
18✔
728
    return rhs.operator<(*this);
18✔
729
  }
18✔
730

731
  bool operator==(const Netmask& rhs) const
732
  {
19,248,408✔
733
    return std::tie(d_network, d_bits) == std::tie(rhs.d_network, rhs.d_bits);
19,248,408✔
734
  }
19,248,408✔
735

736
  [[nodiscard]] bool empty() const
737
  {
4,316,909✔
738
    return d_network.sin4.sin_family == 0;
4,316,909✔
739
  }
4,316,909✔
740

741
  //! Get normalized version of the netmask. This means that all address bits below the network bits are zero.
742
  [[nodiscard]] Netmask getNormalized() const
743
  {
21,420,978✔
744
    return {getMaskedNetwork(), d_bits};
21,420,978✔
745
  }
21,420,978✔
746
  //! Get Netmask for super network of this one (i.e. with fewer network bits)
747
  [[nodiscard]] Netmask getSuper(uint8_t bits) const
748
  {
419,741✔
749
    return {d_network, std::min(d_bits, bits)};
419,741✔
750
  }
419,741✔
751

752
  //! Get the total number of address bits for this netmask (either 32 or 128 depending on IP version)
753
  [[nodiscard]] uint8_t getFullBits() const
754
  {
864,833✔
755
    return d_network.getBits();
864,833✔
756
  }
864,833✔
757

758
  /** Get the value of the bit at the provided bit index. When the index >= 0,
759
      the index is relative to the LSB starting at index zero. When the index < 0,
760
      the index is relative to the MSB starting at index -1 and counting down.
761
      When the index points outside the network bits, it always yields zero.
762
   */
763
  [[nodiscard]] bool getBit(int bit) const
764
  {
79,458,332✔
765
    if (bit < -d_bits) {
79,458,332!
766
      return false;
×
767
    }
×
768
    if (bit >= 0) {
79,458,332!
769
      if (isIPv4()) {
×
770
        if (bit >= 32 || bit < (32 - d_bits)) {
×
771
          return false;
×
772
        }
×
773
      }
×
774
      if (isIPv6()) {
×
775
        if (bit >= 128 || bit < (128 - d_bits)) {
×
776
          return false;
×
777
        }
×
778
      }
×
779
    }
×
780
    return d_network.getBit(bit);
79,458,332✔
781
  }
79,458,332✔
782

783
  struct Hash
784
  {
785
    size_t operator()(const Netmask& netmask) const
786
    {
×
787
      return burtle(&netmask.d_bits, 1, ComboAddress::addressOnlyHash()(netmask.d_network));
×
788
    }
×
789
  };
790

791
private:
792
  ComboAddress d_network;
793
  uint32_t d_mask{0};
794
  uint8_t d_bits{0};
795
};
796

797
namespace std
798
{
799
template <>
800
struct hash<Netmask>
801
{
802
  auto operator()(const Netmask& netmask) const
803
  {
×
804
    return Netmask::Hash{}(netmask);
×
805
  }
×
806
};
807
}
808

809
/** Binary tree map implementation with <Netmask,T> pair.
810
 *
811
 * This is an binary tree implementation for storing attributes for IPv4 and IPv6 prefixes.
812
 * The most simple use case is simple NetmaskTree<bool> used by NetmaskGroup, which only
813
 * wants to know if given IP address is matched in the prefixes stored.
814
 *
815
 * This element is useful for anything that needs to *STORE* prefixes, and *MATCH* IP addresses
816
 * to a *LIST* of *PREFIXES*. Not the other way round.
817
 *
818
 * You can store IPv4 and IPv6 addresses to same tree, separate payload storage is kept per AFI.
819
 * Network prefixes (Netmasks) are always recorded in normalized fashion, meaning that only
820
 * the network bits are set. This is what is returned in the insert() and lookup() return
821
 * values.
822
 *
823
 * Use swap if you need to move the tree to another NetmaskTree instance, it is WAY faster
824
 * than using copy ctor or assignment operator, since it moves the nodes and tree root to
825
 * new home instead of actually recreating the tree.
826
 *
827
 * Please see NetmaskGroup for example of simple use case. Other usecases can be found
828
 * from GeoIPBackend and Sortlist, and from dnsdist.
829
 */
830
template <typename T, class K = Netmask>
831
class NetmaskTree
832
{
833
public:
834
  class Iterator;
835

836
  using key_type = K;
837
  using value_type = T;
838
  using node_type = std::pair<const key_type, value_type>;
839
  using size_type = size_t;
840
  using iterator = class Iterator;
841

842
private:
843
  /** Single node in tree, internal use only.
844
   */
845
  class TreeNode : boost::noncopyable
846
  {
847
  public:
848
    explicit TreeNode() noexcept :
849
      parent(nullptr), node(), assigned(false), d_bits(0)
850
    {
13,859✔
851
    }
13,859✔
852
    explicit TreeNode(const key_type& key) :
853
      parent(nullptr), node({key.getNormalized(), value_type()}), assigned(false), d_bits(key.getFullBits())
854
    {
864,833✔
855
    }
864,833✔
856

857
    //<! Makes a left leaf node with specified key.
858
    TreeNode* make_left(const key_type& key)
859
    {
1,634✔
860
      d_bits = node.first.getBits();
1,634✔
861
      left = make_unique<TreeNode>(key);
1,634✔
862
      left->parent = this;
1,634✔
863
      return left.get();
1,634✔
864
    }
1,634✔
865

866
    //<! Makes a right leaf node with specified key.
867
    TreeNode* make_right(const key_type& key)
868
    {
15,082✔
869
      d_bits = node.first.getBits();
15,082✔
870
      right = make_unique<TreeNode>(key);
15,082✔
871
      right->parent = this;
15,082✔
872
      return right.get();
15,082✔
873
    }
15,082✔
874

875
    //<! Splits branch at indicated bit position by inserting key
876
    TreeNode* split(const key_type& key, int bits)
877
    {
3,182✔
878
      if (parent == nullptr) {
3,182!
879
        // not to be called on the root node
880
        throw std::logic_error(
×
881
          "NetmaskTree::TreeNode::split(): must not be called on root node");
×
882
      }
×
883

884
      // determine reference from parent
885
      unique_ptr<TreeNode>& parent_ref = (parent->left.get() == this ? parent->left : parent->right);
3,182!
886
      if (parent_ref.get() != this) {
3,182!
887
        throw std::logic_error(
×
888
          "NetmaskTree::TreeNode::split(): parent node reference is invalid");
×
889
      }
×
890

891
      // create new tree node for the new key and
892
      // attach the new node under our former parent
893
      auto new_intermediate_node = make_unique<TreeNode>(key);
3,182✔
894
      new_intermediate_node->d_bits = bits;
3,182✔
895
      new_intermediate_node->parent = parent;
3,182✔
896
      auto* new_intermediate_node_raw = new_intermediate_node.get();
3,182✔
897

898
      // hereafter new_intermediate points to "this"
899
      // ie the child of the new intermediate node
900
      std::swap(parent_ref, new_intermediate_node);
3,182✔
901
      // and we now assign this to current_node so
902
      // it's clear it no longer refers to the new
903
      // intermediate node
904
      std::unique_ptr<TreeNode> current_node = std::move(new_intermediate_node);
3,182✔
905

906
      // attach "this" node below the new node
907
      // (left or right depending on bit)
908
      // technically the raw pointer escapes the duration of the
909
      // unique pointer, but just below we store the unique pointer
910
      // in the parent, so it lives as long as necessary
911
      // coverity[escape]
912
      current_node->parent = new_intermediate_node_raw;
3,182✔
913
      if (current_node->node.first.getBit(-1 - bits)) {
3,182!
914
        new_intermediate_node_raw->right = std::move(current_node);
111✔
915
      }
111✔
916
      else {
3,071✔
917
        new_intermediate_node_raw->left = std::move(current_node);
3,071✔
918
      }
3,071✔
919

920
      return new_intermediate_node_raw;
3,182✔
921
    }
3,182✔
922

923
    //<! Forks branch for new key at indicated bit position
924
    TreeNode* fork(const key_type& key, int bits)
925
    {
419,741✔
926
      if (parent == nullptr) {
419,741!
927
        // not to be called on the root node
928
        throw std::logic_error(
×
929
          "NetmaskTree::TreeNode::fork(): must not be called on root node");
×
930
      }
×
931

932
      // determine reference from parent
933
      unique_ptr<TreeNode>& parent_ref = (parent->left.get() == this ? parent->left : parent->right);
419,741!
934
      if (parent_ref.get() != this) {
419,741!
935
        throw std::logic_error(
×
936
          "NetmaskTree::TreeNode::fork(): parent node reference is invalid");
×
937
      }
×
938

939
      // create new tree node for the branch point
940

941
      // the current node will now be a child of the new branch node
942
      // (hereafter new_child1 points to "this")
943
      unique_ptr<TreeNode> new_child1 = std::move(parent_ref);
419,741✔
944
      // attach the branch node under our former parent
945
      parent_ref = make_unique<TreeNode>(node.first.getSuper(bits));
419,741✔
946
      auto* branch_node = parent_ref.get();
419,741✔
947
      branch_node->d_bits = bits;
419,741✔
948
      branch_node->parent = parent;
419,741✔
949

950
      // create second new leaf node for the new key
951
      unique_ptr<TreeNode> new_child2 = make_unique<TreeNode>(key);
419,741✔
952
      TreeNode* new_node = new_child2.get();
419,741✔
953

954
      // attach the new child nodes below the branch node
955
      // (left or right depending on bit)
956
      new_child1->parent = branch_node;
419,741✔
957
      new_child2->parent = branch_node;
419,741✔
958
      if (new_child1->node.first.getBit(-1 - bits)) {
419,741!
959
        branch_node->right = std::move(new_child1);
2,565✔
960
        branch_node->left = std::move(new_child2);
2,565✔
961
      }
2,565✔
962
      else {
417,176✔
963
        branch_node->right = std::move(new_child2);
417,176✔
964
        branch_node->left = std::move(new_child1);
417,176✔
965
      }
417,176✔
966
      // now we have attached the new unique pointers to the tree:
967
      // - branch_node is below its parent
968
      // - new_child1 (ourselves) is below branch_node
969
      // - new_child2, the new leaf node, is below branch_node as well
970

971
      return new_node;
419,741✔
972
    }
419,741✔
973

974
    //<! Traverse left branch depth-first
975
    TreeNode* traverse_l()
976
    {
97,027✔
977
      TreeNode* tnode = this;
97,027✔
978

979
      while (tnode->left) {
192,690✔
980
        tnode = tnode->left.get();
95,663✔
981
      }
95,663✔
982
      return tnode;
97,027✔
983
    }
97,027✔
984

985
    //<! Traverse tree depth-first and in-order (L-N-R)
986
    TreeNode* traverse_lnr()
987
    {
193,323✔
988
      TreeNode* tnode = this;
193,323✔
989

990
      // precondition: descended left as deep as possible
991
      if (tnode->right) {
193,323!
992
        // descend right
993
        tnode = tnode->right.get();
94,544✔
994
        // descend left as deep as possible and return next node
995
        return tnode->traverse_l();
94,544✔
996
      }
94,544✔
997

998
      // ascend to parent
999
      while (tnode->parent != nullptr) {
193,323✔
1000
        TreeNode* prev_child = tnode;
190,760✔
1001
        tnode = tnode->parent;
190,760✔
1002

1003
        // return this node, but only when we come from the left child branch
1004
        if (tnode->left && tnode->left.get() == prev_child) {
190,760!
1005
          return tnode;
96,216✔
1006
        }
96,216✔
1007
      }
190,760✔
1008
      return nullptr;
2,563✔
1009
    }
98,779✔
1010

1011
    //<! Traverse only assigned nodes
1012
    TreeNode* traverse_lnr_assigned()
1013
    {
85,682✔
1014
      TreeNode* tnode = traverse_lnr();
85,682✔
1015

1016
      while (tnode != nullptr && !tnode->assigned) {
150,459!
1017
        tnode = tnode->traverse_lnr();
64,777✔
1018
      }
64,777✔
1019
      return tnode;
85,682✔
1020
    }
85,682✔
1021

1022
    unique_ptr<TreeNode> left;
1023
    unique_ptr<TreeNode> right;
1024
    TreeNode* parent;
1025

1026
    node_type node;
1027
    bool assigned; //<! Whether this node is assigned-to by the application
1028

1029
    int d_bits; //<! How many bits have been used so far
1030
  };
1031

1032
  void cleanup_tree(TreeNode* node)
1033
  {
28,531✔
1034
    // only cleanup this node if it has no children and node not assigned
1035
    if (!(node->left || node->right || node->assigned)) {
28,531!
1036
      // get parent node ptr
1037
      TreeNode* pparent = node->parent;
14,921✔
1038
      // delete this node
1039
      if (pparent) {
14,921✔
1040
        if (pparent->left.get() == node) {
14,900✔
1041
          pparent->left.reset();
2,090✔
1042
        }
2,090✔
1043
        else {
12,810✔
1044
          pparent->right.reset();
12,810✔
1045
        }
12,810✔
1046
        // now recurse up to the parent
1047
        cleanup_tree(pparent);
14,900✔
1048
      }
14,900✔
1049
    }
14,921✔
1050
  }
28,531✔
1051

1052
  void copyTree(const NetmaskTree& rhs)
1053
  {
2,483✔
1054
    try {
2,483✔
1055
      TreeNode* node = rhs.d_root.get();
2,483✔
1056
      if (node != nullptr) {
2,483!
1057
        node = node->traverse_l();
2,483✔
1058
      }
2,483✔
1059
      while (node != nullptr) {
45,347✔
1060
        if (node->assigned) {
42,864✔
1061
          insert(node->node.first).second = node->node.second;
23,006✔
1062
        }
23,006✔
1063
        node = node->traverse_lnr();
42,864✔
1064
      }
42,864✔
1065
    }
2,483✔
1066
    catch (const NetmaskException&) {
2,483✔
1067
      abort();
×
1068
    }
×
1069
    catch (const std::logic_error&) {
2,483✔
1070
      abort();
×
1071
    }
×
1072
  }
2,483✔
1073

1074
public:
1075
  class Iterator
1076
  {
1077
  public:
1078
    using value_type = node_type;
1079
    using reference = node_type&;
1080
    using pointer = node_type*;
1081
    using iterator_category = std::forward_iterator_tag;
1082
    using difference_type = size_type;
1083

1084
  private:
1085
    friend class NetmaskTree;
1086

1087
    const NetmaskTree* d_tree;
1088
    TreeNode* d_node;
1089

1090
    Iterator(const NetmaskTree* tree, TreeNode* node) :
1091
      d_tree(tree), d_node(node)
1092
    {
362✔
1093
    }
362✔
1094

1095
  public:
1096
    Iterator() :
1097
      d_tree(nullptr), d_node(nullptr) {}
×
1098

1099
    Iterator& operator++() // prefix
1100
    {
83,616✔
1101
      if (d_node == nullptr) {
83,616!
1102
        throw std::logic_error(
×
1103
          "NetmaskTree::Iterator::operator++: iterator is invalid");
×
1104
      }
×
1105
      d_node = d_node->traverse_lnr_assigned();
83,616✔
1106
      return *this;
83,616✔
1107
    }
83,616✔
1108
    Iterator operator++(int) // postfix
1109
    {
×
1110
      Iterator tmp(*this);
×
1111
      operator++();
×
1112
      return tmp;
×
1113
    }
×
1114

1115
    reference operator*()
1116
    {
45,569✔
1117
      if (d_node == nullptr) {
45,569!
1118
        throw std::logic_error(
×
1119
          "NetmaskTree::Iterator::operator*: iterator is invalid");
×
1120
      }
×
1121
      return d_node->node;
45,569✔
1122
    }
45,569✔
1123

1124
    pointer operator->()
1125
    {
182✔
1126
      if (d_node == nullptr) {
182!
1127
        throw std::logic_error(
×
1128
          "NetmaskTree::Iterator::operator->: iterator is invalid");
×
1129
      }
×
1130
      return &d_node->node;
182✔
1131
    }
182✔
1132

1133
    bool operator==(const Iterator& rhs)
1134
    {
83,797✔
1135
      return (d_tree == rhs.d_tree && d_node == rhs.d_node);
83,797!
1136
    }
83,797✔
1137
    bool operator!=(const Iterator& rhs)
1138
    {
83,797✔
1139
      return !(*this == rhs);
83,797✔
1140
    }
83,797✔
1141
  };
1142

1143
  NetmaskTree() noexcept :
1144
    d_root(new TreeNode()), d_left(nullptr)
1145
  {
8,743✔
1146
  }
8,743✔
1147

1148
  NetmaskTree(const NetmaskTree& rhs) :
1149
    d_root(new TreeNode()), d_left(nullptr)
1150
  {
2,315✔
1151
    copyTree(rhs);
2,315✔
1152
  }
2,315✔
1153

1154
  ~NetmaskTree() = default;
7,358✔
1155

1156
  NetmaskTree& operator=(const NetmaskTree& rhs)
1157
  {
168✔
1158
    if (this != &rhs) {
168!
1159
      clear();
168✔
1160
      copyTree(rhs);
168✔
1161
    }
168✔
1162
    return *this;
168✔
1163
  }
168✔
1164

1165
  NetmaskTree(NetmaskTree&&) noexcept = default;
280✔
1166
  NetmaskTree& operator=(NetmaskTree&&) noexcept = default;
137✔
1167

1168
  [[nodiscard]] iterator begin() const
1169
  {
148✔
1170
    return Iterator(this, d_left);
148✔
1171
  }
148✔
1172
  [[nodiscard]] iterator end() const
1173
  {
148✔
1174
    return Iterator(this, nullptr);
148✔
1175
  }
148✔
1176
  iterator begin()
1177
  {
33✔
1178
    return Iterator(this, d_left);
33✔
1179
  }
33✔
1180
  iterator end()
1181
  {
33✔
1182
    return Iterator(this, nullptr);
33✔
1183
  }
33✔
1184

1185
  node_type& insert(const string& mask)
1186
  {
9✔
1187
    return insert(key_type(mask));
9✔
1188
  }
9✔
1189

1190
  //<! Creates new value-pair in tree and returns it.
1191
  node_type& insert(const key_type& key)
1192
  {
445,555✔
1193
    TreeNode* node{};
445,555✔
1194
    bool is_left = true;
445,555✔
1195

1196
    // we turn left on IPv4 and right on IPv6
1197
    if (key.isIPv4()) {
445,555!
1198
      node = d_root->left.get();
227,518✔
1199
      if (node == nullptr) {
227,518!
1200

1201
        d_root->left = make_unique<TreeNode>(key);
2,860✔
1202
        node = d_root->left.get();
2,860✔
1203
        node->assigned = true;
2,860✔
1204
        node->parent = d_root.get();
2,860✔
1205
        d_size++;
2,860✔
1206
        d_left = node;
2,860✔
1207
        return node->node;
2,860✔
1208
      }
2,860✔
1209
    }
227,518✔
1210
    else if (key.isIPv6()) {
218,037!
1211
      node = d_root->right.get();
218,037✔
1212
      if (node == nullptr) {
218,037!
1213

1214
        d_root->right = make_unique<TreeNode>(key);
2,593✔
1215
        node = d_root->right.get();
2,593✔
1216
        node->assigned = true;
2,593✔
1217
        node->parent = d_root.get();
2,593✔
1218
        d_size++;
2,593✔
1219
        if (!d_root->left) {
2,593!
1220
          d_left = node;
15✔
1221
        }
15✔
1222
        return node->node;
2,593✔
1223
      }
2,593✔
1224
      if (d_root->left) {
215,444!
1225
        is_left = false;
215,438✔
1226
      }
215,438✔
1227
    }
215,444✔
1228
    else {
×
1229
      throw NetmaskException("invalid address family");
×
1230
    }
×
1231

1232
    // we turn left on 0 and right on 1
1233
    int bits = 0;
440,102✔
1234
    for (; bits < key.getBits(); bits++) {
19,584,640!
1235
      bool vall = key.getBit(-1 - bits);
19,580,995✔
1236

1237
      if (bits >= node->d_bits) {
19,580,995!
1238
        // the end of the current node is reached; continue with the next
1239
        if (vall) {
3,000,168!
1240
          if (node->left || node->assigned) {
2,907,614!
1241
            is_left = false;
2,907,614✔
1242
          }
2,907,614✔
1243
          if (!node->right) {
2,907,614!
1244
            // the right branch doesn't exist yet; attach our key here
1245
            node = node->make_right(key);
1,216✔
1246
            break;
1,216✔
1247
          }
1,216✔
1248
          node = node->right.get();
2,906,398✔
1249
        }
2,906,398✔
1250
        else {
92,554✔
1251
          if (!node->left) {
92,554!
1252
            // the left branch doesn't exist yet; attach our key here
1253
            node = node->make_left(key);
33✔
1254
            break;
33✔
1255
          }
33✔
1256
          node = node->left.get();
92,521✔
1257
        }
92,521✔
1258
        continue;
2,998,919✔
1259
      }
3,000,168✔
1260
      if (bits >= node->node.first.getBits()) {
16,580,827!
1261
        // the matching branch ends here, yet the key netmask has more bits; add a
1262
        // child node below the existing branch leaf.
1263
        if (vall) {
15,467!
1264
          if (node->assigned) {
13,866!
1265
            is_left = false;
13,866✔
1266
          }
13,866✔
1267
          node = node->make_right(key);
13,866✔
1268
        }
13,866✔
1269
        else {
1,601✔
1270
          node = node->make_left(key);
1,601✔
1271
        }
1,601✔
1272
        break;
15,467✔
1273
      }
15,467✔
1274
      bool valr = node->node.first.getBit(-1 - bits);
16,565,360✔
1275
      if (vall != valr) {
16,565,360!
1276
        if (vall) {
419,741!
1277
          is_left = false;
417,176✔
1278
        }
417,176✔
1279
        // the branch matches just upto this point, yet continues in a different
1280
        // direction; fork the branch.
1281
        node = node->fork(key, bits);
419,741✔
1282
        break;
419,741✔
1283
      }
419,741✔
1284
    }
16,565,360✔
1285

1286
    if (node->node.first.getBits() > key.getBits()) {
440,102!
1287
      // key is a super-network of the matching node; split the branch and
1288
      // insert a node for the key above the matching node.
1289
      node = node->split(key, key.getBits());
3,182✔
1290
    }
3,182✔
1291

1292
    if (node->left) {
440,102!
1293
      is_left = false;
3,521✔
1294
    }
3,521✔
1295

1296
    node_type& value = node->node;
440,102✔
1297

1298
    if (!node->assigned) {
440,102!
1299
      // only increment size if not assigned before
1300
      d_size++;
439,810✔
1301
      // update the pointer to the left-most tree node
1302
      if (is_left) {
439,810!
1303
        d_left = node;
485✔
1304
      }
485✔
1305
      node->assigned = true;
439,810✔
1306
    }
439,810✔
1307
    else {
292✔
1308
      // tree node exists for this value
1309
      if (is_left && d_left != node) {
292!
1310
        throw std::logic_error(
×
1311
          "NetmaskTree::insert(): lost track of left-most node in tree");
×
1312
      }
×
1313
    }
292✔
1314

1315
    return value;
440,102✔
1316
  }
440,102✔
1317

1318
  //<! Creates or updates value
1319
  void insert_or_assign(const key_type& mask, const value_type& value)
1320
  {
10✔
1321
    insert(mask).second = value;
10✔
1322
  }
10✔
1323

1324
  void insert_or_assign(const string& mask, const value_type& value)
1325
  {
×
1326
    insert(key_type(mask)).second = value;
×
1327
  }
×
1328

1329
  //<! check if given key is present in TreeMap
1330
  [[nodiscard]] bool has_key(const key_type& key) const
1331
  {
80✔
1332
    const node_type* ptr = lookup(key);
80✔
1333
    return ptr && ptr->first == key;
80!
1334
  }
80✔
1335

1336
  //<! Returns "best match" for key_type, which might not be value
1337
  [[nodiscard]] node_type* lookup(const key_type& value) const
1338
  {
38,635✔
1339
    uint8_t max_bits = value.getBits();
38,635✔
1340
    return lookupImpl(value, max_bits);
38,635✔
1341
  }
38,635✔
1342

1343
  //<! Perform best match lookup for value, using at most max_bits
1344
  [[nodiscard]] node_type* lookup(const ComboAddress& value, int max_bits = 128) const
1345
  {
968,815✔
1346
    uint8_t addr_bits = value.getBits();
968,815✔
1347
    if (max_bits < 0 || max_bits > addr_bits) {
968,819!
1348
      max_bits = addr_bits;
573,679✔
1349
    }
573,679✔
1350

1351
    return lookupImpl(key_type(value, max_bits), max_bits);
968,815✔
1352
  }
968,815✔
1353

1354
  //<! Removes key from TreeMap.
1355
  void erase(const key_type& key)
1356
  {
13,636✔
1357
    TreeNode* node = nullptr;
13,636✔
1358

1359
    if (key.isIPv4()) {
13,636!
1360
      node = d_root->left.get();
13,615✔
1361
    }
13,615✔
1362
    else if (key.isIPv6()) {
21!
1363
      node = d_root->right.get();
21✔
1364
    }
21✔
1365
    else {
×
1366
      throw NetmaskException("invalid address family");
×
1367
    }
×
1368
    // no tree, no value
1369
    if (node == nullptr) {
13,636!
1370
      return;
×
1371
    }
×
1372
    int bits = 0;
13,636✔
1373
    for (; node && bits < key.getBits(); bits++) {
346,447!
1374
      bool vall = key.getBit(-1 - bits);
332,814✔
1375
      if (bits >= node->d_bits) {
332,814✔
1376
        // the end of the current node is reached; continue with the next
1377
        if (vall) {
214,442✔
1378
          node = node->right.get();
147,044✔
1379
        }
147,044✔
1380
        else {
67,398✔
1381
          node = node->left.get();
67,398✔
1382
        }
67,398✔
1383
        continue;
214,442✔
1384
      }
214,442✔
1385
      if (bits >= node->node.first.getBits()) {
118,372!
1386
        // the matching branch ends here
1387
        if (key.getBits() != node->node.first.getBits()) {
×
1388
          node = nullptr;
×
1389
        }
×
1390
        break;
×
1391
      }
×
1392
      bool valr = node->node.first.getBit(-1 - bits);
118,372✔
1393
      if (vall != valr) {
118,372!
1394
        // the branch matches just upto this point, yet continues in a different
1395
        // direction
1396
        node = nullptr;
3✔
1397
        break;
3✔
1398
      }
3✔
1399
    }
118,372✔
1400
    if (node) {
13,636✔
1401
      if (d_size == 0) {
13,631!
1402
        throw std::logic_error(
×
1403
          "NetmaskTree::erase(): size of tree is zero before erase");
×
1404
      }
×
1405
      d_size--;
13,631✔
1406
      node->assigned = false;
13,631✔
1407
      node->node.second = value_type();
13,631✔
1408

1409
      if (node == d_left) {
13,631!
1410
        d_left = d_left->traverse_lnr_assigned();
2,066✔
1411
      }
2,066✔
1412
      cleanup_tree(node);
13,631✔
1413
    }
13,631✔
1414
  }
13,636✔
1415

1416
  void erase(const string& key)
1417
  {
9✔
1418
    erase(key_type(key));
9✔
1419
  }
9✔
1420

1421
  //<! checks whether the container is empty.
1422
  [[nodiscard]] bool empty() const
1423
  {
98,833✔
1424
    return (d_size == 0);
98,833✔
1425
  }
98,833✔
1426

1427
  //<! returns the number of elements
1428
  [[nodiscard]] size_type size() const
1429
  {
419,920✔
1430
    return d_size;
419,920✔
1431
  }
419,920✔
1432

1433
  //<! See if given ComboAddress matches any prefix
1434
  [[nodiscard]] bool match(const ComboAddress& value) const
1435
  {
2,261✔
1436
    return (lookup(value) != nullptr);
2,261✔
1437
  }
2,261✔
1438

1439
  [[nodiscard]] bool match(const std::string& value) const
1440
  {
×
1441
    return match(ComboAddress(value));
×
1442
  }
×
1443

1444
  //<! Clean out the tree
1445
  void clear()
1446
  {
2,801✔
1447
    d_root = make_unique<TreeNode>();
2,801✔
1448
    d_left = nullptr;
2,801✔
1449
    d_size = 0;
2,801✔
1450
  }
2,801✔
1451

1452
  //<! swaps the contents with another NetmaskTree
1453
  void swap(NetmaskTree& rhs) noexcept
1454
  {
45✔
1455
    std::swap(d_root, rhs.d_root);
45✔
1456
    std::swap(d_left, rhs.d_left);
45✔
1457
    std::swap(d_size, rhs.d_size);
45✔
1458
  }
45✔
1459

1460
private:
1461
  [[nodiscard]] node_type* lookupImpl(const key_type& value, uint8_t max_bits) const
1462
  {
1,007,439✔
1463
    TreeNode* node = nullptr;
1,007,439✔
1464

1465
    if (value.isIPv4()) {
1,007,447!
1466
      node = d_root->left.get();
589,944✔
1467
    }
589,944✔
1468
    else if (value.isIPv6()) {
2,147,901,141!
1469
      node = d_root->right.get();
417,494✔
1470
    }
417,494✔
1471
    else {
2,147,483,647✔
1472
      throw NetmaskException("invalid address family");
2,147,483,647✔
1473
    }
2,147,483,647✔
1474
    if (node == nullptr) {
1,007,438!
1475
      return nullptr;
149,866✔
1476
    }
149,866✔
1477

1478
    node_type* ret = nullptr;
857,572✔
1479

1480
    int bits = 0;
857,572✔
1481
    for (; bits < max_bits; bits++) {
25,385,671!
1482
      bool vall = value.getBit(-1 - bits);
25,147,893✔
1483
      if (bits >= node->d_bits) {
25,147,893!
1484
        // the end of the current node is reached; continue with the next
1485
        // (we keep track of last assigned node)
1486
        if (node->assigned && bits == node->node.first.getBits()) {
7,650,778!
1487
          ret = &node->node;
671,062✔
1488
        }
671,062✔
1489
        if (vall) {
7,650,778!
1490
          if (!node->right) {
3,435,224!
1491
            break;
11,522✔
1492
          }
11,522✔
1493
          node = node->right.get();
3,423,702✔
1494
        }
3,423,702✔
1495
        else {
4,215,554✔
1496
          if (!node->left) {
4,215,554!
1497
            break;
1,789✔
1498
          }
1,789✔
1499
          node = node->left.get();
4,213,765✔
1500
        }
4,213,765✔
1501
        continue;
7,637,467✔
1502
      }
7,650,778✔
1503
      if (bits >= node->node.first.getBits()) {
17,497,115!
1504
        // the matching branch ends here
1505
        break;
207,130✔
1506
      }
207,130✔
1507
      bool valr = node->node.first.getBit(-1 - bits);
17,289,985✔
1508
      if (vall != valr) {
17,289,985!
1509
        // the branch matches just upto this point, yet continues in a different
1510
        // direction
1511
        break;
399,365✔
1512
      }
399,365✔
1513
    }
17,289,985✔
1514
    // needed if we did not find one in loop
1515
    if (node->assigned && bits == node->node.first.getBits()) {
857,572!
1516
      ret = &node->node;
457,197✔
1517
    }
457,197✔
1518
    // this can be nullptr.
1519
    return ret;
857,572✔
1520
  }
1,007,438✔
1521

1522
  unique_ptr<TreeNode> d_root; //<! Root of our tree
1523
  TreeNode* d_left;
1524
  size_type d_size{0};
1525
};
1526

1527
/** This class represents a group of supplemental Netmask classes. An IP address matches
1528
    if it is matched by one or more of the Netmask objects within.
1529
*/
1530
class NetmaskGroup
1531
{
1532
public:
1533
  NetmaskGroup() noexcept = default;
4,041✔
1534

1535
  //! If this IP address is matched by any of the classes within
1536

1537
  bool match(const ComboAddress* address) const
1538
  {
161,806✔
1539
    const auto& ret = tree.lookup(*address);
161,806✔
1540
    if (ret != nullptr) {
161,806✔
1541
      return ret->second;
11,912✔
1542
    }
11,912✔
1543
    return false;
149,894✔
1544
  }
161,806✔
1545

1546
  [[nodiscard]] bool match(const ComboAddress& address) const
1547
  {
150,936✔
1548
    return match(&address);
150,936✔
1549
  }
150,936✔
1550

1551
  bool lookup(const ComboAddress* address, Netmask* nmp) const
1552
  {
×
1553
    const auto& ret = tree.lookup(*address);
×
1554
    if (ret != nullptr) {
×
1555
      if (nmp != nullptr) {
×
1556
        *nmp = ret->first;
×
1557
      }
×
1558
      return ret->second;
×
1559
    }
×
1560
    return false;
×
1561
  }
×
1562

1563
  bool lookup(const ComboAddress& address, Netmask* nmp) const
1564
  {
×
1565
    return lookup(&address, nmp);
×
1566
  }
×
1567

1568
  //! Add this string to the list of possible matches
1569
  void addMask(const string& address, bool positive = true)
1570
  {
7,538✔
1571
    if (!address.empty() && address[0] == '!') {
7,538!
1572
      addMask(Netmask(address.substr(1)), false);
1,230✔
1573
    }
1,230✔
1574
    else {
6,308✔
1575
      addMask(Netmask(address), positive);
6,308✔
1576
    }
6,308✔
1577
  }
7,538✔
1578

1579
  //! Add this Netmask to the list of possible matches
1580
  void addMask(const Netmask& netmask, bool positive = true)
1581
  {
7,580✔
1582
    tree.insert(netmask).second = positive;
7,580✔
1583
  }
7,580✔
1584

1585
  void addMasks(const NetmaskGroup& group, boost::optional<bool> positive)
UNCOV
1586
  {
×
UNCOV
1587
    for (const auto& entry : group.tree) {
×
UNCOV
1588
      addMask(entry.first, positive ? *positive : entry.second);
×
UNCOV
1589
    }
×
UNCOV
1590
  }
×
1591

1592
  //! Delete this Netmask from the list of possible matches
1593
  void deleteMask(const Netmask& netmask)
1594
  {
×
1595
    tree.erase(netmask);
×
1596
  }
×
1597

1598
  void deleteMasks(const NetmaskGroup& group)
1599
  {
×
1600
    for (const auto& entry : group.tree) {
×
1601
      deleteMask(entry.first);
×
1602
    }
×
1603
  }
×
1604

1605
  void deleteMask(const std::string& address)
1606
  {
×
1607
    if (!address.empty()) {
×
1608
      deleteMask(Netmask(address));
×
1609
    }
×
1610
  }
×
1611

1612
  void clear()
1613
  {
1,367✔
1614
    tree.clear();
1,367✔
1615
  }
1,367✔
1616

1617
  [[nodiscard]] bool empty() const
1618
  {
97,469✔
1619
    return tree.empty();
97,469✔
1620
  }
97,469✔
1621

1622
  [[nodiscard]] size_t size() const
1623
  {
290✔
1624
    return tree.size();
290✔
1625
  }
290✔
1626

1627
  [[nodiscard]] string toString() const
1628
  {
16✔
1629
    ostringstream str;
16✔
1630
    for (auto iter = tree.begin(); iter != tree.end(); ++iter) {
107✔
1631
      if (iter != tree.begin()) {
91✔
1632
        str << ", ";
75✔
1633
      }
75✔
1634
      if (!(iter->second)) {
91✔
1635
        str << "!";
18✔
1636
      }
18✔
1637
      str << iter->first.toString();
91✔
1638
    }
91✔
1639
    return str.str();
16✔
1640
  }
16✔
1641

1642
  [[nodiscard]] std::vector<std::string> toStringVector() const
1643
  {
5✔
1644
    std::vector<std::string> out;
5✔
1645
    out.reserve(tree.size());
5✔
1646
    for (const auto& entry : tree) {
6✔
1647
      out.push_back((entry.second ? "" : "!") + entry.first.toString());
6!
1648
    }
6✔
1649
    return out;
5✔
1650
  }
5✔
1651

1652
  void toMasks(const string& ips)
1653
  {
1,021✔
1654
    vector<string> parts;
1,021✔
1655
    stringtok(parts, ips, ", \t");
1,021✔
1656

1657
    for (const auto& part : parts) {
1,131✔
1658
      addMask(part);
702✔
1659
    }
702✔
1660
  }
1,021✔
1661

1662
private:
1663
  NetmaskTree<bool> tree;
1664
};
1665

1666
struct SComboAddress
1667
{
1668
  SComboAddress(const ComboAddress& orig) :
1669
    ca(orig) {}
4,764✔
1670
  ComboAddress ca;
1671
  bool operator<(const SComboAddress& rhs) const
1672
  {
×
1673
    return ComboAddress::addressOnlyLessThan()(ca, rhs.ca);
×
1674
  }
×
1675
  operator const ComboAddress&() const
1676
  {
×
1677
    return ca;
×
1678
  }
×
1679
};
1680

1681
class NetworkError : public runtime_error
1682
{
1683
public:
1684
  NetworkError(const string& why = "Network Error") :
1685
    runtime_error(why.c_str())
1686
  {}
463✔
1687
  NetworkError(const char* why = "Network Error") :
1688
    runtime_error(why)
UNCOV
1689
  {}
×
1690
};
1691

1692
class AddressAndPortRange
1693
{
1694
public:
1695
  AddressAndPortRange() :
1696
    d_addrMask(0), d_portMask(0)
UNCOV
1697
  {
×
UNCOV
1698
    d_addr.sin4.sin_family = 0; // disable this doing anything useful
×
UNCOV
1699
    d_addr.sin4.sin_port = 0; // this guarantees d_network compares identical
×
UNCOV
1700
  }
×
1701

1702
  AddressAndPortRange(ComboAddress address, uint8_t addrMask, uint8_t portMask = 0) :
1703
    d_addr(address), d_addrMask(addrMask), d_portMask(portMask)
UNCOV
1704
  {
×
UNCOV
1705
    if (!d_addr.isIPv4()) {
×
UNCOV
1706
      d_portMask = 0;
×
UNCOV
1707
    }
×
UNCOV
1708

×
UNCOV
1709
    uint16_t port = d_addr.getPort();
×
UNCOV
1710
    if (d_portMask < 16) {
×
UNCOV
1711
      auto mask = static_cast<uint16_t>(~(0xFFFF >> d_portMask));
×
UNCOV
1712
      port = port & mask;
×
UNCOV
1713
    }
×
UNCOV
1714

×
UNCOV
1715
    if (d_addrMask < d_addr.getBits()) {
×
UNCOV
1716
      if (d_portMask > 0) {
×
1717
        throw std::runtime_error("Trying to create a AddressAndPortRange with a reduced address mask (" + std::to_string(d_addrMask) + ") and a port range (" + std::to_string(d_portMask) + ")");
×
1718
      }
×
UNCOV
1719
      d_addr = Netmask(d_addr, d_addrMask).getMaskedNetwork();
×
UNCOV
1720
    }
×
UNCOV
1721
    d_addr.setPort(port);
×
UNCOV
1722
  }
×
1723

1724
  [[nodiscard]] uint8_t getFullBits() const
UNCOV
1725
  {
×
UNCOV
1726
    return d_addr.getBits() + 16;
×
UNCOV
1727
  }
×
1728

1729
  [[nodiscard]] uint8_t getBits() const
UNCOV
1730
  {
×
UNCOV
1731
    if (d_addrMask < d_addr.getBits()) {
×
UNCOV
1732
      return d_addrMask;
×
UNCOV
1733
    }
×
UNCOV
1734

×
UNCOV
1735
    return d_addr.getBits() + d_portMask;
×
UNCOV
1736
  }
×
1737

1738
  /** Get the value of the bit at the provided bit index. When the index >= 0,
1739
      the index is relative to the LSB starting at index zero. When the index < 0,
1740
      the index is relative to the MSB starting at index -1 and counting down.
1741
  */
1742
  [[nodiscard]] bool getBit(int index) const
UNCOV
1743
  {
×
UNCOV
1744
    if (index >= getFullBits()) {
×
1745
      return false;
×
1746
    }
×
UNCOV
1747
    if (index < 0) {
×
UNCOV
1748
      index = getFullBits() + index;
×
UNCOV
1749
    }
×
UNCOV
1750

×
UNCOV
1751
    if (index < 16) {
×
UNCOV
1752
      /* we are into the port bits */
×
UNCOV
1753
      uint16_t port = d_addr.getPort();
×
UNCOV
1754
      return ((port & (1U << index)) != 0x0000);
×
UNCOV
1755
    }
×
UNCOV
1756

×
UNCOV
1757
    index -= 16;
×
UNCOV
1758

×
UNCOV
1759
    return d_addr.getBit(index);
×
UNCOV
1760
  }
×
1761

1762
  [[nodiscard]] bool isIPv4() const
UNCOV
1763
  {
×
UNCOV
1764
    return d_addr.isIPv4();
×
UNCOV
1765
  }
×
1766

1767
  [[nodiscard]] bool isIPv6() const
UNCOV
1768
  {
×
UNCOV
1769
    return d_addr.isIPv6();
×
UNCOV
1770
  }
×
1771

1772
  [[nodiscard]] AddressAndPortRange getNormalized() const
UNCOV
1773
  {
×
UNCOV
1774
    return {d_addr, d_addrMask, d_portMask};
×
UNCOV
1775
  }
×
1776

1777
  [[nodiscard]] AddressAndPortRange getSuper(uint8_t bits) const
UNCOV
1778
  {
×
UNCOV
1779
    if (bits <= d_addrMask) {
×
UNCOV
1780
      return {d_addr, bits, 0};
×
UNCOV
1781
    }
×
1782
    if (bits <= d_addrMask + d_portMask) {
×
1783
      return {d_addr, d_addrMask, static_cast<uint8_t>(d_portMask - (bits - d_addrMask))};
×
1784
    }
×
UNCOV
1785

×
1786
    return {d_addr, d_addrMask, d_portMask};
×
1787
  }
×
1788

1789
  [[nodiscard]] const ComboAddress& getNetwork() const
UNCOV
1790
  {
×
UNCOV
1791
    return d_addr;
×
UNCOV
1792
  }
×
1793

1794
  [[nodiscard]] string toString() const
UNCOV
1795
  {
×
UNCOV
1796
    if (d_addrMask < d_addr.getBits() || d_portMask == 0) {
×
UNCOV
1797
      return d_addr.toStringNoInterface() + "/" + std::to_string(d_addrMask);
×
UNCOV
1798
    }
×
UNCOV
1799
    return d_addr.toStringNoInterface() + ":" + std::to_string(d_addr.getPort()) + "/" + std::to_string(d_portMask);
×
UNCOV
1800
  }
×
1801

1802
  [[nodiscard]] bool empty() const
1803
  {
×
1804
    return d_addr.sin4.sin_family == 0;
×
1805
  }
×
1806

1807
  bool operator==(const AddressAndPortRange& rhs) const
UNCOV
1808
  {
×
UNCOV
1809
    return std::tie(d_addr, d_addrMask, d_portMask) == std::tie(rhs.d_addr, rhs.d_addrMask, rhs.d_portMask);
×
UNCOV
1810
  }
×
1811

1812
  bool operator<(const AddressAndPortRange& rhs) const
1813
  {
×
1814
    if (empty() && !rhs.empty()) {
×
1815
      return false;
×
1816
    }
×
UNCOV
1817

×
1818
    if (!empty() && rhs.empty()) {
×
1819
      return true;
×
1820
    }
×
UNCOV
1821

×
1822
    if (d_addrMask > rhs.d_addrMask) {
×
1823
      return true;
×
1824
    }
×
UNCOV
1825

×
1826
    if (d_addrMask < rhs.d_addrMask) {
×
1827
      return false;
×
1828
    }
×
UNCOV
1829

×
1830
    if (d_addr < rhs.d_addr) {
×
1831
      return true;
×
1832
    }
×
UNCOV
1833

×
1834
    if (d_addr > rhs.d_addr) {
×
1835
      return false;
×
1836
    }
×
UNCOV
1837

×
1838
    if (d_portMask > rhs.d_portMask) {
×
1839
      return true;
×
1840
    }
×
UNCOV
1841

×
1842
    if (d_portMask < rhs.d_portMask) {
×
1843
      return false;
×
1844
    }
×
UNCOV
1845

×
1846
    return d_addr.getPort() < rhs.d_addr.getPort();
×
1847
  }
×
1848

1849
  bool operator>(const AddressAndPortRange& rhs) const
1850
  {
×
1851
    return rhs.operator<(*this);
×
1852
  }
×
1853

1854
  struct hash
1855
  {
1856
    uint32_t operator()(const AddressAndPortRange& apr) const
UNCOV
1857
    {
×
UNCOV
1858
      ComboAddress::addressOnlyHash hashOp;
×
UNCOV
1859
      uint16_t port = apr.d_addr.getPort();
×
UNCOV
1860
      /* it's fine to hash the whole address and port because the non-relevant parts have
×
UNCOV
1861
         been masked to 0 */
×
UNCOV
1862
      return burtle(reinterpret_cast<const unsigned char*>(&port), sizeof(port), hashOp(apr.d_addr)); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
×
UNCOV
1863
    }
×
1864
  };
1865

1866
private:
1867
  ComboAddress d_addr;
1868
  uint8_t d_addrMask;
1869
  /* only used for v4 addresses */
1870
  uint8_t d_portMask;
1871
};
1872

1873
int SSocket(int family, int type, int flags);
1874
int SConnect(int sockfd, const ComboAddress& remote);
1875
/* tries to connect to remote for a maximum of timeout seconds.
1876
   sockfd should be set to non-blocking beforehand.
1877
   returns 0 on success (the socket is writable), throw a
1878
   runtime_error otherwise */
1879
int SConnectWithTimeout(int sockfd, const ComboAddress& remote, const struct timeval& timeout);
1880
int SBind(int sockfd, const ComboAddress& local);
1881
int SAccept(int sockfd, ComboAddress& remote);
1882
int SListen(int sockfd, int limit);
1883
int SSetsockopt(int sockfd, int level, int opname, int value);
1884
void setSocketIgnorePMTU(int sockfd, int family);
1885
void setSocketForcePMTU(int sockfd, int family);
1886
bool setReusePort(int sockfd);
1887

1888
#if defined(IP_PKTINFO)
1889
#define GEN_IP_PKTINFO IP_PKTINFO
106✔
1890
#elif defined(IP_RECVDSTADDR)
1891
#define GEN_IP_PKTINFO IP_RECVDSTADDR
1892
#endif
1893

1894
bool IsAnyAddress(const ComboAddress& addr);
1895
bool HarvestDestinationAddress(const struct msghdr* msgh, ComboAddress* destination);
1896
bool HarvestTimestamp(struct msghdr* msgh, struct timeval* timeval);
1897
void fillMSGHdr(struct msghdr* msgh, struct iovec* iov, cmsgbuf_aligned* cbuf, size_t cbufsize, char* data, size_t datalen, ComboAddress* addr);
1898
int sendOnNBSocket(int fileDesc, const struct msghdr* msgh);
1899
size_t sendMsgWithOptions(int socketDesc, const void* buffer, size_t len, const ComboAddress* dest, const ComboAddress* local, unsigned int localItf, int flags);
1900

1901
/* requires a non-blocking, connected TCP socket */
1902
bool isTCPSocketUsable(int sock);
1903

1904
extern template class NetmaskTree<bool>;
1905
ComboAddress parseIPAndPort(const std::string& input, uint16_t port);
1906

1907
std::set<std::string> getListOfNetworkInterfaces();
1908
std::vector<ComboAddress> getListOfAddressesOfNetworkInterface(const std::string& itf);
1909
std::vector<Netmask> getListOfRangesOfNetworkInterface(const std::string& itf);
1910

1911
/* These functions throw if the value was already set to a higher value,
1912
   or on error */
1913
void setSocketBuffer(int fileDesc, int optname, uint32_t size);
1914
void setSocketReceiveBuffer(int fileDesc, uint32_t size);
1915
void setSocketSendBuffer(int fileDesc, uint32_t size);
1916
uint32_t raiseSocketReceiveBufferToMax(int socket);
1917
uint32_t raiseSocketSendBufferToMax(int socket);
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc