subnet.cc 19.8 KB
Newer Older
1
// Copyright (C) 2012-2017 Internet Systems Consortium, Inc. ("ISC")
2
//
3
4
5
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6

7
8
#include <config.h>

9
#include <asiolink/io_address.h>
10
#include <dhcp/option_space.h>
11
12
#include <dhcpsrv/addr_utilities.h>
#include <dhcpsrv/subnet.h>
13
#include <algorithm>
14
#include <sstream>
15
16

using namespace isc::asiolink;
17
using namespace isc::data;
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
using namespace isc::dhcp;

namespace {

/// @brief Function used in calls to std::upper_bound to check
/// if the specified prefix is lower than the first address a pool.
///
/// @return true if prefix is lower than the first address in the pool.
bool
prefixLessThanFirstAddress(const IOAddress& prefix, const PoolPtr& pool) {
    return (prefix < pool->getFirstAddress());
}

/// @brief Function used in calls to std::sort to compare first
/// prefixes of the two pools.
///
/// @param pool1 First pool.
/// @param pool2 Second pool.
///
/// @return true if first prefix of the first pool is smaller than
/// the first address of the second pool.
bool
comparePoolFirstAddress(const PoolPtr& pool1, const PoolPtr& pool2) {
    return (pool1->getFirstAddress() < pool2->getFirstAddress());
};

}
45
46
47
48

namespace isc {
namespace dhcp {

49
50
51
// This is an initial value of subnet-id. See comments in subnet.h for details.
SubnetID Subnet::static_id_ = 1;

52
Subnet::Subnet(const isc::asiolink::IOAddress& prefix, uint8_t len,
53
               const SubnetID id)
54
    : id_(id == 0 ? generateNextID() : id), prefix_(prefix),
55
56
57
      prefix_len_(len),
      last_allocated_ia_(lastAddrInPrefix(prefix, len)),
      last_allocated_ta_(lastAddrInPrefix(prefix, len)),
58
      last_allocated_pd_(lastAddrInPrefix(prefix, len)) {
59
60
    if ((prefix.isV6() && len > 128) ||
        (prefix.isV4() && len > 32)) {
61
        isc_throw(BadValue,
62
                  "Invalid prefix length specified for subnet: " << len);
63
64
65
    }
}

66
bool
67
Subnet::inRange(const isc::asiolink::IOAddress& addr) const {
68
69
70
71
72
73
    IOAddress first = firstAddrInPrefix(prefix_, prefix_len_);
    IOAddress last = lastAddrInPrefix(prefix_, prefix_len_);

    return ((first <= addr) && (addr <= last));
}

74
isc::asiolink::IOAddress Subnet::getLastAllocated(Lease::Type type) const {
75
76
77
    // check if the type is valid (and throw if it isn't)
    checkType(type);

78
    switch (type) {
79
80
    case Lease::TYPE_V4:
    case Lease::TYPE_NA:
81
        return last_allocated_ia_;
82
    case Lease::TYPE_TA:
83
        return last_allocated_ta_;
84
    case Lease::TYPE_PD:
85
86
87
88
89
90
        return last_allocated_pd_;
    default:
        isc_throw(BadValue, "Pool type " << type << " not supported");
    }
}

91
void Subnet::setLastAllocated(Lease::Type type,
92
93
94
95
96
                              const isc::asiolink::IOAddress& addr) {

    // check if the type is valid (and throw if it isn't)
    checkType(type);

97
    switch (type) {
98
99
    case Lease::TYPE_V4:
    case Lease::TYPE_NA:
100
101
        last_allocated_ia_ = addr;
        return;
102
    case Lease::TYPE_TA:
103
104
        last_allocated_ta_ = addr;
        return;
105
    case Lease::TYPE_PD:
106
107
108
109
110
111
112
        last_allocated_pd_ = addr;
        return;
    default:
        isc_throw(BadValue, "Pool type " << type << " not supported");
    }
}

113
std::string
114
Subnet::toText() const {
115
    std::stringstream tmp;
116
    tmp << prefix_ << "/" << static_cast<unsigned int>(prefix_len_);
117
118
119
    return (tmp.str());
}

120
uint64_t
Tomek Mrugalski's avatar
Tomek Mrugalski committed
121
Subnet::getPoolCapacity(Lease::Type type) const {
122
123
124
    switch (type) {
    case Lease::TYPE_V4:
    case Lease::TYPE_NA:
Tomek Mrugalski's avatar
Tomek Mrugalski committed
125
        return sumPoolCapacity(pools_);
126
    case Lease::TYPE_TA:
Tomek Mrugalski's avatar
Tomek Mrugalski committed
127
        return sumPoolCapacity(pools_ta_);
128
    case Lease::TYPE_PD:
Tomek Mrugalski's avatar
Tomek Mrugalski committed
129
        return sumPoolCapacity(pools_pd_);
130
131
132
133
134
135
136
    default:
        isc_throw(BadValue, "Unsupported pool type: "
                  << static_cast<int>(type));
    }
}

uint64_t
Tomek Mrugalski's avatar
Tomek Mrugalski committed
137
Subnet::sumPoolCapacity(const PoolCollection& pools) const {
138
139
    uint64_t sum = 0;
    for (PoolCollection::const_iterator p = pools.begin(); p != pools.end(); ++p) {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
140
        uint64_t x = (*p)->getCapacity();
141
142
143
144
145
146
147
148
149
150
151
152
153

        // Check if we can add it. If sum + x > uint64::max, then we would have
        // overflown if we tried to add it.
        if (x > std::numeric_limits<uint64_t>::max() - sum) {
            return (std::numeric_limits<uint64_t>::max());
        }

        sum += x;
    }

    return (sum);
}

154
155
void Subnet4::checkType(Lease::Type type) const {
    if (type != Lease::TYPE_V4) {
156
157
158
159
        isc_throw(BadValue, "Only TYPE_V4 is allowed for Subnet4");
    }
}

160
161
162
Subnet4::Subnet4(const isc::asiolink::IOAddress& prefix, uint8_t length,
                 const Triplet<uint32_t>& t1,
                 const Triplet<uint32_t>& t2,
163
164
                 const Triplet<uint32_t>& valid_lifetime,
                 const SubnetID id)
165
166
    : Subnet(prefix, length, id), Network4(),
      siaddr_(IOAddress("0.0.0.0")) {
167
    if (!prefix.isV4()) {
168
169
170
        isc_throw(BadValue, "Non IPv4 prefix " << prefix.toText()
                  << " specified in subnet4");
    }
171
172
173
174
175
176
    // Relay info.
    setRelayInfo(IOAddress::IPV4_ZERO_ADDRESS());
    // Timers.
    setT1(t1);
    setT2(t2);
    setValid(valid_lifetime);
177
178
}

179
180
181
182
183
184
185
186
187
188
189
bool
Subnet4::clientSupported(const isc::dhcp::ClientClasses& client_classes) const {
    NetworkPtr network;
    getSharedNetwork(network);
    if (network && !network->clientSupported(client_classes)) {
        return (false);
    }

    return (Network4::clientSupported(client_classes));
}

190
191
void Subnet4::setSiaddr(const isc::asiolink::IOAddress& siaddr) {
    if (!siaddr.isV4()) {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
192
        isc_throw(BadValue, "Can't set siaddr to non-IPv4 address "
193
                  << siaddr);
194
195
196
197
198
199
200
201
    }
    siaddr_ = siaddr;
}

isc::asiolink::IOAddress Subnet4::getSiaddr() const {
    return (siaddr_);
}

202
const PoolCollection& Subnet::getPools(Lease::Type type) const {
203
204
205
    // check if the type is valid (and throw if it isn't)
    checkType(type);

206
    switch (type) {
207
208
    case Lease::TYPE_V4:
    case Lease::TYPE_NA:
209
        return (pools_);
210
    case Lease::TYPE_TA:
211
        return (pools_ta_);
212
    case Lease::TYPE_PD:
213
214
        return (pools_pd_);
    default:
Tomek Mrugalski's avatar
Tomek Mrugalski committed
215
216
        isc_throw(BadValue, "Unsupported pool type: "
                  << static_cast<int>(type));
217
    }
218
}
219

Tomek Mrugalski's avatar
Tomek Mrugalski committed
220
PoolCollection& Subnet::getPoolsWritable(Lease::Type type) {
221
222
    // check if the type is valid (and throw if it isn't)
    checkType(type);
223

224
    switch (type) {
225
226
    case Lease::TYPE_V4:
    case Lease::TYPE_NA:
227
        return (pools_);
228
    case Lease::TYPE_TA:
229
        return (pools_ta_);
230
    case Lease::TYPE_PD:
231
        return (pools_pd_);
232
    default:
233
234
        isc_throw(BadValue, "Invalid pool type specified: "
                  << static_cast<int>(type));
235
    }
236
237
}

Tomek Mrugalski's avatar
Tomek Mrugalski committed
238
const PoolPtr Subnet::getPool(Lease::Type type, const isc::asiolink::IOAddress& hint,
239
                              bool anypool /* true */) const {
240
241
242
243
    // check if the type is valid (and throw if it isn't)
    checkType(type);

    const PoolCollection& pools = getPools(type);
244
245

    PoolPtr candidate;
246

247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
    if (!pools.empty()) {
        // Pools are sorted by their first prefixes. For example: 2001::,
        // 2001::db8::, 3000:: etc. If our hint is 2001:db8:5:: we want to
        // find the pool with the longest matching prefix, so: 2001:db8::,
        // rather than 2001::. upper_bound returns the first pool with a prefix
        // that is greater than 2001:db8:5::, i.e. 3000::. To find the longest
        // matching prefix we use decrement operator to go back by one item.
        // If returned iterator points to begin it means that prefixes in all
        // pools are greater than out prefix, and thus there is no match.
        PoolCollection::const_iterator ub =
            std::upper_bound(pools.begin(), pools.end(), hint,
                             prefixLessThanFirstAddress);

        if (ub != pools.begin()) {
            --ub;
            if ((*ub)->inRange(hint)) {
                candidate = *ub;
            }
265
266
        }

267
268
269
        // If we don't find anything better, then let's just use the first pool
        if (!candidate && anypool) {
            candidate = *pools.begin();
270
271
        }
    }
272
273

    // Return a pool or NULL if no match found.
274
275
276
    return (candidate);
}

277
278
void
Subnet::addPool(const PoolPtr& pool) {
279
280
281
    // check if the type is valid (and throw if it isn't)
    checkType(pool->getType());

282
283
284
285
286
287
288
289
290
291
    // Check that the pool is in range with a subnet only if this is
    // not a pool of IPv6 prefixes. The IPv6 prefixes delegated for
    // the particular subnet don't need to match the prefix of the
    // subnet.
    if (pool->getType() != Lease::TYPE_PD) {
        if (!inRange(pool->getFirstAddress()) || !inRange(pool->getLastAddress())) {
            isc_throw(BadValue, "a pool of type "
                      << Lease::typeToText(pool->getType())
                      << ", with the following address range: "
                      << pool->getFirstAddress() << "-"
292
                      << pool->getLastAddress() << " does not match"
293
294
295
                      << " the prefix of a subnet: "
                      << prefix_ << "/" << static_cast<int>(prefix_len_)
                      << " to which it is being added");
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
    bool overlaps = false;
    if (pool->getType() == Lease::TYPE_V4) {
        overlaps = poolOverlaps(Lease::TYPE_V4, pool);

    } else {
        overlaps =
            poolOverlaps(Lease::TYPE_NA, pool) ||
            poolOverlaps(Lease::TYPE_PD, pool) ||
            poolOverlaps(Lease::TYPE_TA, pool);
    }

    if (overlaps) {
        isc_throw(BadValue,"a pool of type "
                  << Lease::typeToText(pool->getType())
                  << ", with the following address range: "
                  << pool->getFirstAddress() << "-"
                  << pool->getLastAddress() << " overlaps with "
                  "an existing pool in the subnet: "
                  << prefix_ << "/" << static_cast<int>(prefix_len_)
                  << " to which it is being added");
    }

    PoolCollection& pools_writable = getPoolsWritable(pool->getType());
323

324
    // Add the pool to the appropriate pools collection
325
326
327
328
329
    pools_writable.push_back(pool);

    // Sort pools by first address.
    std::sort(pools_writable.begin(), pools_writable.end(),
              comparePoolFirstAddress);
330
331
}

332
333
void
Subnet::delPools(Lease::Type type) {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
334
    getPoolsWritable(type).clear();
335
336
}

337
bool
338
Subnet::inPool(Lease::Type type, const isc::asiolink::IOAddress& addr) const {
339
340

    // Let's start with checking if it even belongs to that subnet.
Francis Dupont's avatar
Francis Dupont committed
341
    if ((type != Lease::TYPE_PD) && !inRange(addr)) {
342
343
344
        return (false);
    }

345
346
347
348
    const PoolCollection& pools = getPools(type);

    for (PoolCollection::const_iterator pool = pools.begin();
         pool != pools.end(); ++pool) {
349
350
351
352
        if ((*pool)->inRange(addr)) {
            return (true);
        }
    }
353
    // There's no pool that address belongs to
354
355
356
    return (false);
}

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
bool
Subnet::poolOverlaps(const Lease::Type& pool_type, const PoolPtr& pool) const {
    const PoolCollection& pools = getPools(pool_type);

    // If no pools, we don't overlap. Nothing to do.
    if (pools.empty()) {
        return (false);
    }

    // We're going to insert a new pool, likely between two existing pools.
    // So we're going to end up with the following case:
    // |<---- pool1 ---->|    |<-------- pool2 ------>|  |<-- pool3 -->|
    // F1               L1    F2                     L2  F3           L3
    // where pool1 and pool3 are existing pools, pool2 is a pool being
    // inserted and "F"/"L" mark first and last address in the pools
    // respectively. So the following conditions must be fulfilled:
    // F2 > L1 and L2 < F3. Obviously, for any pool: F < L.

    // Search for pool3. We use F2 and upper_bound to find the F3 (upper_bound
    // returns first pool in the sorted container which first address is
    // greater than F2). prefixLessThanPoolAddress with the first argument
    // set to "true" is the custom comparison function for upper_bound, which
    // compares F2 with the first addresses of the existing pools.
    PoolCollection::const_iterator pool3_it =
        std::upper_bound(pools.begin(), pools.end(), pool->getFirstAddress(),
                         prefixLessThanFirstAddress);

    // upper_bound returns a first pool which first address is greater than the
    // address F2. However, it is also possible that there is a pool which first
    // address is equal to F2. Such pool is also in conflict with a new pool.
    // If the returned value is pools.begin() it means that all pools have greater
    // first address than F2, thus none of the pools can have first address equal
    // to F2. Otherwise, we'd need to check them for equality.
    if (pool3_it != pools.begin()) {
        // Go back one pool and check if addresses are equal.
        PoolPtr pool3 = *(pool3_it - 1);
        if (pool3->getFirstAddress() == pool->getFirstAddress()) {
            return (true);
        }
    }

    // If returned value is unequal pools.end() it means that there is a pool3,
    // with F3 > F2.
    if (pool3_it != pools.end()) {
        // Let's store the pointer to this pool.
        PoolPtr pool3 = *pool3_it;
        // F3 must be greater than L2, otherwise pools will overlap.
        if (pool3->getFirstAddress() <= pool->getLastAddress()) {
            return (true);
        }
    }

    // If L2 is ok, we now have to find the pool1. This pool should be
    // right before the pool3 if there is any pool before pool3.
    if (pool3_it != pools.begin()) {
        PoolPtr pool1 = *(pool3_it - 1);
        // F2 must be greater than L1.
        if (pool->getFirstAddress() <= pool1->getLastAddress()) {
            return (true);
        }
    }

    return (false);
}


423
424
425
426
Subnet6::Subnet6(const isc::asiolink::IOAddress& prefix, uint8_t length,
                 const Triplet<uint32_t>& t1,
                 const Triplet<uint32_t>& t2,
                 const Triplet<uint32_t>& preferred_lifetime,
427
428
                 const Triplet<uint32_t>& valid_lifetime,
                 const SubnetID id)
429
    : Subnet(prefix, length, id), Network6() {
430
    if (!prefix.isV6()) {
431
        isc_throw(BadValue, "Non IPv6 prefix " << prefix
432
433
                  << " specified in subnet6");
    }
434
435
436
437
438
439

    // Relay info.
    setRelayInfo(RelayInfo(IOAddress::IPV6_ZERO_ADDRESS()));
    // Timers.
    setT1(t1);
    setT2(t2);
440
    setPreferred(preferred_lifetime);
441
    setValid(valid_lifetime);
442
443
}

444
445
446
447
448
449
void Subnet6::checkType(Lease::Type type) const {
    if ( (type != Lease::TYPE_NA) && (type != Lease::TYPE_TA) &&
         (type != Lease::TYPE_PD)) {
        isc_throw(BadValue, "Invalid Pool type: " << Lease::typeToText(type)
                  << "(" << static_cast<int>(type)
                  << "), must be TYPE_NA, TYPE_TA or TYPE_PD for Subnet6");
450
451
452
    }
}

453
454
455
456
457
458
459
460
461
462
463
bool
Subnet6::clientSupported(const isc::dhcp::ClientClasses& client_classes) const {
    NetworkPtr network;
    getSharedNetwork(network);
    if (network && !network->clientSupported(client_classes)) {
        return (false);
    }

    return (Network6::clientSupported(client_classes));
}

464
data::ElementPtr
465
Subnet::toElement() const {
466
    ElementPtr map = Element::createMap();
467

468
469
470
    // Set subnet id
    SubnetID id = getID();
    map->set("id", Element::create(static_cast<long long>(id)));
471

472
473
    // Set subnet
    map->set("subnet", Element::create(toText()));
474

Francis Dupont's avatar
Francis Dupont committed
475
    // Add user-context, but only if defined. Omit if it was not.
476
477
478
479
480
    ConstElementPtr ctx = getContext();
    if (ctx) {
        map->set("user-context", ctx);
    }

481
482
483
484
485
486
487
    return (map);
}

data::ElementPtr
Subnet4::toElement() const {
    // Prepare the map
    ElementPtr map = Subnet::toElement();
488
    ElementPtr network_map = Network4::toElement();
489

490
    merge(map, network_map);
491
492
493
494
495
496
497
498

    // Set DHCP4o6
    const Cfg4o6& d4o6 = get4o6();
    isc::data::merge(map, d4o6.toElement());

    // Set next-server
    map->set("next-server", Element::create(getSiaddr().toText()));

499
500
501
502
503
    // Set pools
    const PoolCollection& pools = getPools(Lease::TYPE_V4);
    ElementPtr pool_list = Element::createList();
    for (PoolCollection::const_iterator pool = pools.cbegin();
         pool != pools.cend(); ++pool) {
504
505
        // Add the elementized pool to the list
        pool_list->add((*pool)->toElement());
506
507
508
509
510
511
512
513
514
    }
    map->set("pools", pool_list);

    return (map);
}

data::ElementPtr
Subnet6::toElement() const {
    // Prepare the map
515
    ElementPtr map = Subnet::toElement();
516
    ElementPtr network_map = Network6::toElement();
517

518
    merge(map, network_map);
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
    // Set pools
    const PoolCollection& pools = getPools(Lease::TYPE_NA);
    ElementPtr pool_list = Element::createList();
    for (PoolCollection::const_iterator pool = pools.cbegin();
         pool != pools.cend(); ++pool) {
        // Prepare the map for a pool (@todo move this code to pool.cc)
        ElementPtr pool_map = Element::createMap();
        // Set pool
        const IOAddress& first = (*pool)->getFirstAddress();
        const IOAddress& last = (*pool)->getLastAddress();
        std::string range = first.toText() + "-" + last.toText();
        // Try to output a prefix (vs a range)
        int prefix_len = prefixLengthFromRange(first, last);
        if (prefix_len >= 0) {
            std::ostringstream oss;
            oss << first.toText() << "/" << prefix_len;
            range = oss.str();
        }
        pool_map->set("pool", Element::create(range));
        // Set user-context
        ConstElementPtr context = (*pool)->getContext();
        if (!isNull(context)) {
            pool_map->set("user-context", context);
        }
        // Set pool options
        ConstCfgOptionPtr opts = (*pool)->getCfgOption();
        pool_map->set("option-data", opts->toElement());
        // Push on the pool list
        pool_list->add(pool_map);
    }
    map->set("pools", pool_list);
    // Set pd-pools
    const PoolCollection& pdpools = getPools(Lease::TYPE_PD);
    ElementPtr pdpool_list = Element::createList();
    for (PoolCollection::const_iterator pool = pdpools.cbegin();
         pool != pdpools.cend(); ++pool) {
        // Get it as a Pool6 (@todo move this code to pool.cc)
        const Pool6* pdpool = dynamic_cast<Pool6*>(pool->get());
        if (!pdpool) {
            isc_throw(ToElementError, "invalid pd-pool pointer");
        }
        // Prepare the map for a pd-pool
        ElementPtr pool_map = Element::createMap();
        // Set prefix
        const IOAddress& prefix = pdpool->getFirstAddress();
        pool_map->set("prefix", Element::create(prefix.toText()));
        // Set prefix-len (get it from min - max)
        const IOAddress& last = pdpool->getLastAddress();
        int prefix_len = prefixLengthFromRange(prefix, last);
        if (prefix_len < 0) {
            // The pool is bad: give up
            isc_throw(ToElementError, "invalid prefix range "
                      << prefix.toText() << "-" << last.toText());
        }
        pool_map->set("prefix-len", Element::create(prefix_len));
        // Set delegated-len
        uint8_t len = pdpool->getLength();
        pool_map->set("delegated-len",
                      Element::create(static_cast<int>(len)));
579

580
581
582
583
584
585
586
587
588
589
590
591
        // Set excluded prefix
        const Option6PDExcludePtr& xopt =
            pdpool->getPrefixExcludeOption();
        if (xopt) {
            const IOAddress& xprefix =
                xopt->getExcludedPrefix(prefix, len);
            pool_map->set("excluded-prefix",
                          Element::create(xprefix.toText()));
            uint8_t xlen = xopt->getExcludedPrefixLength();
            pool_map->set("excluded-prefix-len",
                          Element::create(static_cast<int>(xlen)));
        }
592

593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
        // Set user-context
        ConstElementPtr context = pdpool->getContext();
        if (!isNull(context)) {
            pool_map->set("user-context", context);
        }
        // Set pool options
        ConstCfgOptionPtr opts = pdpool->getCfgOption();
        pool_map->set("option-data", opts->toElement());
        // Push on the pool list
        pdpool_list->add(pool_map);
    }
    map->set("pd-pools", pdpool_list);

    return (map);
}


610
611
} // end of isc::dhcp namespace
} // end of isc namespace