Kea  1.5.0
alloc_engine.cc
Go to the documentation of this file.
1 // Copyright (C) 2012-2018 Internet Systems Consortium, Inc. ("ISC")
2 //
3 // This Source Code Form is subject to the terms of the Mozilla Public
4 // License, v. 2.0. If a copy of the MPL was not distributed with this
5 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
6 
7 #include <config.h>
8 
9 #include <dhcp/dhcp6.h>
10 #include <dhcp/pkt4.h>
11 #include <dhcp/pkt6.h>
12 #include <dhcp_ddns/ncr_msg.h>
13 #include <dhcpsrv/alloc_engine.h>
15 #include <dhcpsrv/cfgmgr.h>
16 #include <dhcpsrv/dhcpsrv_log.h>
17 #include <dhcpsrv/host_mgr.h>
18 #include <dhcpsrv/host.h>
20 #include <dhcpsrv/ncr_generator.h>
21 #include <dhcpsrv/network.h>
22 #include <dhcpsrv/shared_network.h>
23 #include <hooks/callout_handle.h>
24 #include <hooks/hooks_manager.h>
26 #include <stats/stats_mgr.h>
27 #include <util/stopwatch.h>
28 #include <hooks/server_hooks.h>
29 #include <hooks/hooks_manager.h>
30 
31 #include <boost/foreach.hpp>
32 
33 #include <algorithm>
34 #include <cstring>
35 #include <sstream>
36 #include <limits>
37 #include <vector>
38 #include <stdint.h>
39 #include <string.h>
40 #include <utility>
41 
42 using namespace isc::asiolink;
43 using namespace isc::dhcp;
44 using namespace isc::dhcp_ddns;
45 using namespace isc::hooks;
46 using namespace isc::stats;
47 
48 namespace {
49 
51 struct AllocEngineHooks {
52  int hook_index_lease4_select_;
53  int hook_index_lease4_renew_;
54  int hook_index_lease4_expire_;
55  int hook_index_lease4_recover_;
56  int hook_index_lease6_select_;
57  int hook_index_lease6_renew_;
58  int hook_index_lease6_rebind_;
59  int hook_index_lease6_expire_;
60  int hook_index_lease6_recover_;
61 
63  AllocEngineHooks() {
64  hook_index_lease4_select_ = HooksManager::registerHook("lease4_select");
65  hook_index_lease4_renew_ = HooksManager::registerHook("lease4_renew");
66  hook_index_lease4_expire_ = HooksManager::registerHook("lease4_expire");
67  hook_index_lease4_recover_= HooksManager::registerHook("lease4_recover");
68  hook_index_lease6_select_ = HooksManager::registerHook("lease6_select");
69  hook_index_lease6_renew_ = HooksManager::registerHook("lease6_renew");
70  hook_index_lease6_rebind_ = HooksManager::registerHook("lease6_rebind");
71  hook_index_lease6_expire_ = HooksManager::registerHook("lease6_expire");
72  hook_index_lease6_recover_= HooksManager::registerHook("lease6_recover");
73  }
74 };
75 
76 // Declare a Hooks object. As this is outside any function or method, it
77 // will be instantiated (and the constructor run) when the module is loaded.
78 // As a result, the hook indexes will be defined before any method in this
79 // module is called.
80 AllocEngineHooks Hooks;
81 
82 }; // anonymous namespace
83 
84 namespace isc {
85 namespace dhcp {
86 
87 AllocEngine::IterativeAllocator::IterativeAllocator(Lease::Type lease_type)
88  :Allocator(lease_type) {
89 }
90 
93  const uint8_t prefix_len) {
94  if (!prefix.isV6()) {
95  isc_throw(BadValue, "Prefix operations are for IPv6 only (attempted to "
96  "increase prefix " << prefix << ")");
97  }
98 
99  // Get a buffer holding an address.
100  const std::vector<uint8_t>& vec = prefix.toBytes();
101 
102  if (prefix_len < 1 || prefix_len > 128) {
103  isc_throw(BadValue, "Cannot increase prefix: invalid prefix length: "
104  << prefix_len);
105  }
106 
107  // Brief explanation what happens here:
108  // http://www.youtube.com/watch?v=NFQCYpIHLNQ
109 
110  uint8_t n_bytes = (prefix_len - 1)/8;
111  uint8_t n_bits = 8 - (prefix_len - n_bytes*8);
112  uint8_t mask = 1 << n_bits;
113 
114  // Longer explanation: n_bytes specifies number of full bytes that are
115  // in-prefix. They can also be used as an offset for the first byte that
116  // is not in prefix. n_bits specifies number of bits on the last byte that
117  // is (often partially) in prefix. For example for a /125 prefix, the values
118  // are 15 and 3, respectively. Mask is a bitmask that has the least
119  // significant bit from the prefix set.
120 
121  uint8_t packed[V6ADDRESS_LEN];
122 
123  // Copy the address. It must be V6, but we already checked that.
124  std::memcpy(packed, &vec[0], V6ADDRESS_LEN);
125 
126  // Can we safely increase only the last byte in prefix without overflow?
127  if (packed[n_bytes] + uint16_t(mask) < 256u) {
128  packed[n_bytes] += mask;
129  return (IOAddress::fromBytes(AF_INET6, packed));
130  }
131 
132  // Overflow (done on uint8_t, but the sum is greater than 255)
133  packed[n_bytes] += mask;
134 
135  // Deal with the overflow. Start increasing the least significant byte
136  for (int i = n_bytes - 1; i >= 0; --i) {
137  ++packed[i];
138  // If we haven't overflowed (0xff->0x0) the next byte, then we are done
139  if (packed[i] != 0) {
140  break;
141  }
142  }
143 
144  return (IOAddress::fromBytes(AF_INET6, packed));
145 }
146 
149  bool prefix,
150  const uint8_t prefix_len) {
151  if (!prefix) {
152  return (IOAddress::increase(address));
153  } else {
154  return (increasePrefix(address, prefix_len));
155  }
156 }
157 
160  const ClientClasses& client_classes,
161  const DuidPtr&,
162  const IOAddress&) {
163 
164  // Is this prefix allocation?
165  bool prefix = pool_type_ == Lease::TYPE_PD;
166  uint8_t prefix_len = 0;
167 
168  // Let's get the last allocated address. It is usually set correctly,
169  // but there are times when it won't be (like after removing a pool or
170  // perhaps restarting the server).
171  IOAddress last = subnet->getLastAllocated(pool_type_);
172  bool valid = true;
173  bool retrying = false;
174 
175  const PoolCollection& pools = subnet->getPools(pool_type_);
176 
177  if (pools.empty()) {
178  isc_throw(AllocFailed, "No pools defined in selected subnet");
179  }
180 
181  // first we need to find a pool the last address belongs to.
182  PoolCollection::const_iterator it;
183  PoolCollection::const_iterator first = pools.end();
184  PoolPtr first_pool;
185  for (it = pools.begin(); it != pools.end(); ++it) {
186  if (!(*it)->clientSupported(client_classes)) {
187  continue;
188  }
189  if (first == pools.end()) {
190  first = it;
191  }
192  if ((*it)->inRange(last)) {
193  break;
194  }
195  }
196 
197  // Caller checked this cannot happen
198  if (first == pools.end()) {
199  isc_throw(AllocFailed, "No allowed pools defined in selected subnet");
200  }
201 
202  // last one was bogus for one of several reasons:
203  // - we just booted up and that's the first address we're allocating
204  // - a subnet was removed or other reconfiguration just completed
205  // - perhaps allocation algorithm was changed
206  // - last pool does not allow this client
207  if (it == pools.end()) {
208  it = first;
209  }
210 
211  for (;;) {
212  // Trying next pool
213  if (retrying) {
214  for (; it != pools.end(); ++it) {
215  if ((*it)->clientSupported(client_classes)) {
216  break;
217  }
218  }
219  if (it == pools.end()) {
220  // Really out of luck today. That was the last pool.
221  break;
222  }
223  }
224 
225  last = (*it)->getLastAllocated();
226  valid = (*it)->isLastAllocatedValid();
227  if (!valid && (last == (*it)->getFirstAddress())) {
228  // Pool was (re)initialized
229  (*it)->setLastAllocated(last);
230  subnet->setLastAllocated(pool_type_, last);
231  return (last);
232  }
233  // still can be bogus
234  if (valid && !(*it)->inRange(last)) {
235  valid = false;
236  (*it)->resetLastAllocated();
237  (*it)->setLastAllocated((*it)->getFirstAddress());
238  }
239 
240  if (valid) {
241  // Ok, we have a pool that the last address belonged to, let's use it.
242  if (prefix) {
243  Pool6Ptr pool6 = boost::dynamic_pointer_cast<Pool6>(*it);
244 
245  if (!pool6) {
246  // Something is gravely wrong here
247  isc_throw(Unexpected, "Wrong type of pool: "
248  << (*it)->toText()
249  << " is not Pool6");
250  }
251  // Get the prefix length
252  prefix_len = pool6->getLength();
253  }
254 
255  IOAddress next = increaseAddress(last, prefix, prefix_len);
256  if ((*it)->inRange(next)) {
257  // the next one is in the pool as well, so we haven't hit
258  // pool boundary yet
259  (*it)->setLastAllocated(next);
260  subnet->setLastAllocated(pool_type_, next);
261  return (next);
262  }
263 
264  valid = false;
265  (*it)->resetLastAllocated();
266  }
267  // We hit pool boundary, let's try to jump to the next pool and try again
268  ++it;
269  retrying = true;
270  }
271 
272  // Let's rewind to the beginning.
273  for (it = first; it != pools.end(); ++it) {
274  if ((*it)->clientSupported(client_classes)) {
275  (*it)->setLastAllocated((*it)->getFirstAddress());
276  (*it)->resetLastAllocated();
277  }
278  }
279 
280  // ok to access first element directly. We checked that pools is non-empty
281  last = (*first)->getLastAllocated();
282  (*first)->setLastAllocated(last);
283  subnet->setLastAllocated(pool_type_, last);
284  return (last);
285 }
286 
288  :Allocator(lease_type) {
289  isc_throw(NotImplemented, "Hashed allocator is not implemented");
290 }
291 
292 
295  const ClientClasses&,
296  const DuidPtr&,
297  const IOAddress&) {
298  isc_throw(NotImplemented, "Hashed allocator is not implemented");
299 }
300 
302  :Allocator(lease_type) {
303  isc_throw(NotImplemented, "Random allocator is not implemented");
304 }
305 
306 
309  const ClientClasses&,
310  const DuidPtr&,
311  const IOAddress&) {
312  isc_throw(NotImplemented, "Random allocator is not implemented");
313 }
314 
315 
316 AllocEngine::AllocEngine(AllocType engine_type, uint64_t attempts,
317  bool ipv6)
318  : attempts_(attempts), incomplete_v4_reclamations_(0),
319  incomplete_v6_reclamations_(0) {
320 
321  // Choose the basic (normal address) lease type
322  Lease::Type basic_type = ipv6 ? Lease::TYPE_NA : Lease::TYPE_V4;
323 
324  // Initialize normal address allocators
325  switch (engine_type) {
326  case ALLOC_ITERATIVE:
327  allocators_[basic_type] = AllocatorPtr(new IterativeAllocator(basic_type));
328  break;
329  case ALLOC_HASHED:
330  allocators_[basic_type] = AllocatorPtr(new HashedAllocator(basic_type));
331  break;
332  case ALLOC_RANDOM:
333  allocators_[basic_type] = AllocatorPtr(new RandomAllocator(basic_type));
334  break;
335  default:
336  isc_throw(BadValue, "Invalid/unsupported allocation algorithm");
337  }
338 
339  // If this is IPv6 allocation engine, initialize also temporary addrs
340  // and prefixes
341  if (ipv6) {
342  switch (engine_type) {
343  case ALLOC_ITERATIVE:
346  break;
347  case ALLOC_HASHED:
350  break;
351  case ALLOC_RANDOM:
354  break;
355  default:
356  isc_throw(BadValue, "Invalid/unsupported allocation algorithm");
357  }
358  }
359 
360  // Register hook points
361  hook_index_lease4_select_ = Hooks.hook_index_lease4_select_;
362  hook_index_lease6_select_ = Hooks.hook_index_lease6_select_;
363 }
364 
366  std::map<Lease::Type, AllocatorPtr>::const_iterator alloc = allocators_.find(type);
367 
368  if (alloc == allocators_.end()) {
369  isc_throw(BadValue, "No allocator initialized for pool type "
370  << Lease::typeToText(type));
371  }
372  return (alloc->second);
373 }
374 
375 } // end of namespace isc::dhcp
376 } // end of namespace isc
377 
378 namespace {
379 
392 bool
393 inAllowedPool(AllocEngine::ClientContext6& ctx, const Lease::Type& lease_type,
394  const IOAddress& address, bool check_subnet) {
395  // If the subnet belongs to a shared network we will be iterating
396  // over the subnets that belong to this shared network.
397  Subnet6Ptr current_subnet = ctx.subnet_;
398  while (current_subnet) {
399 
400  if (current_subnet->clientSupported(ctx.query_->getClasses())) {
401  if (check_subnet) {
402  if (current_subnet->inPool(lease_type, address)) {
403  return (true);
404  }
405  } else {
406  if (current_subnet->inPool(lease_type, address,
407  ctx.query_->getClasses())) {
408  return (true);
409  }
410  }
411  }
412 
413  current_subnet = current_subnet->getNextSubnet(ctx.subnet_);
414  }
415 
416  return (false);
417 }
418 
419 }
420 
421 
422 // ##########################################################################
423 // # DHCPv6 lease allocation code starts here.
424 // ##########################################################################
425 
426 namespace isc {
427 namespace dhcp {
428 
430  : query_(), fake_allocation_(false), subnet_(), host_subnet_(), duid_(),
431  hwaddr_(), host_identifiers_(), hosts_(), fwd_dns_update_(false),
432  rev_dns_update_(false), hostname_(), callout_handle_(), ias_() {
433 }
434 
436  const DuidPtr& duid,
437  const bool fwd_dns,
438  const bool rev_dns,
439  const std::string& hostname,
440  const bool fake_allocation,
441  const Pkt6Ptr& query,
442  const CalloutHandlePtr& callout_handle)
443  : query_(query), fake_allocation_(fake_allocation), subnet_(subnet),
444  duid_(duid), hwaddr_(), host_identifiers_(), hosts_(),
445  fwd_dns_update_(fwd_dns), rev_dns_update_(rev_dns), hostname_(hostname),
446  callout_handle_(callout_handle), allocated_resources_(), new_leases_(),
447  ias_() {
448 
449  // Initialize host identifiers.
450  if (duid) {
451  addHostIdentifier(Host::IDENT_DUID, duid->getDuid());
452  }
453 }
454 
456  : iaid_(0), type_(Lease::TYPE_NA), hints_(), old_leases_(),
457  changed_leases_(), ia_rsp_() {
458 }
459 
460 void
463  const uint8_t prefix_len) {
464  hints_.push_back(std::make_pair(prefix, prefix_len));
465 }
466 
467 void
470  const uint8_t prefix_len) {
471  static_cast<void>(allocated_resources_.insert(std::make_pair(prefix,
472  prefix_len)));
473 }
474 
475 bool
477 isAllocated(const asiolink::IOAddress& prefix, const uint8_t prefix_len) const {
478  return (static_cast<bool>
479  (allocated_resources_.count(std::make_pair(prefix, prefix_len))));
480 }
481 
485  if (subnet) {
486  SubnetID id = (subnet_->getHostReservationMode() == Network::HR_GLOBAL ?
487  SUBNET_ID_GLOBAL : subnet->getID());
488 
489  auto host = hosts_.find(id);
490  if (host != hosts_.cend()) {
491  return (host->second);
492  }
493  }
494 
495  return (ConstHostPtr());
496 }
497 
501  if (subnet && subnet_->getHostReservationMode() == Network::HR_GLOBAL) {
502  auto host = hosts_.find(SUBNET_ID_GLOBAL);
503  if (host != hosts_.cend()) {
504  return (host->second);
505  }
506  }
507 
508  return (ConstHostPtr());
509 }
510 
511 bool
513  ConstHostPtr ghost = globalHost();
514  return (ghost && ghost->hasReservation(resv));
515 }
516 
518  ctx.hosts_.clear();
519 
520  // If there is no subnet, there is nothing to do.
521  if (!ctx.subnet_) {
522  return;
523  }
524 
525  auto subnet = ctx.subnet_;
526 
527  std::map<SubnetID, ConstHostPtr> host_map;
528  SharedNetwork6Ptr network;
529  subnet->getSharedNetwork(network);
530 
531  if (subnet->getHostReservationMode() == Network::HR_GLOBAL) {
532  ConstHostPtr ghost = findGlobalReservation(ctx);
533  if (ghost) {
534  ctx.hosts_[SUBNET_ID_GLOBAL] = ghost;
535 
536  // @todo In theory, to support global as part of HR_ALL,
537  // we would just keep going, instead of returning.
538  return;
539  }
540  }
541 
542  // If the subnet belongs to a shared network it is usually going to be
543  // more efficient to make a query for all reservations for a particular
544  // client rather than a query for each subnet within this shared network.
545  // The only case when it is going to be less efficient is when there are
546  // more host identifier types in use than subnets within a shared network.
547  const bool use_single_query = network &&
548  (network->getAllSubnets()->size() > ctx.host_identifiers_.size());
549 
550  if (use_single_query) {
551  for (auto id_pair : ctx.host_identifiers_) {
552  ConstHostCollection hosts = HostMgr::instance().getAll(id_pair.first,
553  &id_pair.second[0],
554  id_pair.second.size());
555  // Store the hosts in the temporary map, because some hosts may
556  // belong to subnets outside of the shared network. We'll need
557  // to eliminate them.
558  for (auto host = hosts.begin(); host != hosts.end(); ++host) {
559  if ((*host)->getIPv6SubnetID()) {
560  host_map[(*host)->getIPv6SubnetID()] = *host;
561  }
562  }
563  }
564  }
565 
566  // We can only search for the reservation if a subnet has been selected.
567  while (subnet) {
568 
569  // Only makes sense to get reservations if the client has access
570  // to the class and host reservations are enabled.
571  if (subnet->clientSupported(ctx.query_->getClasses()) &&
572  (subnet->getHostReservationMode() != Network::HR_DISABLED)) {
573  // Iterate over configured identifiers in the order of preference
574  // and try to use each of them to search for the reservations.
575  for (auto id_pair : ctx.host_identifiers_) {
576  if (use_single_query) {
577  if (host_map.count(subnet->getID()) > 0) {
578  ctx.hosts_[subnet->getID()] = host_map[subnet->getID()];
579  }
580 
581  } else {
582  // Attempt to find a host using a specified identifier.
583  ConstHostPtr host = HostMgr::instance().get6(subnet->getID(),
584  id_pair.first,
585  &id_pair.second[0],
586  id_pair.second.size());
587  // If we found matching host for this subnet.
588  if (host) {
589  ctx.hosts_[subnet->getID()] = host;
590  break;
591  }
592  }
593  }
594 
595  }
596 
597  // We need to get to the next subnet if this is a shared network. If it
598  // is not (a plain subnet), getNextSubnet will return NULL and we're
599  // done here.
600  subnet = subnet->getNextSubnet(ctx.subnet_, ctx.query_->getClasses());
601  }
602 }
603 
606  ConstHostPtr host;
607  BOOST_FOREACH(const IdentifierPair& id_pair, ctx.host_identifiers_) {
608  // Attempt to find a host using a specified identifier.
609  host = HostMgr::instance().get6(SUBNET_ID_GLOBAL, id_pair.first,
610  &id_pair.second[0], id_pair.second.size());
611 
612  // If we found matching global host we're done.
613  if (host) {
614  break;
615  }
616  }
617 
618  return (host);
619 }
620 
621 
624 
625  try {
626  if (!ctx.subnet_) {
627  isc_throw(InvalidOperation, "Subnet is required for IPv6 lease allocation");
628  } else
629  if (!ctx.duid_) {
630  isc_throw(InvalidOperation, "DUID is mandatory for IPv6 lease allocation");
631  }
632 
633  // Check if there are existing leases for that shared network and
634  // DUID/IAID.
635  Subnet6Ptr subnet = ctx.subnet_;
636  Lease6Collection all_leases =
638  *ctx.duid_,
639  ctx.currentIA().iaid_);
640 
641  // Iterate over the leases and eliminate those that are outside of
642  // our shared network.
643  Lease6Collection leases;
644  while (subnet) {
645  for (auto l : all_leases) {
646  if ((l)->subnet_id_ == subnet->getID()) {
647  leases.push_back(l);
648  }
649  }
650 
651  subnet = subnet->getNextSubnet(ctx.subnet_);
652  }
653 
654  // Now do the checks:
655  // Case 1. if there are no leases, and there are reservations...
656  // 1.1. are the reserved addresses are used by someone else?
657  // yes: we have a problem
658  // no: assign them => done
659  // Case 2. if there are leases and there are no reservations...
660  // 2.1 are the leases reserved for someone else?
661  // yes: release them, assign something else
662  // no: renew them => done
663  // Case 3. if there are leases and there are reservations...
664  // 3.1 are the leases matching reservations?
665  // yes: renew them => done
666  // no: release existing leases, assign new ones based on reservations
667  // Case 4/catch-all. if there are no leases and no reservations...
668  // assign new leases
669 
670  // Case 1: There are no leases and there's a reservation for this host.
671  if (leases.empty() && !ctx.hosts_.empty()) {
672 
674  ALLOC_ENGINE_V6_ALLOC_NO_LEASES_HR)
675  .arg(ctx.query_->getLabel());
676 
677  // Try to allocate leases that match reservations. Typically this will
678  // succeed, except cases where the reserved addresses are used by
679  // someone else.
680  allocateReservedLeases6(ctx, leases);
681 
682  // If not, we'll need to continue and will eventually fall into case 4:
683  // getting a regular lease. That could happen when we're processing
684  // request from client X, there's a reserved address A for X, but
685  // A is currently used by client Y. We can't immediately reassign A
686  // from X to Y, because Y keeps using it, so X would send Decline right
687  // away. Need to wait till Y renews, then we can release A, so it
688  // will become available for X.
689 
690  // Case 2: There are existing leases and there are no reservations.
691  //
692  // There is at least one lease for this client and there are no reservations.
693  // We will return these leases for the client, but we may need to update
694  // FQDN information.
695  } else if (!leases.empty() && ctx.hosts_.empty()) {
696 
698  ALLOC_ENGINE_V6_ALLOC_LEASES_NO_HR)
699  .arg(ctx.query_->getLabel());
700 
701  // Check if the existing leases are reserved for someone else.
702  // If they're not, we're ok to keep using them.
703  removeNonmatchingReservedLeases6(ctx, leases);
704 
705  leases = updateLeaseData(ctx, leases);
706 
707  // If leases are empty at this stage, it means that we used to have
708  // leases for this client, but we checked and those leases are reserved
709  // for someone else, so we lost them. We will need to continue and
710  // will finally end up in case 4 (no leases, no reservations), so we'll
711  // assign something new.
712 
713  // Case 3: There are leases and there are reservations.
714  } else if (!leases.empty() && !ctx.hosts_.empty()) {
715 
717  ALLOC_ENGINE_V6_ALLOC_LEASES_HR)
718  .arg(ctx.query_->getLabel());
719 
720  // First, check if have leases matching reservations, and add new
721  // leases if we don't have them.
722  allocateReservedLeases6(ctx, leases);
723 
724  // leases now contain both existing and new leases that were created
725  // from reservations.
726 
727  // Second, let's remove leases that are reserved for someone else.
728  // This applies to any existing leases. This will not happen frequently,
729  // but it may happen with the following chain of events:
730  // 1. client A gets address X;
731  // 2. reservation for client B for address X is made by a administrator;
732  // 3. client A reboots
733  // 4. client A requests the address (X) he got previously
734  removeNonmatchingReservedLeases6(ctx, leases);
735 
736  // leases now contain existing and new leases, but we removed those
737  // leases that are reserved for someone else (non-matching reserved).
738 
739  // There's one more check to do. Let's remove leases that are not
740  // matching reservations, i.e. if client X has address A, but there's
741  // a reservation for address B, we should release A and reassign B.
742  // Caveat: do this only if we have at least one reserved address.
743  removeNonreservedLeases6(ctx, leases);
744 
745  // All checks are done. Let's hope we have some leases left.
746 
747  // If we don't have any leases at this stage, it means that we hit
748  // one of the following cases:
749  // - we have a reservation, but it's not for this IAID/ia-type and
750  // we had to return the address we were using
751  // - we have a reservation for this iaid/ia-type, but the reserved
752  // address is currently used by someone else. We can't assign it
753  // yet.
754  // - we had an address, but we just discovered that it's reserved for
755  // someone else, so we released it.
756  }
757 
758  if (leases.empty()) {
759  // Case 4/catch-all: One of the following is true:
760  // - we don't have leases and there are no reservations
761  // - we used to have leases, but we lost them, because they are now
762  // reserved for someone else
763  // - we have a reservation, but it is not usable yet, because the address
764  // is still used by someone else
765  //
766  // In any case, we need to go through normal lease assignment process
767  // for now. This is also a catch-all or last resort approach, when we
768  // couldn't find any reservations (or couldn't use them).
769 
771  ALLOC_ENGINE_V6_ALLOC_UNRESERVED)
772  .arg(ctx.query_->getLabel());
773 
774  leases = allocateUnreservedLeases6(ctx);
775  }
776 
777  if (!leases.empty()) {
778  // If there are any leases allocated, let's store in them in the
779  // IA context so as they are available when we process subsequent
780  // IAs.
781  BOOST_FOREACH(Lease6Ptr lease, leases) {
782  ctx.addAllocatedResource(lease->addr_, lease->prefixlen_);
783  ctx.new_leases_.push_back(lease);
784  }
785  return (leases);
786  }
787 
788 
789  } catch (const isc::Exception& e) {
790 
791  // Some other error, return an empty lease.
792  LOG_ERROR(alloc_engine_logger, ALLOC_ENGINE_V6_ALLOC_ERROR)
793  .arg(ctx.query_->getLabel())
794  .arg(e.what());
795  }
796 
797  return (Lease6Collection());
798 }
799 
801 AllocEngine::allocateUnreservedLeases6(ClientContext6& ctx) {
802 
803  AllocatorPtr allocator = getAllocator(ctx.currentIA().type_);
804 
805  if (!allocator) {
806  isc_throw(InvalidOperation, "No allocator specified for "
807  << Lease6::typeToText(ctx.currentIA().type_));
808  }
809 
810  Lease6Collection leases;
811 
813  if (!ctx.currentIA().hints_.empty()) {
815  hint = ctx.currentIA().hints_[0].first;
816  }
817 
818  Subnet6Ptr original_subnet = ctx.subnet_;
819  Subnet6Ptr subnet = ctx.subnet_;
820 
821  Pool6Ptr pool;
822 
823  CalloutHandle::CalloutNextStep callout_status = CalloutHandle::NEXT_STEP_CONTINUE;
824 
825  while (subnet) {
826 
827  if (!subnet->clientSupported(ctx.query_->getClasses())) {
828  subnet = subnet->getNextSubnet(original_subnet);
829  continue;
830  }
831 
832  ctx.subnet_ = subnet;
833 
834  // check if the hint is in pool and is available
835  // This is equivalent of subnet->inPool(hint), but returns the pool
836  pool = boost::dynamic_pointer_cast<Pool6>
837  (subnet->getPool(ctx.currentIA().type_, ctx.query_->getClasses(),
838  hint));
839 
840  // check if the pool is allowed
841  if (pool && !pool->clientSupported(ctx.query_->getClasses())) {
842  pool.reset();
843  }
844 
845  if (pool) {
846 
847  // Check which host reservation mode is supported in this subnet.
848  Network::HRMode hr_mode = subnet->getHostReservationMode();
849 
851  Lease6Ptr lease =
852  LeaseMgrFactory::instance().getLease6(ctx.currentIA().type_, hint);
853  if (!lease) {
854 
855  // In-pool reservations: Check if this address is reserved for someone
856  // else. There is no need to check for whom it is reserved, because if
857  // it has been reserved for us we would have already allocated a lease.
858 
859  ConstHostPtr host;
860  if (hr_mode != Network::HR_DISABLED) {
861  host = HostMgr::instance().get6(subnet->getID(), hint);
862  }
863 
864  if (!host) {
865  // If the in-pool reservations are disabled, or there is no
866  // reservation for a given hint, we're good to go.
867 
868  // The hint is valid and not currently used, let's create a
869  // lease for it
870  lease = createLease6(ctx, hint, pool->getLength(), callout_status);
871 
872  // It can happen that the lease allocation failed (we could
873  // have lost the race condition. That means that the hint is
874  // no longer usable and we need to continue the regular
875  // allocation path.
876  if (lease) {
877 
879  Lease6Collection collection;
880  collection.push_back(lease);
881  return (collection);
882  }
883  } else {
885  ALLOC_ENGINE_V6_HINT_RESERVED)
886  .arg(ctx.query_->getLabel())
887  .arg(hint.toText());
888  }
889 
890  } else {
891 
892  // If the lease is expired, we may likely reuse it, but...
893  if (lease->expired()) {
894 
895  ConstHostPtr host;
896  if (hr_mode != Network::HR_DISABLED) {
897  host = HostMgr::instance().get6(subnet->getID(), hint);
898  }
899 
900  // Let's check if there is a reservation for this address.
901  if (!host) {
902 
903  // Copy an existing, expired lease so as it can be returned
904  // to the caller.
905  Lease6Ptr old_lease(new Lease6(*lease));
906  ctx.currentIA().old_leases_.push_back(old_lease);
907 
909  lease = reuseExpiredLease(lease, ctx, pool->getLength(),
910  callout_status);
911 
913  leases.push_back(lease);
914  return (leases);
915 
916  } else {
918  ALLOC_ENGINE_V6_EXPIRED_HINT_RESERVED)
919  .arg(ctx.query_->getLabel())
920  .arg(hint.toText());
921  }
922  }
923  }
924  }
925 
926  subnet = subnet->getNextSubnet(original_subnet);
927  }
928 
929  uint64_t total_attempts = 0;
930 
931  // Need to check if the subnet belongs to a shared network. If so,
932  // we might be able to find a better subnet for lease allocation,
933  // for which it is more likely that there are some leases available.
934  // If we stick to the selected subnet, we may end up walking over
935  // the entire subnet (or more subnets) to discover that the pools
936  // have been exhausted. Using a subnet from which a lease was
937  // assigned most recently is an optimization which increases
938  // the likelyhood of starting from the subnet which pools are not
939  // exhausted.
940  SharedNetwork6Ptr network;
941  original_subnet->getSharedNetwork(network);
942  if (network) {
943  // This would try to find a subnet with the same set of classes
944  // as the current subnet, but with the more recent "usage timestamp".
945  // This timestamp is only updated for the allocations made with an
946  // allocator (unreserved lease allocations), not the static
947  // allocations or requested addresses.
948  original_subnet = network->getPreferredSubnet(original_subnet, ctx.currentIA().type_);
949  }
950 
951  ctx.subnet_ = subnet = original_subnet;
952 
953  while (subnet) {
954 
955  if (!subnet->clientSupported(ctx.query_->getClasses())) {
956  subnet = subnet->getNextSubnet(original_subnet);
957  continue;
958  }
959 
960  // The hint was useless (it was not provided at all, was used by someone else,
961  // was out of pool or reserved for someone else). Search the pool until first
962  // of the following occurs:
963  // - we find a free address
964  // - we find an address for which the lease has expired
965  // - we exhaust number of tries
966  uint64_t possible_attempts =
967  subnet->getPoolCapacity(ctx.currentIA().type_,
968  ctx.query_->getClasses());
969  // Try next subnet if there is no chance to get something
970  if (possible_attempts == 0) {
971  subnet = subnet->getNextSubnet(original_subnet);
972  continue;
973  }
974  uint64_t max_attempts = (attempts_ > 0 ? attempts_ : possible_attempts);
975  Network::HRMode hr_mode = subnet->getHostReservationMode();
976 
977  // Set the default status code in case the lease6_select callouts
978  // do not exist and the callout handle has a status returned by
979  // any of the callouts already invoked for this packet.
980  if (ctx.callout_handle_) {
981  ctx.callout_handle_->setStatus(CalloutHandle::NEXT_STEP_CONTINUE);
982  }
983 
984  for (uint64_t i = 0; i < max_attempts; ++i) {
985 
986  ++total_attempts;
987 
988  IOAddress candidate = allocator->pickAddress(subnet,
989  ctx.query_->getClasses(),
990  ctx.duid_,
991  hint);
992 
996  if (hr_mode == Network::HR_ALL &&
997  HostMgr::instance().get6(subnet->getID(), candidate)) {
998 
999  // Don't allocate.
1000  continue;
1001  }
1002 
1003  // The first step is to find out prefix length. It is 128 for
1004  // non-PD leases.
1005  uint8_t prefix_len = 128;
1006  if (ctx.currentIA().type_ == Lease::TYPE_PD) {
1007  pool = boost::dynamic_pointer_cast<Pool6>(
1008  subnet->getPool(ctx.currentIA().type_,
1009  ctx.query_->getClasses(),
1010  candidate));
1011  if (pool) {
1012  prefix_len = pool->getLength();
1013  }
1014  }
1015 
1016  Lease6Ptr existing = LeaseMgrFactory::instance().getLease6(ctx.currentIA().type_,
1017  candidate);
1018  if (!existing) {
1019 
1020  // there's no existing lease for selected candidate, so it is
1021  // free. Let's allocate it.
1022 
1023  ctx.subnet_ = subnet;
1024  Lease6Ptr lease = createLease6(ctx, candidate, prefix_len, callout_status);
1025  if (lease) {
1026  // We are allocating a new lease (not renewing). So, the
1027  // old lease should be NULL.
1028  ctx.currentIA().old_leases_.clear();
1029 
1030  leases.push_back(lease);
1031  return (leases);
1032 
1033  } else if (ctx.callout_handle_ &&
1034  (callout_status != CalloutHandle::NEXT_STEP_CONTINUE)) {
1035  // Don't retry when the callout status is not continue.
1036  break;
1037  }
1038 
1039  // Although the address was free just microseconds ago, it may have
1040  // been taken just now. If the lease insertion fails, we continue
1041  // allocation attempts.
1042  } else {
1043  if (existing->expired()) {
1044  // Copy an existing, expired lease so as it can be returned
1045  // to the caller.
1046  Lease6Ptr old_lease(new Lease6(*existing));
1047  ctx.currentIA().old_leases_.push_back(old_lease);
1048 
1049  ctx.subnet_ = subnet;
1050  existing = reuseExpiredLease(existing, ctx, prefix_len,
1051  callout_status);
1052 
1053  leases.push_back(existing);
1054  return (leases);
1055  }
1056  }
1057  }
1058 
1059  subnet = subnet->getNextSubnet(original_subnet);
1060  }
1061 
1062  // Unable to allocate an address, return an empty lease.
1063  LOG_WARN(alloc_engine_logger, ALLOC_ENGINE_V6_ALLOC_FAIL)
1064  .arg(ctx.query_->getLabel())
1065  .arg(total_attempts);
1066 
1067  // We failed to allocate anything. Let's return empty collection.
1068  return (Lease6Collection());
1069 }
1070 
1071 void
1072 AllocEngine::allocateReservedLeases6(ClientContext6& ctx,
1073  Lease6Collection& existing_leases) {
1074 
1075  // If there are no reservations or the reservation is v4, there's nothing to do.
1076  if (ctx.hosts_.empty()) {
1078  ALLOC_ENGINE_V6_ALLOC_NO_V6_HR)
1079  .arg(ctx.query_->getLabel());
1080  return;
1081  }
1082 
1083  if (allocateGlobalReservedLeases6(ctx, existing_leases)) {
1084  // global reservation provided the lease, we're done
1085  return;
1086  }
1087 
1088  // Let's convert this from Lease::Type to IPv6Reserv::Type
1089  IPv6Resrv::Type type = ctx.currentIA().type_ == Lease::TYPE_NA ?
1091 
1092  // We want to avoid allocating new lease for an IA if there is already
1093  // a valid lease for which client has reservation. So, we first check if
1094  // we already have a lease for a reserved address or prefix.
1095  BOOST_FOREACH(const Lease6Ptr& lease, existing_leases) {
1096  if ((lease->valid_lft_ != 0)) {
1097  if ((ctx.hosts_.count(lease->subnet_id_) > 0) &&
1098  ctx.hosts_[lease->subnet_id_]->hasReservation(makeIPv6Resrv(*lease))) {
1099  // We found existing lease for a reserved address or prefix.
1100  // We'll simply extend the lifetime of the lease.
1102  ALLOC_ENGINE_V6_ALLOC_HR_LEASE_EXISTS)
1103  .arg(ctx.query_->getLabel())
1104  .arg(lease->typeToText(lease->type_))
1105  .arg(lease->addr_.toText());
1106 
1107  // Besides IP reservations we're also going to return other reserved
1108  // parameters, such as hostname. We want to hand out the hostname value
1109  // from the same reservation entry as IP addresses. Thus, let's see if
1110  // there is any hostname reservation.
1111  if (!ctx.host_subnet_) {
1112  SharedNetwork6Ptr network;
1113  ctx.subnet_->getSharedNetwork(network);
1114  if (network) {
1115  // Remember the subnet that holds this preferred host
1116  // reservation. The server will use it to return appropriate
1117  // FQDN, classes etc.
1118  ctx.host_subnet_ = network->getSubnet(lease->subnet_id_);
1119  ConstHostPtr host = ctx.hosts_[lease->subnet_id_];
1120  // If there is a hostname reservation here we should stick
1121  // to this reservation. By updating the hostname in the
1122  // context we make sure that the database is updated with
1123  // this new value and the server doesn't need to do it and
1124  // its processing performance is not impacted by the hostname
1125  // updates.
1126  if (host && !host->getHostname().empty()) {
1127  // We have to determine whether the hostname is generated
1128  // in response to client's FQDN or not. If yes, we will
1129  // need to qualify the hostname. Otherwise, we just use
1130  // the hostname as it is specified for the reservation.
1131  OptionPtr fqdn = ctx.query_->getOption(D6O_CLIENT_FQDN);
1132  ctx.hostname_ = CfgMgr::instance().getD2ClientMgr().
1133  qualifyName(host->getHostname(), static_cast<bool>(fqdn));
1134  }
1135  }
1136  }
1137 
1138  // If this is a real allocation, we may need to extend the lease
1139  // lifetime.
1140  if (!ctx.fake_allocation_ && conditionalExtendLifetime(*lease)) {
1142  }
1143  return;
1144  }
1145  }
1146  }
1147 
1148  // There is no lease for a reservation in this IA. So, let's now iterate
1149  // over reservations specified and try to allocate one of them for the IA.
1150 
1151  Subnet6Ptr subnet = ctx.subnet_;
1152 
1153  while (subnet) {
1154 
1155  SubnetID subnet_id = subnet->getID();
1156 
1157  // No hosts for this subnet or the subnet not supported.
1158  if (!subnet->clientSupported(ctx.query_->getClasses()) ||
1159  ctx.hosts_.count(subnet_id) == 0) {
1160  subnet = subnet->getNextSubnet(ctx.subnet_);
1161  continue;
1162  }
1163 
1164  ConstHostPtr host = ctx.hosts_[subnet_id];
1165 
1166  // Get the IPv6 reservations of specified type.
1167  const IPv6ResrvRange& reservs = host->getIPv6Reservations(type);
1168  BOOST_FOREACH(IPv6ResrvTuple type_lease_tuple, reservs) {
1169  // We do have a reservation for address or prefix.
1170  const IOAddress& addr = type_lease_tuple.second.getPrefix();
1171  uint8_t prefix_len = type_lease_tuple.second.getPrefixLen();
1172 
1173  // We have allocated this address/prefix while processing one of the
1174  // previous IAs, so let's try another reservation.
1175  if (ctx.isAllocated(addr, prefix_len)) {
1176  continue;
1177  }
1178 
1179  // If there's a lease for this address, let's not create it.
1180  // It doesn't matter whether it is for this client or for someone else.
1181  if (!LeaseMgrFactory::instance().getLease6(ctx.currentIA().type_,
1182  addr)) {
1183 
1184  // Let's remember the subnet from which the reserved address has been
1185  // allocated. We'll use this subnet for allocating other reserved
1186  // resources.
1187  ctx.subnet_ = subnet;
1188 
1189  if (!ctx.host_subnet_) {
1190  ctx.host_subnet_ = subnet;
1191  if (!host->getHostname().empty()) {
1192  // If there is a hostname reservation here we should stick
1193  // to this reservation. By updating the hostname in the
1194  // context we make sure that the database is updated with
1195  // this new value and the server doesn't need to do it and
1196  // its processing performance is not impacted by the hostname
1197  // updates.
1198 
1199  // We have to determine whether the hostname is generated
1200  // in response to client's FQDN or not. If yes, we will
1201  // need to qualify the hostname. Otherwise, we just use
1202  // the hostname as it is specified for the reservation.
1203  OptionPtr fqdn = ctx.query_->getOption(D6O_CLIENT_FQDN);
1204  ctx.hostname_ = CfgMgr::instance().getD2ClientMgr().
1205  qualifyName(host->getHostname(), static_cast<bool>(fqdn));
1206  }
1207  }
1208 
1209  // Ok, let's create a new lease...
1210  CalloutHandle::CalloutNextStep callout_status = CalloutHandle::NEXT_STEP_CONTINUE;
1211  Lease6Ptr lease = createLease6(ctx, addr, prefix_len, callout_status);
1212 
1213  // ... and add it to the existing leases list.
1214  existing_leases.push_back(lease);
1215 
1216 
1217  if (ctx.currentIA().type_ == Lease::TYPE_NA) {
1218  LOG_INFO(alloc_engine_logger, ALLOC_ENGINE_V6_HR_ADDR_GRANTED)
1219  .arg(addr.toText())
1220  .arg(ctx.query_->getLabel());
1221  } else {
1222  LOG_INFO(alloc_engine_logger, ALLOC_ENGINE_V6_HR_PREFIX_GRANTED)
1223  .arg(addr.toText())
1224  .arg(static_cast<int>(prefix_len))
1225  .arg(ctx.query_->getLabel());
1226  }
1227 
1228  // We found a lease for this client and this IA. Let's return.
1229  // Returning after the first lease was assigned is useful if we
1230  // have multiple reservations for the same client. If the client
1231  // sends 2 IAs, the first time we call allocateReservedLeases6 will
1232  // use the first reservation and return. The second time, we'll
1233  // go over the first reservation, but will discover that there's
1234  // a lease corresponding to it and will skip it and then pick
1235  // the second reservation and turn it into the lease. This approach
1236  // would work for any number of reservations.
1237  return;
1238  }
1239 
1240  }
1241 
1242  subnet = subnet->getNextSubnet(ctx.subnet_);
1243  }
1244 }
1245 
1246 bool
1247 AllocEngine::allocateGlobalReservedLeases6(ClientContext6& ctx,
1248  Lease6Collection& existing_leases) {
1249  // Get the global host
1250  ConstHostPtr ghost = ctx.globalHost();
1251  if (!ghost) {
1252  return (false);
1253  }
1254 
1255  // We want to avoid allocating a new lease for an IA if there is already
1256  // a valid lease for which client has reservation. So, we first check if
1257  // we already have a lease for a reserved address or prefix.
1258  BOOST_FOREACH(const Lease6Ptr& lease, existing_leases) {
1259  if ((lease->valid_lft_ != 0) &&
1260  (ghost->hasReservation(makeIPv6Resrv(*lease)))) {
1261  // We found existing lease for a reserved address or prefix.
1262  // We'll simply extend the lifetime of the lease.
1264  ALLOC_ENGINE_V6_ALLOC_HR_LEASE_EXISTS)
1265  .arg(ctx.query_->getLabel())
1266  .arg(lease->typeToText(lease->type_))
1267  .arg(lease->addr_.toText());
1268 
1269  // Besides IP reservations we're also going to return other reserved
1270  // parameters, such as hostname. We want to hand out the hostname value
1271  // from the same reservation entry as IP addresses. Thus, let's see if
1272  // there is any hostname reservation.
1273  if (!ghost->getHostname().empty()) {
1274  // We have to determine whether the hostname is generated
1275  // in response to client's FQDN or not. If yes, we will
1276  // need to qualify the hostname. Otherwise, we just use
1277  // the hostname as it is specified for the reservation.
1278  OptionPtr fqdn = ctx.query_->getOption(D6O_CLIENT_FQDN);
1279  ctx.hostname_ = CfgMgr::instance().getD2ClientMgr().
1280  qualifyName(ghost->getHostname(), static_cast<bool>(fqdn));
1281  }
1282 
1283  // If this is a real allocation, we may need to extend the lease
1284  // lifetime.
1285  if (!ctx.fake_allocation_ && conditionalExtendLifetime(*lease)) {
1287  }
1288 
1289  return(true);
1290  }
1291  }
1292 
1293  // There is no lease for a reservation in this IA. So, let's now iterate
1294  // over reservations specified and try to allocate one of them for the IA.
1295 
1296  // Let's convert this from Lease::Type to IPv6Reserv::Type
1297  IPv6Resrv::Type type = ctx.currentIA().type_ == Lease::TYPE_NA ?
1299 
1300  const IPv6ResrvRange& reservs = ghost->getIPv6Reservations(type);
1301  BOOST_FOREACH(IPv6ResrvTuple type_lease_tuple, reservs) {
1302  // We do have a reservation for address or prefix.
1303  const IOAddress& addr = type_lease_tuple.second.getPrefix();
1304  uint8_t prefix_len = type_lease_tuple.second.getPrefixLen();
1305 
1306  // We have allocated this address/prefix while processing one of the
1307  // previous IAs, so let's try another reservation.
1308  if (ctx.isAllocated(addr, prefix_len)) {
1309  continue;
1310  }
1311 
1312  // If there's a lease for this address, let's not create it.
1313  // It doesn't matter whether it is for this client or for someone else.
1314  if (!LeaseMgrFactory::instance().getLease6(ctx.currentIA().type_, addr)) {
1315 
1316  if (!ghost->getHostname().empty()) {
1317  // If there is a hostname reservation here we should stick
1318  // to this reservation. By updating the hostname in the
1319  // context we make sure that the database is updated with
1320  // this new value and the server doesn't need to do it and
1321  // its processing performance is not impacted by the hostname
1322  // updates.
1323 
1324  // We have to determine whether the hostname is generated
1325  // in response to client's FQDN or not. If yes, we will
1326  // need to qualify the hostname. Otherwise, we just use
1327  // the hostname as it is specified for the reservation.
1328  OptionPtr fqdn = ctx.query_->getOption(D6O_CLIENT_FQDN);
1329  ctx.hostname_ = CfgMgr::instance().getD2ClientMgr().
1330  qualifyName(ghost->getHostname(), static_cast<bool>(fqdn));
1331  }
1332 
1333  // Ok, let's create a new lease...
1334  CalloutHandle::CalloutNextStep callout_status = CalloutHandle::NEXT_STEP_CONTINUE;
1335  Lease6Ptr lease = createLease6(ctx, addr, prefix_len, callout_status);
1336 
1337  // ... and add it to the existing leases list.
1338  existing_leases.push_back(lease);
1339 
1340  if (ctx.currentIA().type_ == Lease::TYPE_NA) {
1341  LOG_INFO(alloc_engine_logger, ALLOC_ENGINE_V6_HR_ADDR_GRANTED)
1342  .arg(addr.toText())
1343  .arg(ctx.query_->getLabel());
1344  } else {
1345  LOG_INFO(alloc_engine_logger, ALLOC_ENGINE_V6_HR_PREFIX_GRANTED)
1346  .arg(addr.toText())
1347  .arg(static_cast<int>(prefix_len))
1348  .arg(ctx.query_->getLabel());
1349  }
1350 
1351  // We found a lease for this client and this IA. Let's return.
1352  // Returning after the first lease was assigned is useful if we
1353  // have multiple reservations for the same client. If the client
1354  // sends 2 IAs, the first time we call allocateReservedLeases6 will
1355  // use the first reservation and return. The second time, we'll
1356  // go over the first reservation, but will discover that there's
1357  // a lease corresponding to it and will skip it and then pick
1358  // the second reservation and turn it into the lease. This approach
1359  // would work for any number of reservations.
1360  return (true);
1361  }
1362  }
1363 
1364  return(false);
1365 }
1366 
1367 void
1368 AllocEngine::removeNonmatchingReservedLeases6(ClientContext6& ctx,
1369  Lease6Collection& existing_leases) {
1370  // If there are no leases (so nothing to remove) just return.
1371  if (existing_leases.empty() || !ctx.subnet_) {
1372  return;
1373  }
1374  // If host reservation is disabled (so there are no reserved leases)
1375  // use the simplified version.
1376  if (ctx.subnet_->getHostReservationMode() == Network::HR_DISABLED) {
1377  removeNonmatchingReservedNoHostLeases6(ctx, existing_leases);
1378  return;
1379  }
1380 
1381  // We need a copy, so we won't be iterating over a container and
1382  // removing from it at the same time. It's only a copy of pointers,
1383  // so the operation shouldn't be that expensive.
1384  Lease6Collection copy = existing_leases;
1385 
1386  BOOST_FOREACH(const Lease6Ptr& candidate, copy) {
1387  // If we have reservation we should check if the reservation is for
1388  // the candidate lease. If so, we simply accept the lease.
1389  IPv6Resrv resv = makeIPv6Resrv(*candidate);
1390  if ((ctx.hasGlobalReservation(resv)) ||
1391  ((ctx.hosts_.count(candidate->subnet_id_) > 0) &&
1392  (ctx.hosts_[candidate->subnet_id_]->hasReservation(resv)))) {
1393  // We have a subnet reservation
1394  continue;
1395  }
1396 
1397  // The candidate address doesn't appear to be reserved for us.
1398  // We have to make a bit more expensive operation here to retrieve
1399  // the reservation for the candidate lease and see if it is
1400  // reserved for someone else.
1401  ConstHostPtr host = HostMgr::instance().get6(ctx.subnet_->getID(),
1402  candidate->addr_);
1403  // If lease is not reserved to someone else, it means that it can
1404  // be allocated to us from a dynamic pool, but we must check if
1405  // this lease belongs to any pool. If it does, we can proceed to
1406  // checking the next lease.
1407  if (!host && inAllowedPool(ctx, candidate->type_,
1408  candidate->addr_, false)) {
1409  continue;
1410  }
1411 
1412  if (host) {
1413  // Ok, we have a problem. This host has a lease that is reserved
1414  // for someone else. We need to recover from this.
1415  if (ctx.currentIA().type_ == Lease::TYPE_NA) {
1416  LOG_INFO(alloc_engine_logger, ALLOC_ENGINE_V6_REVOKED_ADDR_LEASE)
1417  .arg(candidate->addr_.toText()).arg(ctx.duid_->toText())
1418  .arg(host->getIdentifierAsText());
1419  } else {
1420  LOG_INFO(alloc_engine_logger, ALLOC_ENGINE_V6_REVOKED_PREFIX_LEASE)
1421  .arg(candidate->addr_.toText())
1422  .arg(static_cast<int>(candidate->prefixlen_))
1423  .arg(ctx.duid_->toText())
1424  .arg(host->getIdentifierAsText());
1425  }
1426  }
1427 
1428  // Remove this lease from LeaseMgr as it is reserved to someone
1429  // else or doesn't belong to a pool.
1430  LeaseMgrFactory::instance().deleteLease(candidate->addr_);
1431 
1432  // Update DNS if needed.
1433  queueNCR(CHG_REMOVE, candidate);
1434 
1435  // Need to decrease statistic for assigned addresses.
1436  StatsMgr::instance().addValue(
1437  StatsMgr::generateName("subnet", candidate->subnet_id_,
1438  ctx.currentIA().type_ == Lease::TYPE_NA ?
1439  "assigned-nas" : "assigned-pds"),
1440  static_cast<int64_t>(-1));
1441 
1442  // In principle, we could trigger a hook here, but we will do this
1443  // only if we get serious complaints from actual users. We want the
1444  // conflict resolution procedure to really work and user libraries
1445  // should not interfere with it.
1446 
1447  // Add this to the list of removed leases.
1448  ctx.currentIA().old_leases_.push_back(candidate);
1449 
1450  // Let's remove this candidate from existing leases
1451  removeLeases(existing_leases, candidate->addr_);
1452  }
1453 }
1454 
1455 void
1456 AllocEngine::removeNonmatchingReservedNoHostLeases6(ClientContext6& ctx,
1457  Lease6Collection& existing_leases) {
1458  // We need a copy, so we won't be iterating over a container and
1459  // removing from it at the same time. It's only a copy of pointers,
1460  // so the operation shouldn't be that expensive.
1461  Lease6Collection copy = existing_leases;
1462 
1463  BOOST_FOREACH(const Lease6Ptr& candidate, copy) {
1464  // Lease can be allocated to us from a dynamic pool, but we must
1465  // check if this lease belongs to any allowed pool. If it does,
1466  // we can proceed to checking the next lease.
1467  if (inAllowedPool(ctx, candidate->type_,
1468  candidate->addr_, false)) {
1469  continue;
1470  }
1471 
1472  // Remove this lease from LeaseMgr as it doesn't belong to a pool.
1473  LeaseMgrFactory::instance().deleteLease(candidate->addr_);
1474 
1475  // Update DNS if needed.
1476  queueNCR(CHG_REMOVE, candidate);
1477 
1478  // Need to decrease statistic for assigned addresses.
1479  StatsMgr::instance().addValue(
1480  StatsMgr::generateName("subnet", candidate->subnet_id_,
1481  ctx.currentIA().type_ == Lease::TYPE_NA ?
1482  "assigned-nas" : "assigned-pds"),
1483  static_cast<int64_t>(-1));
1484 
1485  // Add this to the list of removed leases.
1486  ctx.currentIA().old_leases_.push_back(candidate);
1487 
1488  // Let's remove this candidate from existing leases
1489  removeLeases(existing_leases, candidate->addr_);
1490  }
1491 }
1492 
1493 bool
1494 AllocEngine::removeLeases(Lease6Collection& container, const asiolink::IOAddress& addr) {
1495 
1496  bool removed = false;
1497  for (Lease6Collection::iterator lease = container.begin();
1498  lease != container.end(); ++lease) {
1499  if ((*lease)->addr_ == addr) {
1500  lease->reset();
1501  removed = true;
1502  }
1503  }
1504 
1505  // Remove all elements that have NULL value
1506  container.erase(std::remove(container.begin(), container.end(), Lease6Ptr()),
1507  container.end());
1508 
1509  return (removed);
1510 }
1511 
1512 void
1513 AllocEngine::removeNonreservedLeases6(ClientContext6& ctx,
1514  Lease6Collection& existing_leases) {
1515  // This method removes leases that are not reserved for this host.
1516  // It will keep at least one lease, though.
1517  if (existing_leases.empty()) {
1518  return;
1519  }
1520 
1521  // This is the total number of leases. We should not remove the last one.
1522  int total = existing_leases.size();
1523 
1524  // This is officially not scary code anymore. iterates and marks specified
1525  // leases for deletion, by setting appropriate pointers to NULL.
1526  for (Lease6Collection::iterator lease = existing_leases.begin();
1527  lease != existing_leases.end(); ++lease) {
1528 
1529  // If there is reservation for this keep it.
1530  IPv6Resrv resv = makeIPv6Resrv(*(*lease));
1531  if (ctx.hasGlobalReservation(resv) ||
1532  ((ctx.hosts_.count((*lease)->subnet_id_) > 0) &&
1533  (ctx.hosts_[(*lease)->subnet_id_]->hasReservation(resv)))) {
1534  continue;
1535  }
1536 
1537  // We have reservations, but not for this lease. Release it.
1538  // Remove this lease from LeaseMgr
1539  LeaseMgrFactory::instance().deleteLease((*lease)->addr_);
1540 
1541  // Update DNS if required.
1542  queueNCR(CHG_REMOVE, *lease);
1543 
1544  // Need to decrease statistic for assigned addresses.
1545  StatsMgr::instance().addValue(
1546  StatsMgr::generateName("subnet", (*lease)->subnet_id_,
1547  ctx.currentIA().type_ == Lease::TYPE_NA ?
1548  "assigned-nas" : "assigned-pds"),
1549  static_cast<int64_t>(-1));
1550 
1552 
1553  // Add this to the list of removed leases.
1554  ctx.currentIA().old_leases_.push_back(*lease);
1555 
1556  // Set this pointer to NULL. The pointer is still valid. We're just
1557  // setting the Lease6Ptr to NULL value. We'll remove all NULL
1558  // pointers once the loop is finished.
1559  lease->reset();
1560 
1561  if (--total == 1) {
1562  // If there's only one lease left, break the loop.
1563  break;
1564  }
1565 
1566  }
1567 
1568  // Remove all elements that we previously marked for deletion (those that
1569  // have NULL value).
1570  existing_leases.erase(std::remove(existing_leases.begin(),
1571  existing_leases.end(), Lease6Ptr()), existing_leases.end());
1572 }
1573 
1574 Lease6Ptr
1575 AllocEngine::reuseExpiredLease(Lease6Ptr& expired, ClientContext6& ctx,
1576  uint8_t prefix_len,
1577  CalloutHandle::CalloutNextStep& callout_status) {
1578 
1579  if (!expired->expired()) {
1580  isc_throw(BadValue, "Attempt to recycle lease that is still valid");
1581  }
1582 
1583  if (expired->type_ != Lease::TYPE_PD) {
1584  prefix_len = 128; // non-PD lease types must be always /128
1585  }
1586 
1587  if (!ctx.fake_allocation_) {
1588  // The expired lease needs to be reclaimed before it can be reused.
1589  // This includes declined leases for which probation period has
1590  // elapsed.
1591  reclaimExpiredLease(expired, ctx.callout_handle_);
1592  }
1593 
1594  // address, lease type and prefixlen (0) stay the same
1595  expired->iaid_ = ctx.currentIA().iaid_;
1596  expired->duid_ = ctx.duid_;
1597  expired->preferred_lft_ = ctx.subnet_->getPreferred();
1598  expired->valid_lft_ = ctx.subnet_->getValid();
1599  expired->t1_ = ctx.subnet_->getT1();
1600  expired->t2_ = ctx.subnet_->getT2();
1601  expired->cltt_ = time(NULL);
1602  expired->subnet_id_ = ctx.subnet_->getID();
1603  expired->hostname_ = ctx.hostname_;
1604  expired->fqdn_fwd_ = ctx.fwd_dns_update_;
1605  expired->fqdn_rev_ = ctx.rev_dns_update_;
1606  expired->prefixlen_ = prefix_len;
1607  expired->state_ = Lease::STATE_DEFAULT;
1608 
1610  ALLOC_ENGINE_V6_REUSE_EXPIRED_LEASE_DATA)
1611  .arg(ctx.query_->getLabel())
1612  .arg(expired->toText());
1613 
1614  // Let's execute all callouts registered for lease6_select
1615  if (ctx.callout_handle_ &&
1616  HooksManager::getHooksManager().calloutsPresent(hook_index_lease6_select_)) {
1617 
1618  // Use the RAII wrapper to make sure that the callout handle state is
1619  // reset when this object goes out of scope. All hook points must do
1620  // it to prevent possible circular dependency between the callout
1621  // handle and its arguments.
1622  ScopedCalloutHandleState callout_handle_state(ctx.callout_handle_);
1623 
1624  // Enable copying options from the packet within hook library.
1625  ScopedEnableOptionsCopy<Pkt6> query6_options_copy(ctx.query_);
1626 
1627  // Pass necessary arguments
1628 
1629  // Pass the original packet
1630  ctx.callout_handle_->setArgument("query6", ctx.query_);
1631 
1632  // Subnet from which we do the allocation
1633  ctx.callout_handle_->setArgument("subnet6", ctx.subnet_);
1634 
1635  // Is this solicit (fake = true) or request (fake = false)
1636  ctx.callout_handle_->setArgument("fake_allocation", ctx.fake_allocation_);
1637 
1638  // The lease that will be assigned to a client
1639  ctx.callout_handle_->setArgument("lease6", expired);
1640 
1641  // Call the callouts
1642  HooksManager::callCallouts(hook_index_lease6_select_, *ctx.callout_handle_);
1643 
1644  callout_status = ctx.callout_handle_->getStatus();
1645 
1646  // Callouts decided to skip the action. This means that the lease is not
1647  // assigned, so the client will get NoAddrAvail as a result. The lease
1648  // won't be inserted into the database.
1649  if (callout_status == CalloutHandle::NEXT_STEP_SKIP) {
1650  LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE6_SELECT_SKIP);
1651  return (Lease6Ptr());
1652  }
1653 
1658 
1659  // Let's use whatever callout returned. Hopefully it is the same lease
1660  // we handed to it.
1661  ctx.callout_handle_->getArgument("lease6", expired);
1662  }
1663 
1664  if (!ctx.fake_allocation_) {
1665  // for REQUEST we do update the lease
1667 
1668  // If the lease is in the current subnet we need to account
1669  // for the re-assignment of The lease.
1670  if (ctx.subnet_->inPool(ctx.currentIA().type_, expired->addr_)) {
1671  StatsMgr::instance().addValue(
1672  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
1673  ctx.currentIA().type_ == Lease::TYPE_NA ?
1674  "assigned-nas" : "assigned-pds"),
1675  static_cast<int64_t>(1));
1676  }
1677  }
1678 
1679  // We do nothing for SOLICIT. We'll just update database when
1680  // the client gets back to us with REQUEST message.
1681 
1682  // it's not really expired at this stage anymore - let's return it as
1683  // an updated lease
1684  return (expired);
1685 }
1686 
1687 Lease6Ptr AllocEngine::createLease6(ClientContext6& ctx,
1688  const IOAddress& addr,
1689  uint8_t prefix_len,
1690  CalloutHandle::CalloutNextStep& callout_status) {
1691 
1692  if (ctx.currentIA().type_ != Lease::TYPE_PD) {
1693  prefix_len = 128; // non-PD lease types must be always /128
1694  }
1695 
1696  Lease6Ptr lease(new Lease6(ctx.currentIA().type_, addr, ctx.duid_,
1697  ctx.currentIA().iaid_, ctx.subnet_->getPreferred(),
1698  ctx.subnet_->getValid(), ctx.subnet_->getT1(),
1699  ctx.subnet_->getT2(), ctx.subnet_->getID(),
1700  ctx.hwaddr_, prefix_len));
1701 
1702  lease->fqdn_fwd_ = ctx.fwd_dns_update_;
1703  lease->fqdn_rev_ = ctx.rev_dns_update_;
1704  lease->hostname_ = ctx.hostname_;
1705 
1706  // Let's execute all callouts registered for lease6_select
1707  if (ctx.callout_handle_ &&
1708  HooksManager::getHooksManager().calloutsPresent(hook_index_lease6_select_)) {
1709 
1710  // Use the RAII wrapper to make sure that the callout handle state is
1711  // reset when this object goes out of scope. All hook points must do
1712  // it to prevent possible circular dependency between the callout
1713  // handle and its arguments.
1714  ScopedCalloutHandleState callout_handle_state(ctx.callout_handle_);
1715 
1716  // Enable copying options from the packet within hook library.
1717  ScopedEnableOptionsCopy<Pkt6> query6_options_copy(ctx.query_);
1718 
1719  // Pass necessary arguments
1720 
1721  // Pass the original packet
1722  ctx.callout_handle_->setArgument("query6", ctx.query_);
1723 
1724  // Subnet from which we do the allocation
1725  ctx.callout_handle_->setArgument("subnet6", ctx.subnet_);
1726 
1727  // Is this solicit (fake = true) or request (fake = false)
1728  ctx.callout_handle_->setArgument("fake_allocation", ctx.fake_allocation_);
1729  ctx.callout_handle_->setArgument("lease6", lease);
1730 
1731  // This is the first callout, so no need to clear any arguments
1732  HooksManager::callCallouts(hook_index_lease6_select_, *ctx.callout_handle_);
1733 
1734  callout_status = ctx.callout_handle_->getStatus();
1735 
1736  // Callouts decided to skip the action. This means that the lease is not
1737  // assigned, so the client will get NoAddrAvail as a result. The lease
1738  // won't be inserted into the database.
1739  if (callout_status == CalloutHandle::NEXT_STEP_SKIP) {
1740  LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE6_SELECT_SKIP);
1741  return (Lease6Ptr());
1742  }
1743 
1744  // Let's use whatever callout returned. Hopefully it is the same lease
1745  // we handed to it.
1746  ctx.callout_handle_->getArgument("lease6", lease);
1747  }
1748 
1749  if (!ctx.fake_allocation_) {
1750  // That is a real (REQUEST) allocation
1751  bool status = LeaseMgrFactory::instance().addLease(lease);
1752 
1753  if (status) {
1754  // The lease insertion succeeded - if the lease is in the
1755  // current subnet lets bump up the statistic.
1756  if (ctx.subnet_->inPool(ctx.currentIA().type_, addr)) {
1757  StatsMgr::instance().addValue(
1758  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
1759  ctx.currentIA().type_ == Lease::TYPE_NA ?
1760  "assigned-nas" : "assigned-pds"),
1761  static_cast<int64_t>(1));
1762  }
1763 
1764  return (lease);
1765  } else {
1766  // One of many failures with LeaseMgr (e.g. lost connection to the
1767  // database, database failed etc.). One notable case for that
1768  // is that we are working in multi-process mode and we lost a race
1769  // (some other process got that address first)
1770  return (Lease6Ptr());
1771  }
1772  } else {
1773  // That is only fake (SOLICIT without rapid-commit) allocation
1774 
1775  // It is for advertise only. We should not insert the lease into LeaseMgr,
1776  // but rather check that we could have inserted it.
1778  ctx.currentIA().type_, addr);
1779  if (!existing) {
1780  return (lease);
1781  } else {
1782  return (Lease6Ptr());
1783  }
1784  }
1785 }
1786 
1789  try {
1790  if (!ctx.subnet_) {
1791  isc_throw(InvalidOperation, "Subnet is required for allocation");
1792  }
1793 
1794  if (!ctx.duid_) {
1795  isc_throw(InvalidOperation, "DUID is mandatory for allocation");
1796  }
1797 
1798  // Check if there are any leases for this client.
1799  Subnet6Ptr subnet = ctx.subnet_;
1800  Lease6Collection leases;
1801  while (subnet) {
1802  Lease6Collection leases_subnet =
1804  *ctx.duid_,
1805  ctx.currentIA().iaid_,
1806  subnet->getID());
1807  leases.insert(leases.end(), leases_subnet.begin(), leases_subnet.end());
1808 
1809  subnet = subnet->getNextSubnet(ctx.subnet_);
1810  }
1811 
1812 
1813  if (!leases.empty()) {
1815  ALLOC_ENGINE_V6_RENEW_REMOVE_RESERVED)
1816  .arg(ctx.query_->getLabel());
1817 
1818  // Check if the existing leases are reserved for someone else.
1819  // If they're not, we're ok to keep using them.
1820  removeNonmatchingReservedLeases6(ctx, leases);
1821  }
1822 
1823  if (!ctx.hosts_.empty()) {
1824 
1826  ALLOC_ENGINE_V6_RENEW_HR)
1827  .arg(ctx.query_->getLabel());
1828 
1829  // If we have host reservation, allocate those leases.
1830  allocateReservedLeases6(ctx, leases);
1831 
1832  // There's one more check to do. Let's remove leases that are not
1833  // matching reservations, i.e. if client X has address A, but there's
1834  // a reservation for address B, we should release A and reassign B.
1835  // Caveat: do this only if we have at least one reserved address.
1836  removeNonreservedLeases6(ctx, leases);
1837  }
1838 
1839  // If we happen to removed all leases, get something new for this guy.
1840  // Depending on the configuration, we may enable or disable granting
1841  // new leases during renewals. This is controlled with the
1842  // allow_new_leases_in_renewals_ field.
1843  if (leases.empty()) {
1844 
1846  ALLOC_ENGINE_V6_EXTEND_ALLOC_UNRESERVED)
1847  .arg(ctx.query_->getLabel());
1848 
1849  leases = allocateUnreservedLeases6(ctx);
1850  }
1851 
1852  // Extend all existing leases that passed all checks.
1853  for (Lease6Collection::iterator l = leases.begin(); l != leases.end(); ++l) {
1855  ALLOC_ENGINE_V6_EXTEND_LEASE)
1856  .arg(ctx.query_->getLabel())
1857  .arg((*l)->typeToText((*l)->type_))
1858  .arg((*l)->addr_);
1859  extendLease6(ctx, *l);
1860  }
1861 
1862  if (!leases.empty()) {
1863  // If there are any leases allocated, let's store in them in the
1864  // IA context so as they are available when we process subsequent
1865  // IAs.
1866  BOOST_FOREACH(Lease6Ptr lease, leases) {
1867  ctx.addAllocatedResource(lease->addr_, lease->prefixlen_);
1868  ctx.new_leases_.push_back(lease);
1869  }
1870  }
1871 
1872  return (leases);
1873 
1874  } catch (const isc::Exception& e) {
1875 
1876  // Some other error, return an empty lease.
1877  LOG_ERROR(alloc_engine_logger, ALLOC_ENGINE_V6_EXTEND_ERROR)
1878  .arg(ctx.query_->getLabel())
1879  .arg(e.what());
1880  }
1881 
1882  return (Lease6Collection());
1883 }
1884 
1885 void
1886 AllocEngine::extendLease6(ClientContext6& ctx, Lease6Ptr lease) {
1887 
1888  if (!lease || !ctx.subnet_) {
1889  return;
1890  }
1891 
1892  // It is likely that the lease for which we're extending the lifetime doesn't
1893  // belong to the current but a sibling subnet.
1894  if (ctx.subnet_->getID() != lease->subnet_id_) {
1895  SharedNetwork6Ptr network;
1896  ctx.subnet_->getSharedNetwork(network);
1897  if (network) {
1898  Subnet6Ptr subnet = network->getSubnet(SubnetID(lease->subnet_id_));
1899  // Found the actual subnet this lease belongs to. Stick to this
1900  // subnet.
1901  if (subnet) {
1902  ctx.subnet_ = subnet;
1903  }
1904  }
1905  }
1906 
1907  // If the lease is not global and it is either out of range (NAs only) or it
1908  // is not permitted by subnet client classification, delete it.
1909  if (!(ctx.hasGlobalReservation(makeIPv6Resrv(*lease))) &&
1910  (((lease->type_ != Lease::TYPE_PD) && !ctx.subnet_->inRange(lease->addr_)) ||
1911  !ctx.subnet_->clientSupported(ctx.query_->getClasses()))) {
1912  // Oh dear, the lease is no longer valid. We need to get rid of it.
1913 
1914  // Remove this lease from LeaseMgr
1915  LeaseMgrFactory::instance().deleteLease(lease->addr_);
1916 
1917  // Updated DNS if required.
1918  queueNCR(CHG_REMOVE, lease);
1919 
1920  // Need to decrease statistic for assigned addresses.
1921  StatsMgr::instance().addValue(
1922  StatsMgr::generateName("subnet", ctx.subnet_->getID(), "assigned-nas"),
1923  static_cast<int64_t>(-1));
1924 
1925  // Add it to the removed leases list.
1926  ctx.currentIA().old_leases_.push_back(lease);
1927 
1928  return;
1929  }
1930 
1932  ALLOC_ENGINE_V6_EXTEND_LEASE_DATA)
1933  .arg(ctx.query_->getLabel())
1934  .arg(lease->toText());
1935 
1936  // Keep the old data in case the callout tells us to skip update.
1937  Lease6Ptr old_data(new Lease6(*lease));
1938 
1939  lease->preferred_lft_ = ctx.subnet_->getPreferred();
1940  lease->valid_lft_ = ctx.subnet_->getValid();
1941  lease->t1_ = ctx.subnet_->getT1();
1942  lease->t2_ = ctx.subnet_->getT2();
1943  lease->hostname_ = ctx.hostname_;
1944  lease->fqdn_fwd_ = ctx.fwd_dns_update_;
1945  lease->fqdn_rev_ = ctx.rev_dns_update_;
1946  lease->hwaddr_ = ctx.hwaddr_;
1947  lease->state_ = Lease::STATE_DEFAULT;
1948 
1949  // Extend lease lifetime if it is time to extend it.
1950  conditionalExtendLifetime(*lease);
1951 
1953  ALLOC_ENGINE_V6_EXTEND_NEW_LEASE_DATA)
1954  .arg(ctx.query_->getLabel())
1955  .arg(lease->toText());
1956 
1957  bool skip = false;
1958  // Get the callouts specific for the processed message and execute them.
1959  int hook_point = ctx.query_->getType() == DHCPV6_RENEW ?
1960  Hooks.hook_index_lease6_renew_ : Hooks.hook_index_lease6_rebind_;
1961  if (HooksManager::calloutsPresent(hook_point)) {
1962  CalloutHandlePtr callout_handle = ctx.callout_handle_;
1963 
1964  // Use the RAII wrapper to make sure that the callout handle state is
1965  // reset when this object goes out of scope. All hook points must do
1966  // it to prevent possible circular dependency between the callout
1967  // handle and its arguments.
1968  ScopedCalloutHandleState callout_handle_state(callout_handle);
1969 
1970  // Enable copying options from the packet within hook library.
1971  ScopedEnableOptionsCopy<Pkt6> query6_options_copy(ctx.query_);
1972 
1973  // Pass the original packet
1974  callout_handle->setArgument("query6", ctx.query_);
1975 
1976  // Pass the lease to be updated
1977  callout_handle->setArgument("lease6", lease);
1978 
1979  // Pass the IA option to be sent in response
1980  if (lease->type_ == Lease::TYPE_NA) {
1981  callout_handle->setArgument("ia_na", ctx.currentIA().ia_rsp_);
1982  } else {
1983  callout_handle->setArgument("ia_pd", ctx.currentIA().ia_rsp_);
1984  }
1985 
1986  // Call all installed callouts
1987  HooksManager::callCallouts(hook_point, *callout_handle);
1988 
1989  // Callouts decided to skip the next processing step. The next
1990  // processing step would actually renew the lease, so skip at this
1991  // stage means "keep the old lease as it is".
1992  if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
1993  skip = true;
1995  DHCPSRV_HOOK_LEASE6_EXTEND_SKIP)
1996  .arg(ctx.query_->getName());
1997  }
1998 
2000  }
2001 
2002  if (!skip) {
2003  // If the lease we're renewing has expired, we need to reclaim this
2004  // lease before we can renew it.
2005  if (old_data->expired()) {
2006  reclaimExpiredLease(old_data, ctx.callout_handle_);
2007 
2008  // If the lease is in the current subnet we need to account
2009  // for the re-assignment of The lease.
2010  if (ctx.subnet_->inPool(ctx.currentIA().type_, old_data->addr_)) {
2011  StatsMgr::instance().addValue(
2012  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
2013  ctx.currentIA().type_ == Lease::TYPE_NA ?
2014  "assigned-nas" : "assigned-pds"),
2015  static_cast<int64_t>(1));
2016  }
2017  } else {
2018  if (!lease->hasIdenticalFqdn(*old_data)) {
2019  // We're not reclaiming the lease but since the FQDN has changed
2020  // we have to at least send NCR.
2021  queueNCR(CHG_REMOVE, old_data);
2022  }
2023  }
2024 
2025  // Now that the lease has been reclaimed, we can go ahead and update it
2026  // in the lease database.
2028 
2029  } else {
2030  // Copy back the original date to the lease. For MySQL it doesn't make
2031  // much sense, but for memfile, the Lease6Ptr points to the actual lease
2032  // in memfile, so the actual update is performed when we manipulate
2033  // fields of returned Lease6Ptr, the actual updateLease6() is no-op.
2034  *lease = *old_data;
2035  }
2036 
2037  // Add the old lease to the changed lease list. This allows the server
2038  // to make decisions regarding DNS updates.
2039  ctx.currentIA().changed_leases_.push_back(old_data);
2040 }
2041 
2042 
2044 AllocEngine::updateLeaseData(ClientContext6& ctx, const Lease6Collection& leases) {
2045  Lease6Collection updated_leases;
2046  bool remove_queued = false;
2047  for (Lease6Collection::const_iterator lease_it = leases.begin();
2048  lease_it != leases.end(); ++lease_it) {
2049  Lease6Ptr lease(new Lease6(**lease_it));
2050  lease->fqdn_fwd_ = ctx.fwd_dns_update_;
2051  lease->fqdn_rev_ = ctx.rev_dns_update_;
2052  lease->hostname_ = ctx.hostname_;
2053  if (!ctx.fake_allocation_) {
2054 
2055  if (lease->state_ == Lease::STATE_EXPIRED_RECLAIMED) {
2056  // Transition lease state to default (aka assigned)
2057  lease->state_ = Lease::STATE_DEFAULT;
2058 
2059  // If the lease is in the current subnet we need to account
2060  // for the re-assignment of The lease.
2061  if (inAllowedPool(ctx, ctx.currentIA().type_,
2062  lease->addr_, true)) {
2063  StatsMgr::instance().addValue(
2064  StatsMgr::generateName("subnet", lease->subnet_id_,
2065  ctx.currentIA().type_ == Lease::TYPE_NA ?
2066  "assigned-nas" : "assigned-pds"),
2067  static_cast<int64_t>(1));
2068  }
2069  }
2070 
2071  bool fqdn_changed = ((lease->type_ != Lease::TYPE_PD) &&
2072  !(lease->hasIdenticalFqdn(**lease_it)));
2073 
2074  if (conditionalExtendLifetime(*lease) || fqdn_changed) {
2075  ctx.currentIA().changed_leases_.push_back(*lease_it);
2077 
2078  // If the FQDN differs, remove existing DNS entries.
2079  // We only need one remove.
2080  if (fqdn_changed && !remove_queued) {
2081  queueNCR(CHG_REMOVE, *lease_it);
2082  remove_queued = true;
2083  }
2084  }
2085  }
2086 
2087  updated_leases.push_back(lease);
2088  }
2089 
2090  return (updated_leases);
2091 }
2092 
2093 void
2094 AllocEngine::reclaimExpiredLeases6(const size_t max_leases, const uint16_t timeout,
2095  const bool remove_lease,
2096  const uint16_t max_unwarned_cycles) {
2097 
2099  ALLOC_ENGINE_V6_LEASES_RECLAMATION_START)
2100  .arg(max_leases)
2101  .arg(timeout);
2102 
2103  // Create stopwatch and automatically start it to measure the time
2104  // taken by the routine.
2105  util::Stopwatch stopwatch;
2106 
2107  LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
2108 
2109  // This value indicates if we have been able to deal with all expired
2110  // leases in this pass.
2111  bool incomplete_reclamation = false;
2112  Lease6Collection leases;
2113  // The value of 0 has a special meaning - reclaim all.
2114  if (max_leases > 0) {
2115  // If the value is non-zero, the caller has limited the number of
2116  // leases to reclaim. We obtain one lease more to see if there will
2117  // be still leases left after this pass.
2118  lease_mgr.getExpiredLeases6(leases, max_leases + 1);
2119  // There are more leases expired leases than we will process in this
2120  // pass, so we should mark it as an incomplete reclamation. We also
2121  // remove this extra lease (which we don't want to process anyway)
2122  // from the collection.
2123  if (leases.size() > max_leases) {
2124  leases.pop_back();
2125  incomplete_reclamation = true;
2126  }
2127 
2128  } else {
2129  // If there is no limitation on the number of leases to reclaim,
2130  // we will try to process all. Hence, we don't mark it as incomplete
2131  // reclamation just yet.
2132  lease_mgr.getExpiredLeases6(leases, max_leases);
2133  }
2134 
2135  // Do not initialize the callout handle until we know if there are any
2136  // lease6_expire callouts installed.
2137  CalloutHandlePtr callout_handle;
2138  if (!leases.empty() &&
2139  HooksManager::getHooksManager().calloutsPresent(Hooks.hook_index_lease6_expire_)) {
2140  callout_handle = HooksManager::createCalloutHandle();
2141  }
2142 
2143  size_t leases_processed = 0;
2144  BOOST_FOREACH(Lease6Ptr lease, leases) {
2145 
2146  try {
2147  // Reclaim the lease.
2148  reclaimExpiredLease(lease, remove_lease, callout_handle);
2149  ++leases_processed;
2150 
2151  } catch (const std::exception& ex) {
2152  LOG_ERROR(alloc_engine_logger, ALLOC_ENGINE_V6_LEASE_RECLAMATION_FAILED)
2153  .arg(lease->addr_.toText())
2154  .arg(ex.what());
2155  }
2156 
2157  // Check if we have hit the timeout for running reclamation routine and
2158  // return if we have. We're checking it here, because we always want to
2159  // allow reclaiming at least one lease.
2160  if ((timeout > 0) && (stopwatch.getTotalMilliseconds() >= timeout)) {
2161  // Timeout. This will likely mean that we haven't been able to process
2162  // all leases we wanted to process. The reclamation pass will be
2163  // probably marked as incomplete.
2164  if (!incomplete_reclamation) {
2165  if (leases_processed < leases.size()) {
2166  incomplete_reclamation = true;
2167  }
2168  }
2169 
2171  ALLOC_ENGINE_V6_LEASES_RECLAMATION_TIMEOUT)
2172  .arg(timeout);
2173  break;
2174  }
2175  }
2176 
2177  // Stop measuring the time.
2178  stopwatch.stop();
2179 
2180  // Mark completion of the lease reclamation routine and present some stats.
2182  ALLOC_ENGINE_V6_LEASES_RECLAMATION_COMPLETE)
2183  .arg(leases_processed)
2184  .arg(stopwatch.logFormatTotalDuration());
2185 
2186  // Check if this was an incomplete reclamation and increase the number of
2187  // consecutive incomplete reclamations.
2188  if (incomplete_reclamation) {
2189  ++incomplete_v6_reclamations_;
2190  // If the number of incomplete reclamations is beyond the threshold, we
2191  // need to issue a warning.
2192  if ((max_unwarned_cycles > 0) &&
2193  (incomplete_v6_reclamations_ > max_unwarned_cycles)) {
2194  LOG_WARN(alloc_engine_logger, ALLOC_ENGINE_V6_LEASES_RECLAMATION_SLOW)
2195  .arg(max_unwarned_cycles);
2196  // We issued a warning, so let's now reset the counter.
2197  incomplete_v6_reclamations_ = 0;
2198  }
2199 
2200  } else {
2201  // This was a complete reclamation, so let's reset the counter.
2202  incomplete_v6_reclamations_ = 0;
2203 
2205  ALLOC_ENGINE_V6_NO_MORE_EXPIRED_LEASES);
2206  }
2207 }
2208 
2209 void
2212  ALLOC_ENGINE_V6_RECLAIMED_LEASES_DELETE)
2213  .arg(secs);
2214 
2215  uint64_t deleted_leases = 0;
2216  try {
2217  // Try to delete leases from the lease database.
2218  LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
2219  deleted_leases = lease_mgr.deleteExpiredReclaimedLeases6(secs);
2220 
2221  } catch (const std::exception& ex) {
2222  LOG_ERROR(alloc_engine_logger, ALLOC_ENGINE_V6_RECLAIMED_LEASES_DELETE_FAILED)
2223  .arg(ex.what());
2224  }
2225 
2227  ALLOC_ENGINE_V6_RECLAIMED_LEASES_DELETE_COMPLETE)
2228  .arg(deleted_leases);
2229 }
2230 
2231 
2232 void
2233 AllocEngine::reclaimExpiredLeases4(const size_t max_leases, const uint16_t timeout,
2234  const bool remove_lease,
2235  const uint16_t max_unwarned_cycles) {
2236 
2238  ALLOC_ENGINE_V4_LEASES_RECLAMATION_START)
2239  .arg(max_leases)
2240  .arg(timeout);
2241 
2242  // Create stopwatch and automatically start it to measure the time
2243  // taken by the routine.
2244  util::Stopwatch stopwatch;
2245 
2246  LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
2247 
2248  // This value indicates if we have been able to deal with all expired
2249  // leases in this pass.
2250  bool incomplete_reclamation = false;
2251  Lease4Collection leases;
2252  // The value of 0 has a special meaning - reclaim all.
2253  if (max_leases > 0) {
2254  // If the value is non-zero, the caller has limited the number of
2255  // leases to reclaim. We obtain one lease more to see if there will
2256  // be still leases left after this pass.
2257  lease_mgr.getExpiredLeases4(leases, max_leases + 1);
2258  // There are more leases expired leases than we will process in this
2259  // pass, so we should mark it as an incomplete reclamation. We also
2260  // remove this extra lease (which we don't want to process anyway)
2261  // from the collection.
2262  if (leases.size() > max_leases) {
2263  leases.pop_back();
2264  incomplete_reclamation = true;
2265  }
2266 
2267  } else {
2268  // If there is no limitation on the number of leases to reclaim,
2269  // we will try to process all. Hence, we don't mark it as incomplete
2270  // reclamation just yet.
2271  lease_mgr.getExpiredLeases4(leases, max_leases);
2272  }
2273 
2274 
2275  // Do not initialize the callout handle until we know if there are any
2276  // lease4_expire callouts installed.
2277  CalloutHandlePtr callout_handle;
2278  if (!leases.empty() &&
2279  HooksManager::getHooksManager().calloutsPresent(Hooks.hook_index_lease4_expire_)) {
2280  callout_handle = HooksManager::createCalloutHandle();
2281  }
2282 
2283  size_t leases_processed = 0;
2284  BOOST_FOREACH(Lease4Ptr lease, leases) {
2285 
2286  try {
2287  // Reclaim the lease.
2288  reclaimExpiredLease(lease, remove_lease, callout_handle);
2289  ++leases_processed;
2290 
2291  } catch (const std::exception& ex) {
2292  LOG_ERROR(alloc_engine_logger, ALLOC_ENGINE_V4_LEASE_RECLAMATION_FAILED)
2293  .arg(lease->addr_.toText())
2294  .arg(ex.what());
2295  }
2296 
2297  // Check if we have hit the timeout for running reclamation routine and
2298  // return if we have. We're checking it here, because we always want to
2299  // allow reclaiming at least one lease.
2300  if ((timeout > 0) && (stopwatch.getTotalMilliseconds() >= timeout)) {
2301  // Timeout. This will likely mean that we haven't been able to process
2302  // all leases we wanted to process. The reclamation pass will be
2303  // probably marked as incomplete.
2304  if (!incomplete_reclamation) {
2305  if (leases_processed < leases.size()) {
2306  incomplete_reclamation = true;
2307  }
2308  }
2309 
2311  ALLOC_ENGINE_V4_LEASES_RECLAMATION_TIMEOUT)
2312  .arg(timeout);
2313  break;
2314  }
2315  }
2316 
2317  // Stop measuring the time.
2318  stopwatch.stop();
2319 
2320  // Mark completion of the lease reclamation routine and present some stats.
2322  ALLOC_ENGINE_V4_LEASES_RECLAMATION_COMPLETE)
2323  .arg(leases_processed)
2324  .arg(stopwatch.logFormatTotalDuration());
2325 
2326  // Check if this was an incomplete reclamation and increase the number of
2327  // consecutive incomplete reclamations.
2328  if (incomplete_reclamation) {
2329  ++incomplete_v4_reclamations_;
2330  // If the number of incomplete reclamations is beyond the threshold, we
2331  // need to issue a warning.
2332  if ((max_unwarned_cycles > 0) &&
2333  (incomplete_v4_reclamations_ > max_unwarned_cycles)) {
2334  LOG_WARN(alloc_engine_logger, ALLOC_ENGINE_V4_LEASES_RECLAMATION_SLOW)
2335  .arg(max_unwarned_cycles);
2336  // We issued a warning, so let's now reset the counter.
2337  incomplete_v4_reclamations_ = 0;
2338  }
2339 
2340  } else {
2341  // This was a complete reclamation, so let's reset the counter.
2342  incomplete_v4_reclamations_ = 0;
2343 
2345  ALLOC_ENGINE_V4_NO_MORE_EXPIRED_LEASES);
2346  }
2347 }
2348 
2349 template<typename LeasePtrType>
2350 void
2351 AllocEngine::reclaimExpiredLease(const LeasePtrType& lease, const bool remove_lease,
2352  const CalloutHandlePtr& callout_handle) {
2353  reclaimExpiredLease(lease, remove_lease ? DB_RECLAIM_REMOVE : DB_RECLAIM_UPDATE,
2354  callout_handle);
2355 }
2356 
2357 template<typename LeasePtrType>
2358 void
2359 AllocEngine::reclaimExpiredLease(const LeasePtrType& lease,
2360  const CalloutHandlePtr& callout_handle) {
2361  // This variant of the method is used by the code which allocates or
2362  // renews leases. It may be the case that the lease has already been
2363  // reclaimed, so there is nothing to do.
2364  if (!lease->stateExpiredReclaimed()) {
2365  reclaimExpiredLease(lease, DB_RECLAIM_LEAVE_UNCHANGED, callout_handle);
2366  }
2367 }
2368 
2369 void
2370 AllocEngine::reclaimExpiredLease(const Lease6Ptr& lease,
2371  const DbReclaimMode& reclaim_mode,
2372  const CalloutHandlePtr& callout_handle) {
2373 
2375  ALLOC_ENGINE_V6_LEASE_RECLAIM)
2376  .arg(Pkt6::makeLabel(lease->duid_, lease->hwaddr_))
2377  .arg(lease->addr_.toText())
2378  .arg(static_cast<int>(lease->prefixlen_));
2379 
2380  // The skip flag indicates if the callouts have taken responsibility
2381  // for reclaiming the lease. The callout will set this to true if
2382  // it reclaims the lease itself. In this case the reclamation routine
2383  // will not update DNS nor update the database.
2384  bool skipped = false;
2385  if (callout_handle) {
2386 
2387  // Use the RAII wrapper to make sure that the callout handle state is
2388  // reset when this object goes out of scope. All hook points must do
2389  // it to prevent possible circular dependency between the callout
2390  // handle and its arguments.
2391  ScopedCalloutHandleState callout_handle_state(callout_handle);
2392 
2393  callout_handle->deleteAllArguments();
2394  callout_handle->setArgument("lease6", lease);
2395  callout_handle->setArgument("remove_lease", reclaim_mode == DB_RECLAIM_REMOVE);
2396 
2397  HooksManager::callCallouts(Hooks.hook_index_lease6_expire_,
2398  *callout_handle);
2399 
2400  skipped = callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP;
2401  }
2402 
2405 
2406  if (!skipped) {
2407 
2408  // Generate removal name change request for D2, if required.
2409  // This will return immediately if the DNS wasn't updated
2410  // when the lease was created.
2411  queueNCR(CHG_REMOVE, lease);
2412 
2413  // Let's check if the lease that just expired is in DECLINED state.
2414  // If it is, we need to perform a couple extra steps.
2415  bool remove_lease = (reclaim_mode == DB_RECLAIM_REMOVE);
2416  if (lease->state_ == Lease::STATE_DECLINED) {
2417  // Do extra steps required for declined lease reclamation:
2418  // - call the recover hook
2419  // - bump decline-related stats
2420  // - log separate message
2421  // There's no point in keeping a declined lease after its
2422  // reclamation. A declined lease doesn't have any client
2423  // identifying information anymore. So we'll flag it for
2424  // removal unless the hook has set the skip flag.
2425  remove_lease = reclaimDeclined(lease);
2426  }
2427 
2428  if (reclaim_mode != DB_RECLAIM_LEAVE_UNCHANGED) {
2429  // Reclaim the lease - depending on the configuration, set the
2430  // expired-reclaimed state or simply remove it.
2431  LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
2432  reclaimLeaseInDatabase<Lease6Ptr>(lease, remove_lease,
2433  boost::bind(&LeaseMgr::updateLease6,
2434  &lease_mgr, _1));
2435  }
2436  }
2437 
2438  // Update statistics.
2439 
2440  // Decrease number of assigned leases.
2441  if (lease->type_ == Lease::TYPE_NA) {
2442  // IA_NA
2443  StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
2444  lease->subnet_id_,
2445  "assigned-nas"),
2446  int64_t(-1));
2447 
2448  } else if (lease->type_ == Lease::TYPE_PD) {
2449  // IA_PD
2450  StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
2451  lease->subnet_id_,
2452  "assigned-pds"),
2453  int64_t(-1));
2454 
2455  }
2456 
2457  // Increase total number of reclaimed leases.
2458  StatsMgr::instance().addValue("reclaimed-leases", int64_t(1));
2459 
2460  // Increase number of reclaimed leases for a subnet.
2461  StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
2462  lease->subnet_id_,
2463  "reclaimed-leases"),
2464  int64_t(1));
2465 }
2466 
2467 void
2468 AllocEngine::reclaimExpiredLease(const Lease4Ptr& lease,
2469  const DbReclaimMode& reclaim_mode,
2470  const CalloutHandlePtr& callout_handle) {
2471 
2473  ALLOC_ENGINE_V4_LEASE_RECLAIM)
2474  .arg(Pkt4::makeLabel(lease->hwaddr_, lease->client_id_))
2475  .arg(lease->addr_.toText());
2476 
2477  // The skip flag indicates if the callouts have taken responsibility
2478  // for reclaiming the lease. The callout will set this to true if
2479  // it reclaims the lease itself. In this case the reclamation routine
2480  // will not update DNS nor update the database.
2481  bool skipped = false;
2482  if (callout_handle) {
2483 
2484  // Use the RAII wrapper to make sure that the callout handle state is
2485  // reset when this object goes out of scope. All hook points must do
2486  // it to prevent possible circular dependency between the callout
2487  // handle and its arguments.
2488  ScopedCalloutHandleState callout_handle_state(callout_handle);
2489 
2490  callout_handle->setArgument("lease4", lease);
2491  callout_handle->setArgument("remove_lease", reclaim_mode == DB_RECLAIM_REMOVE);
2492 
2493  HooksManager::callCallouts(Hooks.hook_index_lease4_expire_,
2494  *callout_handle);
2495 
2496  skipped = callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP;
2497  }
2498 
2501 
2502  if (!skipped) {
2503 
2504  // Generate removal name change request for D2, if required.
2505  // This will return immediately if the DNS wasn't updated
2506  // when the lease was created.
2507  queueNCR(CHG_REMOVE, lease);
2508 
2509  // Let's check if the lease that just expired is in DECLINED state.
2510  // If it is, we need to perform a couple extra steps.
2511  bool remove_lease = (reclaim_mode == DB_RECLAIM_REMOVE);
2512  if (lease->state_ == Lease::STATE_DECLINED) {
2513  // Do extra steps required for declined lease reclamation:
2514  // - call the recover hook
2515  // - bump decline-related stats
2516  // - log separate message
2517  // There's no point in keeping a declined lease after its
2518  // reclamation. A declined lease doesn't have any client
2519  // identifying information anymore. So we'll flag it for
2520  // removal unless the hook has set the skip flag.
2521  remove_lease = reclaimDeclined(lease);
2522  }
2523 
2524  if (reclaim_mode != DB_RECLAIM_LEAVE_UNCHANGED) {
2525  // Reclaim the lease - depending on the configuration, set the
2526  // expired-reclaimed state or simply remove it.
2527  LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
2528  reclaimLeaseInDatabase<Lease4Ptr>(lease, remove_lease,
2529  boost::bind(&LeaseMgr::updateLease4,
2530  &lease_mgr, _1));
2531  }
2532  }
2533 
2534  // Update statistics.
2535 
2536  // Decrease number of assigned addresses.
2537  StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
2538  lease->subnet_id_,
2539  "assigned-addresses"),
2540  int64_t(-1));
2541 
2542  // Increase total number of reclaimed leases.
2543  StatsMgr::instance().addValue("reclaimed-leases", int64_t(1));
2544 
2545  // Increase number of reclaimed leases for a subnet.
2546  StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
2547  lease->subnet_id_,
2548  "reclaimed-leases"),
2549  int64_t(1));
2550 }
2551 
2552 void
2555  ALLOC_ENGINE_V4_RECLAIMED_LEASES_DELETE)
2556  .arg(secs);
2557 
2558  uint64_t deleted_leases = 0;
2559  try {
2560  // Try to delete leases from the lease database.
2561  LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
2562  deleted_leases = lease_mgr.deleteExpiredReclaimedLeases4(secs);
2563 
2564  } catch (const std::exception& ex) {
2565  LOG_ERROR(alloc_engine_logger, ALLOC_ENGINE_V4_RECLAIMED_LEASES_DELETE_FAILED)
2566  .arg(ex.what());
2567  }
2568 
2570  ALLOC_ENGINE_V4_RECLAIMED_LEASES_DELETE_COMPLETE)
2571  .arg(deleted_leases);
2572 }
2573 
2574 bool
2575 AllocEngine::reclaimDeclined(const Lease4Ptr& lease) {
2576 
2577  if (!lease || (lease->state_ != Lease::STATE_DECLINED) ) {
2578  return (true);
2579  }
2580 
2581  if (HooksManager::getHooksManager().calloutsPresent(Hooks.hook_index_lease4_recover_)) {
2582 
2583  // Let's use a static callout handle. It will be initialized the first
2584  // time lease4_recover is called and will keep to that value.
2585  static CalloutHandlePtr callout_handle;
2586  if (!callout_handle) {
2587  callout_handle = HooksManager::createCalloutHandle();
2588  }
2589 
2590  // Use the RAII wrapper to make sure that the callout handle state is
2591  // reset when this object goes out of scope. All hook points must do
2592  // it to prevent possible circular dependency between the callout
2593  // handle and its arguments.
2594  ScopedCalloutHandleState callout_handle_state(callout_handle);
2595 
2596  // Pass necessary arguments
2597  callout_handle->setArgument("lease4", lease);
2598 
2599  // Call the callouts
2600  HooksManager::callCallouts(Hooks.hook_index_lease4_recover_, *callout_handle);
2601 
2602  // Callouts decided to skip the action. This means that the lease is not
2603  // assigned, so the client will get NoAddrAvail as a result. The lease
2604  // won't be inserted into the database.
2605  if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
2606  LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE4_RECOVER_SKIP)
2607  .arg(lease->addr_.toText());
2608  return (false);
2609  }
2610  }
2611 
2612  LOG_INFO(alloc_engine_logger, ALLOC_ENGINE_V4_DECLINED_RECOVERED)
2613  .arg(lease->addr_.toText())
2614  .arg(lease->valid_lft_);
2615 
2616  StatsMgr& stats_mgr = StatsMgr::instance();
2617 
2618  // Decrease subnet specific counter for currently declined addresses
2619  stats_mgr.addValue(StatsMgr::generateName("subnet", lease->subnet_id_,
2620  "declined-addresses"), static_cast<int64_t>(-1));
2621 
2622  // Decrease global counter for declined addresses
2623  stats_mgr.addValue("declined-addresses", static_cast<int64_t>(-1));
2624 
2625  stats_mgr.addValue("reclaimed-declined-addresses", static_cast<int64_t>(1));
2626 
2627  stats_mgr.addValue(StatsMgr::generateName("subnet", lease->subnet_id_,
2628  "reclaimed-declined-addresses"), static_cast<int64_t>(1));
2629 
2630  // Note that we do not touch assigned-addresses counters. Those are
2631  // modified in whatever code calls this method.
2632  return (true);
2633 }
2634 
2635 bool
2636 AllocEngine::reclaimDeclined(const Lease6Ptr& lease) {
2637 
2638  if (!lease || (lease->state_ != Lease::STATE_DECLINED) ) {
2639  return (true);
2640  }
2641 
2642  if (HooksManager::getHooksManager().calloutsPresent(Hooks.hook_index_lease6_recover_)) {
2643 
2644  // Let's use a static callout handle. It will be initialized the first
2645  // time lease6_recover is called and will keep to that value.
2646  static CalloutHandlePtr callout_handle;
2647  if (!callout_handle) {
2648  callout_handle = HooksManager::createCalloutHandle();
2649  }
2650 
2651  // Use the RAII wrapper to make sure that the callout handle state is
2652  // reset when this object goes out of scope. All hook points must do
2653  // it to prevent possible circular dependency between the callout
2654  // handle and its arguments.
2655  ScopedCalloutHandleState callout_handle_state(callout_handle);
2656 
2657  // Pass necessary arguments
2658  callout_handle->setArgument("lease6", lease);
2659 
2660  // Call the callouts
2661  HooksManager::callCallouts(Hooks.hook_index_lease6_recover_, *callout_handle);
2662 
2663  // Callouts decided to skip the action. This means that the lease is not
2664  // assigned, so the client will get NoAddrAvail as a result. The lease
2665  // won't be inserted into the database.
2666  if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
2667  LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE6_RECOVER_SKIP)
2668  .arg(lease->addr_.toText());
2669  return (false);
2670  }
2671  }
2672 
2673  LOG_INFO(alloc_engine_logger, ALLOC_ENGINE_V6_DECLINED_RECOVERED)
2674  .arg(lease->addr_.toText())
2675  .arg(lease->valid_lft_);
2676 
2677  StatsMgr& stats_mgr = StatsMgr::instance();
2678 
2679  // Decrease subnet specific counter for currently declined addresses
2680  stats_mgr.addValue(StatsMgr::generateName("subnet", lease->subnet_id_,
2681  "declined-addresses"), static_cast<int64_t>(-1));
2682 
2683  // Decrease global counter for declined addresses
2684  stats_mgr.addValue("declined-addresses", static_cast<int64_t>(-1));
2685 
2686  stats_mgr.addValue("reclaimed-declined-addresses", static_cast<int64_t>(1));
2687 
2688  stats_mgr.addValue(StatsMgr::generateName("subnet", lease->subnet_id_,
2689  "reclaimed-declined-addresses"), static_cast<int64_t>(1));
2690 
2691  // Note that we do not touch assigned-addresses counters. Those are
2692  // modified in whatever code calls this method.
2693 
2694  return (true);
2695 }
2696 
2697 
2698 template<typename LeasePtrType>
2699 void AllocEngine::reclaimLeaseInDatabase(const LeasePtrType& lease,
2700  const bool remove_lease,
2701  const boost::function<void (const LeasePtrType&)>&
2702  lease_update_fun) const {
2703 
2704  LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
2705 
2706  // Reclaim the lease - depending on the configuration, set the
2707  // expired-reclaimed state or simply remove it.
2708  if (remove_lease) {
2709  lease_mgr.deleteLease(lease->addr_);
2710 
2711  } else if (!lease_update_fun.empty()) {
2712  // Clear FQDN information as we have already sent the
2713  // name change request to remove the DNS record.
2714  lease->hostname_.clear();
2715  lease->fqdn_fwd_ = false;
2716  lease->fqdn_rev_ = false;
2717  lease->state_ = Lease::STATE_EXPIRED_RECLAIMED;
2718  lease_update_fun(lease);
2719 
2720  } else {
2721  return;
2722  }
2723 
2724  // Lease has been reclaimed.
2726  ALLOC_ENGINE_LEASE_RECLAIMED)
2727  .arg(lease->addr_.toText());
2728 }
2729 
2730 
2731 } // end of isc::dhcp namespace
2732 } // end of isc namespace
2733 
2734 // ##########################################################################
2735 // # DHCPv4 lease allocation code starts here.
2736 // ##########################################################################
2737 
2738 namespace {
2739 
2753 bool
2754 addressReserved(const IOAddress& address, const AllocEngine::ClientContext4& ctx) {
2755  if (ctx.subnet_ &&
2756  ((ctx.subnet_->getHostReservationMode() == Network::HR_ALL) ||
2757  ((ctx.subnet_->getHostReservationMode() == Network::HR_OUT_OF_POOL) &&
2758  (!ctx.subnet_->inPool(Lease::TYPE_V4, address))))) {
2759  ConstHostPtr host = HostMgr::instance().get4(ctx.subnet_->getID(), address);
2760  if (host) {
2761  for (auto id = ctx.host_identifiers_.cbegin(); id != ctx.host_identifiers_.cend();
2762  ++id) {
2763  if (id->first == host->getIdentifierType()) {
2764  return (id->second != host->getIdentifier());
2765  }
2766  }
2767  return (true);
2768  }
2769  }
2770  return (false);
2771 }
2772 
2788 bool
2789 hasAddressReservation(AllocEngine::ClientContext4& ctx) {
2790  if (ctx.hosts_.empty()) {
2791  return (false);
2792  }
2793 
2794  Subnet4Ptr subnet = ctx.subnet_;
2795  while (subnet) {
2796  if (subnet->getHostReservationMode() == Network::HR_GLOBAL) {
2797  auto host = ctx.hosts_.find(SUBNET_ID_GLOBAL);
2798  return (host != ctx.hosts_.end() &&
2799  !(host->second->getIPv4Reservation().isV4Zero()));
2800  // if we want global + other modes we would need to
2801  // return only if true, else continue
2802  }
2803 
2804  auto host = ctx.hosts_.find(subnet->getID());
2805  if ((host != ctx.hosts_.end()) &&
2806  !(host->second->getIPv4Reservation().isV4Zero()) &&
2807  ((subnet->getHostReservationMode() == Network::HR_ALL) ||
2808  ((subnet->getHostReservationMode() == Network::HR_OUT_OF_POOL) &&
2809  (!subnet->inPool(Lease::TYPE_V4, host->second->getIPv4Reservation()))))) {
2810  ctx.subnet_ = subnet;
2811  return (true);
2812  }
2813 
2814  // No address reservation found here, so let's try another subnet
2815  // within the same shared network.
2816  subnet = subnet->getNextSubnet(ctx.subnet_, ctx.query_->getClasses());
2817  }
2818 
2819  return (false);
2820 }
2821 
2837 void findClientLease(AllocEngine::ClientContext4& ctx, Lease4Ptr& client_lease) {
2838  LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
2839 
2840  Subnet4Ptr original_subnet = ctx.subnet_;
2841  Subnet4Ptr subnet = ctx.subnet_;
2842 
2843  // Client identifier is optional. If it is specified, use it to try to find
2844  // client's lease.
2845  if (ctx.clientid_) {
2846  // Get all leases for this client identifier. When shared networks are
2847  // in use it is more efficient to make a single query rather than
2848  // multiple queries, one for each subnet.
2849  Lease4Collection leases_client_id = lease_mgr.getLease4(*ctx.clientid_);
2850 
2851  // Iterate over the subnets within the shared network to see if any client's
2852  // lease belongs to them.
2853  while (subnet) {
2854 
2855  // If client identifier has been supplied and the server wasn't
2856  // explicitly configured to ignore client identifiers for this subnet
2857  // check if there is a lease within this subnet.
2858  if (ctx.clientid_ && subnet->getMatchClientId()) {
2859  for (auto l = leases_client_id.begin(); l != leases_client_id.end(); ++l) {
2860  if ((*l)->subnet_id_ == subnet->getID()) {
2861  // Lease found, so stick to this lease.
2862  client_lease = (*l);
2863  ctx.subnet_ = subnet;
2864  return;
2865  }
2866  }
2867  }
2868 
2869  // Haven't found any lease in this subnet, so let's try another subnet
2870  // within the shared network.
2871  subnet = subnet->getNextSubnet(original_subnet, ctx.query_->getClasses());
2872  }
2873  }
2874 
2875  // If no lease found using the client identifier, try the lookup using
2876  // the HW address.
2877  if (!client_lease && ctx.hwaddr_) {
2878 
2879  // Rewind to the first subnet.
2880  subnet = original_subnet;
2881 
2882  // Get all leases for this HW address.
2883  Lease4Collection leases_hw_address = lease_mgr.getLease4(*ctx.hwaddr_);
2884 
2885  while (subnet) {
2886  ClientIdPtr client_id;
2887  if (subnet->getMatchClientId()) {
2888  client_id = ctx.clientid_;
2889  }
2890 
2891  // Try to find the lease that matches current subnet and belongs to
2892  // this client, so both HW address and client identifier match.
2893  for (Lease4Collection::const_iterator client_lease_it = leases_hw_address.begin();
2894  client_lease_it != leases_hw_address.end(); ++client_lease_it) {
2895  Lease4Ptr existing_lease = *client_lease_it;
2896  if ((existing_lease->subnet_id_ == subnet->getID()) &&
2897  existing_lease->belongsToClient(ctx.hwaddr_, client_id)) {
2898  // Found the lease of this client, so return it.
2899  client_lease = existing_lease;
2900  // We got a lease but the subnet it belongs to may differ from
2901  // the original subnet. Let's now stick to this subnet.
2902  ctx.subnet_ = subnet;
2903  return;
2904  }
2905  }
2906 
2907  // Haven't found any lease in this subnet, so let's try another subnet
2908  // within the shared network.
2909  subnet = subnet->getNextSubnet(original_subnet, ctx.query_->getClasses());
2910  }
2911  }
2912 }
2913 
2926 bool
2927 inAllowedPool(AllocEngine::ClientContext4& ctx, const IOAddress& address) {
2928  // If the subnet belongs to a shared network we will be iterating
2929  // over the subnets that belong to this shared network.
2930  Subnet4Ptr current_subnet = ctx.subnet_;
2931  while (current_subnet) {
2932 
2933  if (current_subnet->inPool(Lease::TYPE_V4, address,
2934  ctx.query_->getClasses())) {
2935  // We found a subnet that this address belongs to, so it
2936  // seems that this subnet is the good candidate for allocation.
2937  // Let's update the selected subnet.
2938  ctx.subnet_ = current_subnet;
2939  return (true);
2940  }
2941 
2942  current_subnet = current_subnet->getNextSubnet(ctx.subnet_,
2943  ctx.query_->getClasses());
2944  }
2945 
2946  return (false);
2947 }
2948 
2949 } // end of anonymous namespace
2950 
2951 namespace isc {
2952 namespace dhcp {
2953 
2955  : subnet_(), clientid_(), hwaddr_(),
2956  requested_address_(IOAddress::IPV4_ZERO_ADDRESS()),
2957  fwd_dns_update_(false), rev_dns_update_(false),
2958  hostname_(""), callout_handle_(), fake_allocation_(false),
2959  old_lease_(), new_lease_(), hosts_(), conflicting_lease_(),
2960  query_(), host_identifiers_() {
2961 }
2962 
2964  const ClientIdPtr& clientid,
2965  const HWAddrPtr& hwaddr,
2966  const asiolink::IOAddress& requested_addr,
2967  const bool fwd_dns_update,
2968  const bool rev_dns_update,
2969  const std::string& hostname,
2970  const bool fake_allocation)
2971  : subnet_(subnet), clientid_(clientid), hwaddr_(hwaddr),
2972  requested_address_(requested_addr),
2973  fwd_dns_update_(fwd_dns_update), rev_dns_update_(rev_dns_update),
2974  hostname_(hostname), callout_handle_(),
2975  fake_allocation_(fake_allocation), old_lease_(), new_lease_(),
2976  hosts_(), host_identifiers_() {
2977 
2978  // Initialize host identifiers.
2979  if (hwaddr) {
2980  addHostIdentifier(Host::IDENT_HWADDR, hwaddr->hwaddr_);
2981  }
2982 }
2983 
2986  if (subnet_) {
2987  SubnetID id = (subnet_->getHostReservationMode() == Network::HR_GLOBAL ?
2988  SUBNET_ID_GLOBAL : subnet_->getID());
2989 
2990  auto host = hosts_.find(id);
2991  if (host != hosts_.cend()) {
2992  return (host->second);
2993  }
2994  }
2995  return (ConstHostPtr());
2996 }
2997 
2998 Lease4Ptr
3000  // The NULL pointer indicates that the old lease didn't exist. It may
3001  // be later set to non NULL value if existing lease is found in the
3002  // database.
3003  ctx.old_lease_.reset();
3004  ctx.new_lease_.reset();
3005 
3006  // Before we start allocation process, we need to make sure that the
3007  // selected subnet is allowed for this client. If not, we'll try to
3008  // use some other subnet within the shared network. If there are no
3009  // subnets allowed for this client within the shared network, we
3010  // can't allocate a lease.
3011  Subnet4Ptr subnet = ctx.subnet_;
3012  if (subnet && !subnet->clientSupported(ctx.query_->getClasses())) {
3013  ctx.subnet_ = subnet->getNextSubnet(subnet, ctx.query_->getClasses());
3014  }
3015 
3016  try {
3017  if (!ctx.subnet_) {
3018  isc_throw(BadValue, "Can't allocate IPv4 address without subnet");
3019  }
3020 
3021  if (!ctx.hwaddr_) {
3022  isc_throw(BadValue, "HWAddr must be defined");
3023  }
3024 
3025  if (ctx.fake_allocation_) {
3026  return (discoverLease4(ctx));
3027 
3028  } else {
3029  ctx.new_lease_ = requestLease4(ctx);
3030  }
3031 
3032  } catch (const isc::Exception& e) {
3033  // Some other error, return an empty lease.
3034  LOG_ERROR(alloc_engine_logger, ALLOC_ENGINE_V4_ALLOC_ERROR)
3035  .arg(ctx.query_->getLabel())
3036  .arg(e.what());
3037  }
3038 
3039  return (ctx.new_lease_);
3040 }
3041 
3042 void
3044  ctx.hosts_.clear();
3045 
3046  // If there is no subnet, there is nothing to do.
3047  if (!ctx.subnet_) {
3048  return;
3049  }
3050 
3051  auto subnet = ctx.subnet_;
3052 
3053  std::map<SubnetID, ConstHostPtr> host_map;
3054  SharedNetwork4Ptr network;
3055  subnet->getSharedNetwork(network);
3056 
3057  if (subnet->getHostReservationMode() == Network::HR_GLOBAL) {
3058  ConstHostPtr ghost = findGlobalReservation(ctx);
3059  if (ghost) {
3060  ctx.hosts_[SUBNET_ID_GLOBAL] = ghost;
3061 
3062  // @todo In theory, to support global as part of HR_ALL,
3063  // we would just keep going, instead of returning.
3064  return;
3065  }
3066  }
3067 
3068  // If the subnet belongs to a shared network it is usually going to be
3069  // more efficient to make a query for all reservations for a particular
3070  // client rather than a query for each subnet within this shared network.
3071  // The only case when it is going to be less efficient is when there are
3072  // more host identifier types in use than subnets within a shared network.
3073  const bool use_single_query = network &&
3074  (network->getAllSubnets()->size() > ctx.host_identifiers_.size());
3075 
3076  if (use_single_query) {
3077  for (auto id_pair = ctx.host_identifiers_.begin();
3078  id_pair != ctx.host_identifiers_.end();
3079  ++id_pair) {
3080  ConstHostCollection hosts = HostMgr::instance().getAll(id_pair->first,
3081  &id_pair->second[0],
3082  id_pair->second.size());
3083  // Store the hosts in the temporary map, because some hosts may
3084  // belong to subnets outside of the shared network. We'll need
3085  // to eliminate them.
3086  for (auto host = hosts.begin(); host != hosts.end(); ++host) {
3087  if ((*host)->getIPv4SubnetID() > 0) {
3088  host_map[(*host)->getIPv4SubnetID()] = *host;
3089  }
3090  }
3091  }
3092  }
3093 
3094  // We can only search for the reservation if a subnet has been selected.
3095  while (subnet) {
3096 
3097  // Only makes sense to get reservations if the client has access
3098  // to the class.
3099  if (subnet->clientSupported(ctx.query_->getClasses()) &&
3100  (subnet->getHostReservationMode() != Network::HR_DISABLED)) {
3101  // Iterate over configured identifiers in the order of preference
3102  // and try to use each of them to search for the reservations.
3103  BOOST_FOREACH(const IdentifierPair& id_pair, ctx.host_identifiers_) {
3104  if (use_single_query) {
3105  if (host_map.count(subnet->getID()) > 0) {
3106  ctx.hosts_[subnet->getID()] = host_map[subnet->getID()];
3107  break;
3108  }
3109 
3110  } else {
3111  // Attempt to find a host using a specified identifier.
3112  ConstHostPtr host = HostMgr::instance().get4(subnet->getID(),
3113  id_pair.first,
3114  &id_pair.second[0],
3115  id_pair.second.size());
3116  // If we found matching host for this subnet.
3117  if (host) {
3118  ctx.hosts_[subnet->getID()] = host;
3119  break;
3120  }
3121  }
3122  }
3123  }
3124 
3125  // We need to get to the next subnet if this is a shared network. If it
3126  // is not (a plain subnet), getNextSubnet will return NULL and we're
3127  // done here.
3128  subnet = subnet->getNextSubnet(ctx.subnet_, ctx.query_->getClasses());
3129  }
3130 }
3131 
3134  ConstHostPtr host;
3135  BOOST_FOREACH(const IdentifierPair& id_pair, ctx.host_identifiers_) {
3136  // Attempt to find a host using a specified identifier.
3137  host = HostMgr::instance().get4(SUBNET_ID_GLOBAL, id_pair.first,
3138  &id_pair.second[0], id_pair.second.size());
3139 
3140  // If we found matching global host we're done.
3141  if (host) {
3142  break;
3143  }
3144  }
3145 
3146  return (host);
3147 }
3148 
3149 
3150 Lease4Ptr
3151 AllocEngine::discoverLease4(AllocEngine::ClientContext4& ctx) {
3152  // Find an existing lease for this client. This function will return true
3153  // if there is a conflict with existing lease and the allocation should
3154  // not be continued.
3155  Lease4Ptr client_lease;
3156  findClientLease(ctx, client_lease);
3157 
3158  // new_lease will hold the pointer to the lease that we will offer to the
3159  // caller.
3160  Lease4Ptr new_lease;
3161 
3162  CalloutHandle::CalloutNextStep callout_status = CalloutHandle::NEXT_STEP_CONTINUE;
3163 
3164  // Check if there is a reservation for the client. If there is, we want to
3165  // assign the reserved address, rather than any other one.
3166  if (hasAddressReservation(ctx)) {
3167 
3169  ALLOC_ENGINE_V4_DISCOVER_HR)
3170  .arg(ctx.query_->getLabel())
3171  .arg(ctx.currentHost()->getIPv4Reservation().toText());
3172 
3173  // If the client doesn't have a lease or the leased address is different
3174  // than the reserved one then let's try to allocate the reserved address.
3175  // Otherwise the address that the client has is the one for which it
3176  // has a reservation, so just renew it.
3177  if (!client_lease || (client_lease->addr_ != ctx.currentHost()->getIPv4Reservation())) {
3178  // The call below will return a pointer to the lease for the address
3179  // reserved to this client, if the lease is available, i.e. is not
3180  // currently assigned to any other client.
3181  // Note that we don't remove the existing client's lease at this point
3182  // because this is not a real allocation, we just offer what we can
3183  // allocate in the DHCPREQUEST time.
3184  new_lease = allocateOrReuseLease4(ctx.currentHost()->getIPv4Reservation(), ctx,
3185  callout_status);
3186  if (!new_lease) {
3187  LOG_WARN(alloc_engine_logger, ALLOC_ENGINE_V4_DISCOVER_ADDRESS_CONFLICT)
3188  .arg(ctx.query_->getLabel())
3189  .arg(ctx.currentHost()->getIPv4Reservation().toText())
3190  .arg(ctx.conflicting_lease_ ? ctx.conflicting_lease_->toText() :
3191  "(no lease info)");
3192  }
3193 
3194  } else {
3195  new_lease = renewLease4(client_lease, ctx);
3196  }
3197  }
3198 
3199  // Client does not have a reservation or the allocation of the reserved
3200  // address has failed, probably because the reserved address is in use
3201  // by another client. If the client has a lease, we will check if we can
3202  // offer this lease to the client. The lease can't be offered in the
3203  // situation when it is reserved for another client or when the address
3204  // is not in the dynamic pool. The former may be the result of adding the
3205  // new reservation for the address used by this client. The latter may
3206  // be due to the client using the reserved out-of-the pool address, for
3207  // which the reservation has just been removed.
3208  if (!new_lease && client_lease && inAllowedPool(ctx, client_lease->addr_) &&
3209  !addressReserved(client_lease->addr_, ctx)) {
3210 
3212  ALLOC_ENGINE_V4_OFFER_EXISTING_LEASE)
3213  .arg(ctx.query_->getLabel());
3214 
3215  new_lease = renewLease4(client_lease, ctx);
3216  }
3217 
3218  // The client doesn't have any lease or the lease can't be offered
3219  // because it is either reserved for some other client or the
3220  // address is not in the dynamic pool.
3221  // Let's use the client's hint (requested IP address), if the client
3222  // has provided it, and try to offer it. This address must not be
3223  // reserved for another client, and must be in the range of the
3224  // dynamic pool.
3225  if (!new_lease && !ctx.requested_address_.isV4Zero() &&
3226  inAllowedPool(ctx, ctx.requested_address_) &&
3227  !addressReserved(ctx.requested_address_, ctx)) {
3228 
3230  ALLOC_ENGINE_V4_OFFER_REQUESTED_LEASE)
3231  .arg(ctx.requested_address_.toText())
3232  .arg(ctx.query_->getLabel());
3233 
3234  new_lease = allocateOrReuseLease4(ctx.requested_address_, ctx,
3235  callout_status);
3236  }
3237 
3238  // The allocation engine failed to allocate all of the candidate
3239  // addresses. We will now use the allocator to pick the address
3240  // from the dynamic pool.
3241  if (!new_lease) {
3242 
3244  ALLOC_ENGINE_V4_OFFER_NEW_LEASE)
3245  .arg(ctx.query_->getLabel());
3246 
3247  new_lease = allocateUnreservedLease4(ctx);
3248  }
3249 
3250  // Some of the methods like reuseExpiredLease4 may set the old lease to point
3251  // to the lease which they remove/override. If it is not set, but we have
3252  // found that the client has the lease the client's lease is the one
3253  // to return as an old lease.
3254  if (!ctx.old_lease_ && client_lease) {
3255  ctx.old_lease_ = client_lease;
3256  }
3257 
3258  return (new_lease);
3259 }
3260 
3261 Lease4Ptr
3262 AllocEngine::requestLease4(AllocEngine::ClientContext4& ctx) {
3263  // Find an existing lease for this client. This function will return true
3264  // if there is a conflict with existing lease and the allocation should
3265  // not be continued.
3266  Lease4Ptr client_lease;
3267  findClientLease(ctx, client_lease);
3268 
3269  // Obtain the sole instance of the LeaseMgr.
3270  LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
3271 
3272  // When the client sends the DHCPREQUEST, it should always specify the
3273  // address which it is requesting or renewing. That is, the client should
3274  // either use the requested IP address option or set the ciaddr. However,
3275  // we try to be liberal and allow the clients to not specify an address
3276  // in which case the allocation engine will pick a suitable address
3277  // for the client.
3278  if (!ctx.requested_address_.isV4Zero()) {
3279  // If the client has specified an address, make sure this address
3280  // is not reserved for another client. If it is, stop here because
3281  // we can't allocate this address.
3282  if (addressReserved(ctx.requested_address_, ctx)) {
3283 
3285  ALLOC_ENGINE_V4_REQUEST_ADDRESS_RESERVED)
3286  .arg(ctx.query_->getLabel())
3287  .arg(ctx.requested_address_.toText());
3288 
3289  return (Lease4Ptr());
3290  }
3291 
3292  } else if (hasAddressReservation(ctx)) {
3293  // The client hasn't specified an address to allocate, so the
3294  // allocation engine needs to find an appropriate address.
3295  // If there is a reservation for the client, let's try to
3296  // allocate the reserved address.
3297  ctx.requested_address_ = ctx.currentHost()->getIPv4Reservation();
3298 
3300  ALLOC_ENGINE_V4_REQUEST_USE_HR)
3301  .arg(ctx.query_->getLabel())
3302  .arg(ctx.requested_address_.toText());
3303  }
3304 
3305  if (!ctx.requested_address_.isV4Zero()) {
3306  // There is a specific address to be allocated. Let's find out if
3307  // the address is in use.
3309  // If the address is in use (allocated and not expired), we check
3310  // if the address is in use by our client or another client.
3311  // If it is in use by another client, the address can't be
3312  // allocated.
3313  if (existing && !existing->expired() &&
3314  !existing->belongsToClient(ctx.hwaddr_, ctx.subnet_->getMatchClientId() ?
3315  ctx.clientid_ : ClientIdPtr())) {
3316 
3318  ALLOC_ENGINE_V4_REQUEST_IN_USE)
3319  .arg(ctx.query_->getLabel())
3320  .arg(ctx.requested_address_.toText());
3321 
3322  return (Lease4Ptr());
3323  }
3324 
3325  // If the client has a reservation but it is requesting a different
3326  // address it is possible that the client was offered this different
3327  // address because the reserved address is in use. We will have to
3328  // check if the address is in use.
3329  if (hasAddressReservation(ctx) &&
3330  (ctx.currentHost()->getIPv4Reservation() != ctx.requested_address_)) {
3331  existing =
3332  LeaseMgrFactory::instance().getLease4(ctx.currentHost()->getIPv4Reservation());
3333  // If the reserved address is not in use, i.e. the lease doesn't
3334  // exist or is expired, and the client is requesting a different
3335  // address, return NULL. The client should go back to the
3336  // DHCPDISCOVER and the reserved address will be offered.
3337  if (!existing || existing->expired()) {
3338 
3340  ALLOC_ENGINE_V4_REQUEST_INVALID)
3341  .arg(ctx.query_->getLabel())
3342  .arg(ctx.currentHost()->getIPv4Reservation().toText())
3343  .arg(ctx.requested_address_.toText());
3344 
3345  return (Lease4Ptr());
3346  }
3347  }
3348 
3349  // The use of the out-of-pool addresses is only allowed when the requested
3350  // address is reserved for the client. If the address is not reserved one
3351  // and it doesn't belong to the dynamic pool, do not allocate it.
3352  if ((!hasAddressReservation(ctx) ||
3353  (ctx.currentHost()->getIPv4Reservation() != ctx.requested_address_)) &&
3354  !inAllowedPool(ctx, ctx.requested_address_)) {
3355 
3357  ALLOC_ENGINE_V4_REQUEST_OUT_OF_POOL)
3358  .arg(ctx.query_->getLabel())
3359  .arg(ctx.requested_address_);
3360 
3361  return (Lease4Ptr());
3362  }
3363  }
3364 
3365  // We have gone through all the checks, so we can now allocate the address
3366  // for the client.
3367 
3368  // If the client is requesting an address which is assigned to the client
3369  // let's just renew this address. Also, renew this address if the client
3370  // doesn't request any specific address.
3371  // Added extra checks: the address is reserved or belongs to the dynamic
3372  // pool for the case the pool class has changed before the request.
3373  if (client_lease) {
3374  if (((client_lease->addr_ == ctx.requested_address_) ||
3375  ctx.requested_address_.isV4Zero()) &&
3376  (hasAddressReservation(ctx) ||
3377  inAllowedPool(ctx, client_lease->addr_))) {
3378 
3380  ALLOC_ENGINE_V4_REQUEST_EXTEND_LEASE)
3381  .arg(ctx.query_->getLabel())
3382  .arg(ctx.requested_address_);
3383 
3384  return (renewLease4(client_lease, ctx));
3385  }
3386  }
3387 
3388  // new_lease will hold the pointer to the allocated lease if we allocate
3389  // successfully.
3390  Lease4Ptr new_lease;
3391 
3392  // The client doesn't have the lease or it is requesting an address
3393  // which it doesn't have. Let's try to allocate the requested address.
3394  if (!ctx.requested_address_.isV4Zero()) {
3395 
3397  ALLOC_ENGINE_V4_REQUEST_ALLOC_REQUESTED)
3398  .arg(ctx.query_->getLabel())
3399  .arg(ctx.requested_address_.toText());
3400 
3401  // The call below will return a pointer to the lease allocated
3402  // for the client if there is no lease for the requested address,
3403  // or the existing lease has expired. If the allocation fails,
3404  // e.g. because the lease is in use, we will return NULL to
3405  // indicate that we were unable to allocate the lease.
3406  CalloutHandle::CalloutNextStep callout_status = CalloutHandle::NEXT_STEP_CONTINUE;
3407  new_lease = allocateOrReuseLease4(ctx.requested_address_, ctx,
3408  callout_status);
3409 
3410  } else {
3411 
3413  ALLOC_ENGINE_V4_REQUEST_PICK_ADDRESS)
3414  .arg(ctx.query_->getLabel());
3415 
3416  // We will only get here if the client didn't specify which
3417  // address it wanted to be allocated. The allocation engine will
3418  // to pick the address from the dynamic pool.
3419  new_lease = allocateUnreservedLease4(ctx);
3420  }
3421 
3422  // If we allocated the lease for the client, but the client already had a
3423  // lease, we will need to return the pointer to the previous lease and
3424  // the previous lease needs to be removed from the lease database.
3425  if (new_lease && client_lease) {
3426  ctx.old_lease_ = Lease4Ptr(new Lease4(*client_lease));
3427 
3429  ALLOC_ENGINE_V4_REQUEST_REMOVE_LEASE)
3430  .arg(ctx.query_->getLabel())
3431  .arg(client_lease->addr_.toText());
3432 
3433  lease_mgr.deleteLease(client_lease->addr_);
3434 
3435  // Need to decrease statistic for assigned addresses.
3436  StatsMgr::instance().addValue(
3437  StatsMgr::generateName("subnet", client_lease->subnet_id_, "assigned-addresses"),
3438  static_cast<int64_t>(-1));
3439  }
3440 
3441  // Return the allocated lease or NULL pointer if allocation was
3442  // unsuccessful.
3443  return (new_lease);
3444 }
3445 
3446 Lease4Ptr
3447 AllocEngine::createLease4(const ClientContext4& ctx, const IOAddress& addr,
3448  CalloutHandle::CalloutNextStep& callout_status) {
3449  if (!ctx.hwaddr_) {
3450  isc_throw(BadValue, "Can't create a lease with NULL HW address");
3451  }
3452  if (!ctx.subnet_) {
3453  isc_throw(BadValue, "Can't create a lease without a subnet");
3454  }
3455 
3456  time_t now = time(NULL);
3457 
3458  // @todo: remove this kludge?
3459  std::vector<uint8_t> local_copy;
3460  if (ctx.clientid_ && ctx.subnet_->getMatchClientId()) {
3461  local_copy = ctx.clientid_->getDuid();
3462  }
3463  const uint8_t* local_copy0 = local_copy.empty() ? 0 : &local_copy[0];
3464 
3465  Lease4Ptr lease(new Lease4(addr, ctx.hwaddr_, local_copy0, local_copy.size(),
3466  ctx.subnet_->getValid(), ctx.subnet_->getT1(),
3467  ctx.subnet_->getT2(),
3468  now, ctx.subnet_->getID()));
3469 
3470  // Set FQDN specific lease parameters.
3471  lease->fqdn_fwd_ = ctx.fwd_dns_update_;
3472  lease->fqdn_rev_ = ctx.rev_dns_update_;
3473  lease->hostname_ = ctx.hostname_;
3474 
3475  // Let's execute all callouts registered for lease4_select
3476  if (ctx.callout_handle_ &&
3477  HooksManager::getHooksManager().calloutsPresent(hook_index_lease4_select_)) {
3478 
3479  // Use the RAII wrapper to make sure that the callout handle state is
3480  // reset when this object goes out of scope. All hook points must do
3481  // it to prevent possible circular dependency between the callout
3482  // handle and its arguments.
3483  ScopedCalloutHandleState callout_handle_state(ctx.callout_handle_);
3484 
3485  // Enable copying options from the packet within hook library.
3486  ScopedEnableOptionsCopy<Pkt4> query4_options_copy(ctx.query_);
3487 
3488  // Pass necessary arguments
3489  // Pass the original client query
3490  ctx.callout_handle_->setArgument("query4", ctx.query_);
3491 
3492  // Subnet from which we do the allocation (That's as far as we can go
3493  // with using SubnetPtr to point to Subnet4 object. Users should not
3494  // be confused with dynamic_pointer_casts. They should get a concrete
3495  // pointer (Subnet4Ptr) pointing to a Subnet4 object.
3496  Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(ctx.subnet_);
3497  ctx.callout_handle_->setArgument("subnet4", subnet4);
3498 
3499  // Is this solicit (fake = true) or request (fake = false)
3500  ctx.callout_handle_->setArgument("fake_allocation", ctx.fake_allocation_);
3501 
3502  // Pass the intended lease as well
3503  ctx.callout_handle_->setArgument("lease4", lease);
3504 
3505  // This is the first callout, so no need to clear any arguments
3506  HooksManager::callCallouts(hook_index_lease4_select_, *ctx.callout_handle_);
3507 
3508  callout_status = ctx.callout_handle_->getStatus();
3509 
3510  // Callouts decided to skip the action. This means that the lease is not
3511  // assigned, so the client will get NoAddrAvail as a result. The lease
3512  // won't be inserted into the database.
3513  if (callout_status == CalloutHandle::NEXT_STEP_SKIP) {
3514  LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE4_SELECT_SKIP);
3515  return (Lease4Ptr());
3516  }
3517 
3518  // Let's use whatever callout returned. Hopefully it is the same lease
3519  // we handled to it.
3520  ctx.callout_handle_->getArgument("lease4", lease);
3521  }
3522 
3523  if (!ctx.fake_allocation_) {
3524  // That is a real (REQUEST) allocation
3525  bool status = LeaseMgrFactory::instance().addLease(lease);
3526  if (status) {
3527 
3528  // The lease insertion succeeded, let's bump up the statistic.
3529  StatsMgr::instance().addValue(
3530  StatsMgr::generateName("subnet", ctx.subnet_->getID(), "assigned-addresses"),
3531  static_cast<int64_t>(1));
3532 
3533  return (lease);
3534  } else {
3535  // One of many failures with LeaseMgr (e.g. lost connection to the
3536  // database, database failed etc.). One notable case for that
3537  // is that we are working in multi-process mode and we lost a race
3538  // (some other process got that address first)
3539  return (Lease4Ptr());
3540  }
3541  } else {
3542  // That is only fake (DISCOVER) allocation
3543 
3544  // It is for OFFER only. We should not insert the lease into LeaseMgr,
3545  // but rather check that we could have inserted it.
3546  Lease4Ptr existing = LeaseMgrFactory::instance().getLease4(addr);
3547  if (!existing) {
3548  return (lease);
3549  } else {
3550  return (Lease4Ptr());
3551  }
3552  }
3553 }
3554 
3555 Lease4Ptr
3556 AllocEngine::renewLease4(const Lease4Ptr& lease,
3558  if (!lease) {
3559  isc_throw(BadValue, "null lease specified for renewLease4");
3560  }
3561 
3562  // Let's keep the old data. This is essential if we are using memfile
3563  // (the lease returned points directly to the lease4 object in the database)
3564  // We'll need it if we want to skip update (i.e. roll back renewal)
3566  Lease4 old_values = *lease;
3567  ctx.old_lease_.reset(new Lease4(old_values));
3568 
3569  // Update the lease with the information from the context.
3570  updateLease4Information(lease, ctx);
3571 
3572  if (!ctx.fake_allocation_) {
3573  // If the lease is expired we have to reclaim it before
3574  // re-assigning it to the client. The lease reclamation
3575  // involves execution of hooks and DNS update.
3576  if (ctx.old_lease_->expired()) {
3577  reclaimExpiredLease(ctx.old_lease_, ctx.callout_handle_);
3578 
3579  }
3580 
3581  lease->state_ = Lease::STATE_DEFAULT;
3582  }
3583 
3584  bool skip = false;
3585  // Execute all callouts registered for lease4_renew.
3586  if (HooksManager::getHooksManager().
3587  calloutsPresent(Hooks.hook_index_lease4_renew_)) {
3588 
3589  // Use the RAII wrapper to make sure that the callout handle state is
3590  // reset when this object goes out of scope. All hook points must do
3591  // it to prevent possible circular dependency between the callout
3592  // handle and its arguments.
3593  ScopedCalloutHandleState callout_handle_state(ctx.callout_handle_);
3594 
3595  // Enable copying options from the packet within hook library.
3596  ScopedEnableOptionsCopy<Pkt4> query4_options_copy(ctx.query_);
3597 
3598  // Subnet from which we do the allocation. Convert the general subnet
3599  // pointer to a pointer to a Subnet4. Note that because we are using
3600  // boost smart pointers here, we need to do the cast using the boost
3601  // version of dynamic_pointer_cast.
3602  Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(ctx.subnet_);
3603 
3604  // Pass the parameters. Note the clientid is passed only if match-client-id
3605  // is set. This is done that way, because the lease4-renew hook point is
3606  // about renewing a lease and the configuration parameter says the
3607  // client-id should be ignored. Hence no clientid value if match-client-id
3608  // is false.
3609  ctx.callout_handle_->setArgument("query4", ctx.query_);
3610  ctx.callout_handle_->setArgument("subnet4", subnet4);
3611  ctx.callout_handle_->setArgument("clientid", subnet4->getMatchClientId() ?
3612  ctx.clientid_ : ClientIdPtr());
3613  ctx.callout_handle_->setArgument("hwaddr", ctx.hwaddr_);
3614 
3615  // Pass the lease to be updated
3616  ctx.callout_handle_->setArgument("lease4", lease);
3617 
3618  // Call all installed callouts
3619  HooksManager::callCallouts(Hooks.hook_index_lease4_renew_,
3620  *ctx.callout_handle_);
3621 
3622  // Callouts decided to skip the next processing step. The next
3623  // processing step would actually renew the lease, so skip at this
3624  // stage means "keep the old lease as it is".
3625  if (ctx.callout_handle_->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
3626  skip = true;
3628  DHCPSRV_HOOK_LEASE4_RENEW_SKIP);
3629  }
3630 
3632  }
3633 
3634  if (!ctx.fake_allocation_ && !skip) {
3635  // for REQUEST we do update the lease
3637 
3638  // We need to account for the re-assignment of The lease.
3639  if (ctx.old_lease_->expired() || ctx.old_lease_->state_ == Lease::STATE_EXPIRED_RECLAIMED) {
3640  StatsMgr::instance().addValue(
3641  StatsMgr::generateName("subnet", ctx.subnet_->getID(), "assigned-addresses"),
3642  static_cast<int64_t>(1));
3643  }
3644  }
3645  if (skip) {
3646  // Rollback changes (really useful only for memfile)
3648  *lease = old_values;
3649  }
3650 
3651  return (lease);
3652 }
3653 
3654 Lease4Ptr
3655 AllocEngine::reuseExpiredLease4(Lease4Ptr& expired,
3657  CalloutHandle::CalloutNextStep& callout_status) {
3658  if (!expired) {
3659  isc_throw(BadValue, "null lease specified for reuseExpiredLease");
3660  }
3661 
3662  if (!ctx.subnet_) {
3663  isc_throw(BadValue, "null subnet specified for the reuseExpiredLease");
3664  }
3665 
3666  if (!ctx.fake_allocation_) {
3667  // The expired lease needs to be reclaimed before it can be reused.
3668  // This includes declined leases for which probation period has
3669  // elapsed.
3670  reclaimExpiredLease(expired, ctx.callout_handle_);
3671  expired->state_ = Lease::STATE_DEFAULT;
3672  }
3673 
3674  updateLease4Information(expired, ctx);
3675 
3677  ALLOC_ENGINE_V4_REUSE_EXPIRED_LEASE_DATA)
3678  .arg(ctx.query_->getLabel())
3679  .arg(expired->toText());
3680 
3681  // Let's execute all callouts registered for lease4_select
3682  if (ctx.callout_handle_ && HooksManager::getHooksManager()
3683  .calloutsPresent(hook_index_lease4_select_)) {
3684 
3685  // Enable copying options from the packet within hook library.
3686  ScopedEnableOptionsCopy<Pkt4> query4_options_copy(ctx.query_);
3687 
3688  // Use the RAII wrapper to make sure that the callout handle state is
3689  // reset when this object goes out of scope. All hook points must do
3690  // it to prevent possible circular dependency between the callout
3691  // handle and its arguments.
3692  ScopedCalloutHandleState callout_handle_state(ctx.callout_handle_);
3693 
3694  // Pass necessary arguments
3695  // Pass the original client query
3696  ctx.callout_handle_->setArgument("query4", ctx.query_);
3697 
3698  // Subnet from which we do the allocation. Convert the general subnet
3699  // pointer to a pointer to a Subnet4. Note that because we are using
3700  // boost smart pointers here, we need to do the cast using the boost
3701  // version of dynamic_pointer_cast.
3702  Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(ctx.subnet_);
3703  ctx.callout_handle_->setArgument("subnet4", subnet4);
3704 
3705  // Is this solicit (fake = true) or request (fake = false)
3706  ctx.callout_handle_->setArgument("fake_allocation",
3707  ctx.fake_allocation_);
3708 
3709  // The lease that will be assigned to a client
3710  ctx.callout_handle_->setArgument("lease4", expired);
3711 
3712  // Call the callouts
3713  HooksManager::callCallouts(hook_index_lease4_select_, *ctx.callout_handle_);
3714 
3715  callout_status = ctx.callout_handle_->getStatus();
3716 
3717  // Callouts decided to skip the action. This means that the lease is not
3718  // assigned, so the client will get NoAddrAvail as a result. The lease
3719  // won't be inserted into the database.
3720  if (callout_status == CalloutHandle::NEXT_STEP_SKIP) {
3722  DHCPSRV_HOOK_LEASE4_SELECT_SKIP);
3723  return (Lease4Ptr());
3724  }
3725 
3727 
3728  // Let's use whatever callout returned. Hopefully it is the same lease
3729  // we handed to it.
3730  ctx.callout_handle_->getArgument("lease4", expired);
3731  }
3732 
3733  if (!ctx.fake_allocation_) {
3734  // for REQUEST we do update the lease
3736 
3737  // We need to account for the re-assignment of The lease.
3738  StatsMgr::instance().addValue(
3739  StatsMgr::generateName("subnet", ctx.subnet_->getID(), "assigned-addresses"),
3740  static_cast<int64_t>(1));
3741  }
3742 
3743  // We do nothing for SOLICIT. We'll just update database when
3744  // the client gets back to us with REQUEST message.
3745 
3746  // it's not really expired at this stage anymore - let's return it as
3747  // an updated lease
3748  return (expired);
3749 }
3750 
3751 Lease4Ptr
3752 AllocEngine::allocateOrReuseLease4(const IOAddress& candidate, ClientContext4& ctx,
3753  CalloutHandle::CalloutNextStep& callout_status) {
3754  ctx.conflicting_lease_.reset();
3755 
3756  Lease4Ptr exist_lease = LeaseMgrFactory::instance().getLease4(candidate);
3757  if (exist_lease) {
3758  if (exist_lease->expired()) {
3759  ctx.old_lease_ = Lease4Ptr(new Lease4(*exist_lease));
3760  return (reuseExpiredLease4(exist_lease, ctx, callout_status));
3761 
3762  } else {
3763  // If there is a lease and it is not expired, pass this lease back
3764  // to the caller in the context. The caller may need to know
3765  // which lease we're conflicting with.
3766  ctx.conflicting_lease_ = exist_lease;
3767  }
3768 
3769  } else {
3770  return (createLease4(ctx, candidate, callout_status));
3771  }
3772  return (Lease4Ptr());
3773 }
3774 
3775 Lease4Ptr
3776 AllocEngine::allocateUnreservedLease4(ClientContext4& ctx) {
3777  Lease4Ptr new_lease;
3779  Subnet4Ptr subnet = ctx.subnet_;
3780 
3781  // Need to check if the subnet belongs to a shared network. If so,
3782  // we might be able to find a better subnet for lease allocation,
3783  // for which it is more likely that there are some leases available.
3784  // If we stick to the selected subnet, we may end up walking over
3785  // the entire subnet (or more subnets) to discover that the address
3786  // pools have been exhausted. Using a subnet from which an address
3787  // was assigned most recently is an optimization which increases
3788  // the likelihood of starting from the subnet which address pools
3789  // are not exhausted.
3790  SharedNetwork4Ptr network;
3791  ctx.subnet_->getSharedNetwork(network);
3792  if (network) {
3793  // This would try to find a subnet with the same set of classes
3794  // as the current subnet, but with the more recent "usage timestamp".
3795  // This timestamp is only updated for the allocations made with an
3796  // allocator (unreserved lease allocations), not the static
3797  // allocations or requested addresses.
3798  ctx.subnet_ = subnet = network->getPreferredSubnet(ctx.subnet_);
3799  }
3800 
3801  Subnet4Ptr original_subnet = subnet;
3802 
3803  uint64_t total_attempts = 0;
3804  while (subnet) {
3805 
3806  ClientIdPtr client_id;
3807  if (subnet->getMatchClientId()) {
3808  client_id = ctx.clientid_;
3809  }
3810 
3811  uint64_t possible_attempts =
3812  subnet->getPoolCapacity(Lease::TYPE_V4,
3813  ctx.query_->getClasses());
3814  uint64_t max_attempts = (attempts_ > 0 ? attempts_ : possible_attempts);
3815  // Skip trying if there is no chance to get something
3816  if (possible_attempts == 0) {
3817  max_attempts = 0;
3818  }
3819 
3820  CalloutHandle::CalloutNextStep callout_status = CalloutHandle::NEXT_STEP_CONTINUE;
3821 
3822  for (uint64_t i = 0; i < max_attempts; ++i) {
3823  IOAddress candidate = allocator->pickAddress(subnet,
3824  ctx.query_->getClasses(),
3825  client_id,
3826  ctx.requested_address_);
3827  // If address is not reserved for another client, try to allocate it.
3828  if (!addressReserved(candidate, ctx)) {
3829 
3830  // The call below will return the non-NULL pointer if we
3831  // successfully allocate this lease. This means that the
3832  // address is not in use by another client.
3833  new_lease = allocateOrReuseLease4(candidate, ctx, callout_status);
3834  if (new_lease) {
3835  return (new_lease);
3836 
3837  } else if (ctx.callout_handle_ &&
3838  (callout_status != CalloutHandle::NEXT_STEP_CONTINUE)) {
3839  // Don't retry when the callout status is not continue.
3840  subnet.reset();
3841  break;
3842  }
3843  }
3844  ++total_attempts;
3845  }
3846 
3847  // This pointer may be set to NULL if hooks set SKIP status.
3848  if (subnet) {
3849  subnet = subnet->getNextSubnet(original_subnet, ctx.query_->getClasses());
3850 
3851  if (subnet) {
3852  ctx.subnet_ = subnet;
3853  }
3854  }
3855  }
3856 
3857  // Unable to allocate an address, return an empty lease.
3858  LOG_WARN(alloc_engine_logger, ALLOC_ENGINE_V4_ALLOC_FAIL)
3859  .arg(ctx.query_->getLabel())
3860  .arg(total_attempts);
3861 
3862  return (new_lease);
3863 }
3864 
3865 void
3866 AllocEngine::updateLease4Information(const Lease4Ptr& lease,
3867  AllocEngine::ClientContext4& ctx) const {
3868  lease->subnet_id_ = ctx.subnet_->getID();
3869  lease->hwaddr_ = ctx.hwaddr_;
3870  lease->client_id_ = ctx.subnet_->getMatchClientId() ? ctx.clientid_ : ClientIdPtr();
3871  lease->cltt_ = time(NULL);
3872  lease->t1_ = ctx.subnet_->getT1();
3873  lease->t2_ = ctx.subnet_->getT2();
3874  lease->valid_lft_ = ctx.subnet_->getValid();
3875  lease->fqdn_fwd_ = ctx.fwd_dns_update_;
3876  lease->fqdn_rev_ = ctx.rev_dns_update_;
3877  lease->hostname_ = ctx.hostname_;
3878 }
3879 
3880 bool
3881 AllocEngine::conditionalExtendLifetime(Lease& lease) const {
3882  lease.cltt_ = time(NULL);
3883  return (true);
3884 }
3885 
3886 }; // end of isc::dhcp namespace
3887 }; // end of isc namespace
#define LOG_WARN(LOGGER, MESSAGE)
Macro to conveniently test warn output and log it.
Definition: macros.h:26
static HostMgr & instance()
Returns a sole instance of the HostMgr.
Definition: host_mgr.cc:90
std::map< SubnetID, ConstHostPtr > hosts_
Holds a map of hosts belonging to the client within different subnets.
bool fake_allocation_
Indicates if this is a real or fake allocation.
boost::shared_ptr< DUID > DuidPtr
Definition: duid.h:20
virtual void updateLease4(const Lease4Ptr &lease4)=0
Updates IPv4 lease.
const int ALLOC_ENGINE_DBG_TRACE
Logging levels for the AllocEngine.
static std::string makeLabel(const HWAddrPtr &hwaddr, const ClientIdPtr &client_id, const uint32_t transid)
Returns text representation of the given packet identifiers.
Definition: pkt4.cc:360
Both out-of-pool and in-pool reservations are allowed.
Definition: network.h:112
A generic exception that is thrown when a function is not implemented.
static const uint32_t STATE_EXPIRED_RECLAIMED
Expired and reclaimed lease.
Definition: lease.h:67
Structure that holds a lease for IPv4 address.
Definition: lease.h:256
Abstract Lease Manager.
Definition: lease_mgr.h:222
#define LOG_INFO(LOGGER, MESSAGE)
Macro to conveniently test info output and log it.
Definition: macros.h:20
virtual bool deleteLease(const isc::asiolink::IOAddress &addr)=0
Deletes a lease.
static void findReservation(ClientContext6 &ctx)
Attempts to find appropriate host reservation.
void addHint(const asiolink::IOAddress &prefix, const uint8_t prefix_len=128)
Convenience method adding new hint.
boost::shared_ptr< HWAddr > HWAddrPtr
Shared pointer to a hardware address structure.
Definition: hwaddr.h:154
Only global reservations are allowed.
Definition: network.h:104
boost::shared_ptr< Pool6 > Pool6Ptr
a pointer an IPv6 Pool
Definition: pool.h:402
static std::string typeToText(Type type)
returns text representation of a lease type
Definition: lease.cc:39
void addAllocatedResource(const asiolink::IOAddress &prefix, const uint8_t prefix_len=128)
Convenience method adding allocated prefix or address.
static IPv6Resrv makeIPv6Resrv(const Lease6 &lease)
Creates an IPv6Resrv instance from a Lease6.
Definition: alloc_engine.h:784
static isc::asiolink::IOAddress increaseAddress(const isc::asiolink::IOAddress &address, bool prefix, const uint8_t prefix_len)
Returns the next address or prefix.
time_t cltt_
Client last transmission time.
Definition: lease.h:131
static ConstHostPtr findGlobalReservation(ClientContext6 &ctx)
Attempts to find the host reservation for the client.
static CfgMgr & instance()
returns a single instance of Configuration Manager
Definition: cfgmgr.cc:25
const int DHCPSRV_DBG_HOOKS
Definition: dhcpsrv_log.h:46
Only out-of-pool reservations is allowed.
Definition: network.h:100
std::vector< Lease4Ptr > Lease4Collection
A collection of IPv4 leases.
Definition: lease.h:455
virtual ConstHostCollection getAll(const Host::IdentifierType &identifier_type, const uint8_t *identifier_begin, const size_t identifier_len) const
Return all hosts connected to any subnet for which reservations have been made using a specified iden...
Definition: host_mgr.cc:99
boost::shared_ptr< Option > OptionPtr
Definition: option.h:37
boost::shared_ptr< Subnet4 > Subnet4Ptr
A pointer to a Subnet4 object.
Definition: subnet.h:464
#define LOG_ERROR(LOGGER, MESSAGE)
Macro to conveniently test error output and log it.
Definition: macros.h:32
the lease contains IPv6 prefix (for prefix delegation)
Definition: lease.h:41
const int ALLOC_ENGINE_DBG_TRACE_DETAIL
Record detailed traces.
virtual uint64_t deleteExpiredReclaimedLeases4(const uint32_t secs)=0
Deletes all expired and reclaimed DHCPv4 leases.
DuidPtr duid_
Client identifier.
Definition: alloc_engine.h:342
std::vector< PoolPtr > PoolCollection
a container for either IPv4 or IPv6 Pools
Definition: pool.h:408
long getTotalMilliseconds() const
Retrieves the total measured duration in milliseconds.
Definition: stopwatch.cc:60
Lease4Ptr allocateLease4(ClientContext4 &ctx)
Returns IPv4 lease.
virtual isc::asiolink::IOAddress pickAddress(const SubnetPtr &subnet, const ClientClasses &client_classes, const DuidPtr &duid, const isc::asiolink::IOAddress &hint)
returns an address based on hash calculated from client's DUID.
bool isAllocated(const asiolink::IOAddress &prefix, const uint8_t prefix_len=128) const
Checks if specified address or prefix was allocated.
boost::shared_ptr< Pool > PoolPtr
a pointer to either IPv4 or IPv6 Pool
Definition: pool.h:405
IPv6 reservation for a host.
Definition: host.h:106
AllocEngine(AllocType engine_type, uint64_t attempts, bool ipv6=true)
Constructor.
hooks::CalloutHandlePtr callout_handle_
Callout handle associated with the client's message.
RAII object enabling copying options retrieved from the packet.
Definition: pkt.h:40
virtual const char * what() const
Returns a C-style character string of the cause of the exception.
IdentifierList host_identifiers_
A list holding host identifiers extracted from a message received by the server.
An exception that is thrown when allocation module fails (e.g.
Definition: alloc_engine.h:36
virtual void getExpiredLeases6(Lease6Collection &expired_leases, const size_t max_leases) const =0
Returns a collection of expired DHCPv6 leases.
Statistics Manager class.
asiolink::IOAddress requested_address_
An address that the client desires.
void deleteExpiredReclaimedLeases4(const uint32_t secs)
Deletes reclaimed leases expired more than specified amount of time ago.
AllocType
specifies allocation type
Definition: alloc_engine.h:229
#define isc_throw(type, stream)
A shortcut macro to insert known values into exception arguments.
A generic exception that is thrown if a parameter given to a method is considered invalid in that con...
void stop()
Stops the stopwatch.
Definition: stopwatch.cc:35
void queueNCR(const NameChangeType &chg_type, const Lease4Ptr &lease)
Creates name change request from the DHCPv4 lease.
boost::shared_ptr< Pkt6 > Pkt6Ptr
A pointer to Pkt6 packet.
Definition: pkt6.h:28
Subnet6Ptr subnet_
Subnet selected for the client by the server.
Definition: alloc_engine.h:334
ResourceContainer allocated_resources_
Holds addresses and prefixes allocated for all IAs.
Definition: alloc_engine.h:378
std::pair< IPv6ResrvIterator, IPv6ResrvIterator > IPv6ResrvRange
Definition: host.h:188
const int ALLOC_ENGINE_DBG_TRACE_DETAIL_DATA
Records detailed results of various operations.
virtual isc::asiolink::IOAddress pickAddress(const SubnetPtr &subnet, const ClientClasses &client_classes, const DuidPtr &duid, const isc::asiolink::IOAddress &hint)
returns a random address from pool of specified subnet
Lease4Ptr conflicting_lease_
A pointer to the object representing a lease in conflict.
ElementPtr copy(ConstElementPtr from, int level)
Copy the data up to a nesting level.
Definition: data.cc:1114
boost::shared_ptr< Lease4 > Lease4Ptr
Pointer to a Lease4 structure.
Definition: lease.h:245
std::vector< ConstHostPtr > ConstHostCollection
Collection of the const Host objects.
Definition: host.h:731
Lease4Ptr old_lease_
A pointer to an old lease that the client had before update.
Utility class to measure code execution times.
Definition: stopwatch.h:35
std::map< SubnetID, ConstHostPtr > hosts_
Holds a map of hosts belonging to the client within different subnets.
Definition: alloc_engine.h:356
Random allocator that picks address randomly.
Definition: alloc_engine.h:203
Context information for the DHCPv6 leases allocation.
Definition: alloc_engine.h:316
ConstHostPtr globalHost() const
Returns global host reservation if there is one.
Subnet6Ptr host_subnet_
Subnet from which host reservations should be retrieved.
Definition: alloc_engine.h:339
A generic exception that is thrown when an unexpected error condition occurs.
Lease6Collection renewLeases6(ClientContext6 &ctx)
Renews existing DHCPv6 leases for a given IA.
Wrapper class around callout handle which automatically resets handle's state.
void reclaimExpiredLeases6(const size_t max_leases, const uint16_t timeout, const bool remove_lease, const uint16_t max_unwarned_cycles=0)
Reclaims expired IPv6 leases.
Subnet4Ptr subnet_
Subnet selected for the client by the server.
Pkt4Ptr query_
A pointer to the client's message.
CalloutNextStep
Specifies allowed next steps.
boost::shared_ptr< const Host > ConstHostPtr
Const pointer to the Host object.
Definition: host.h:728
void addHostIdentifier(const Host::IdentifierType &id_type, const std::vector< uint8_t > &identifier)
Convenience function adding host identifier into host_identifiers_ list.
Definition: alloc_engine.h:457
Structure that holds a lease for IPv6 address and/or prefix.
Definition: lease.h:471
Address/prefix allocator that iterates over all addresses.
Definition: alloc_engine.h:122
None - host reservation is disabled.
Definition: network.h:95
std::vector< Lease6Ptr > Lease6Collection
A collection of IPv6 leases.
Definition: lease.h:604
virtual Lease6Ptr getLease6(Lease::Type type, const isc::asiolink::IOAddress &addr) const =0
Returns existing IPv6 lease for a given IPv6 address.
boost::shared_ptr< ClientId > ClientIdPtr
Shared pointer to a Client ID.
Definition: duid.h:103
Type
Type of the reservation.
Definition: host.h:112
virtual void getExpiredLeases4(Lease4Collection &expired_leases, const size_t max_leases) const =0
Returns a collection of expired DHCPv4 leases.
the lease contains temporary IPv6 address
Definition: lease.h:40
boost::shared_ptr< SharedNetwork6 > SharedNetwork6Ptr
Pointer to SharedNetwork6 object.
void addHostIdentifier(const Host::IdentifierType &id_type, const std::vector< uint8_t > &identifier)
Convenience function adding host identifier into host_identifiers_ list.
the lease contains non-temporary IPv6 address
Definition: lease.h:39
boost::shared_ptr< SharedNetwork4 > SharedNetwork4Ptr
Pointer to SharedNetwork4 object.
HRMode
Specifies allowed host reservation mode.
Definition: network.h:91
void addValue(const std::string &name, const int64_t value)
Records incremental integer observation.
Definition: stats_mgr.cc:46
ConstHostPtr currentHost() const
Returns host for currently selected subnet.
This is a base class for exceptions thrown from the DNS library module.
Defines the logger used by the top-level component of kea-dhcp-ddns.
static std::string makeLabel(const DuidPtr duid, const uint32_t transid, const HWAddrPtr &hwaddr)
Returns text representation of the given packet identifiers.
Definition: pkt6.cc:585
Lease6Collection new_leases_
A collection of newly allocated leases.
Definition: alloc_engine.h:381
ClientIdPtr clientid_
Client identifier from the DHCP message.
uint32_t iaid_
iaid IAID field from IA_NA or IA_PD that is being processed
Definition: alloc_engine.h:390
Lease::Type type_
Lease type (IA or PD)
Definition: alloc_engine.h:393
boost::shared_ptr< Allocator > AllocatorPtr
defines a pointer to allocator
Definition: alloc_engine.h:114
Address/prefix allocator that gets an address based on a hash.
Definition: alloc_engine.h:177
Pkt6Ptr query_
A pointer to the client's message.
Definition: alloc_engine.h:324
virtual ConstHostPtr get4(const SubnetID &subnet_id, const Host::IdentifierType &identifier_type, const uint8_t *identifier_begin, const size_t identifier_len) const
Returns a host connected to the IPv4 subnet.
Definition: host_mgr.cc:175
Lease6Collection allocateLeases6(ClientContext6 &ctx)
Allocates IPv6 leases for a given IA container.
boost::shared_ptr< CalloutHandle > CalloutHandlePtr
A shared pointer to a CalloutHandle object.
Dhcp4Hooks Hooks
Definition: dhcp4_srv.cc:117
virtual ConstHostPtr get6(const SubnetID &subnet_id, const Host::IdentifierType &identifier_type, const uint8_t *identifier_begin, const size_t identifier_len) const
Returns a host connected to the IPv6 subnet.
Definition: host_mgr.cc:289
Lease4Ptr new_lease_
A pointer to a newly allocated lease.
HashedAllocator(Lease::Type type)
default constructor (does nothing)
a common structure for IPv4 and IPv6 leases
Definition: lease.h:35
Type
Type of lease or pool.
Definition: lease.h:38
bool fwd_dns_update_
Perform forward DNS update.
isc::log::Logger alloc_engine_logger("alloc-engine")
Logger for the AllocEngine.
base class for all address/prefix allocation algorithms
Definition: alloc_engine.h:63
A generic exception that is thrown if a function is called in a prohibited way.
#define LOG_DEBUG(LOGGER, LEVEL, MESSAGE)
Macro to conveniently test debug output and log it.
Definition: macros.h:14
void deleteExpiredReclaimedLeases6(const uint32_t secs)
Deletes reclaimed leases expired more than specified amount of time ago.
virtual bool addLease(const Lease4Ptr &lease)=0
Adds an IPv4 lease.
IAContext & currentIA()
Returns IA specific context for the currently processed IA.
Definition: alloc_engine.h:467
static const uint32_t STATE_DEFAULT
A lease in the default state.
Definition: lease.h:61
void reclaimExpiredLeases4(const size_t max_leases, const uint16_t timeout, const bool remove_lease, const uint16_t max_unwarned_cycles=0)
Reclaims expired IPv4 leases.
virtual Lease4Ptr getLease4(const isc::asiolink::IOAddress &addr) const =0
Returns an IPv4 lease for specified IPv4 address.
D2ClientMgr & getD2ClientMgr()
Fetches the DHCP-DDNS manager.
Definition: cfgmgr.cc:65
isc::log::Logger dhcpsrv_logger("dhcpsrv")
DHCP server library Logger.
Definition: dhcpsrv_log.h:56
static const uint32_t STATE_DECLINED
Declined lease.
Definition: lease.h:64
boost::shared_ptr< Subnet6 > Subnet6Ptr
A pointer to a Subnet6 object.
Definition: subnet.h:629
bool hasGlobalReservation(const IPv6Resrv &resv) const
Determines if a global reservation exists.
static isc::asiolink::IOAddress increasePrefix(const isc::asiolink::IOAddress &prefix, const uint8_t prefix_len)
Returns the next prefix.
Definition: alloc_engine.cc:92
std::pair< IPv6Resrv::Type, IPv6Resrv > IPv6ResrvTuple
Definition: host.h:187
HWAddrPtr hwaddr_
HW address from the DHCP message.
static LeaseMgr & instance()
Return current lease manager.
virtual isc::asiolink::IOAddress pickAddress(const SubnetPtr &subnet, const ClientClasses &client_classes, const DuidPtr &duid, const isc::asiolink::IOAddress &hint)
returns the next address from pools in a subnet
virtual Lease6Collection getLeases6(Lease::Type type, const DUID &duid, uint32_t iaid) const =0
Returns existing IPv6 leases for a given DUID+IA combination.
RandomAllocator(Lease::Type type)
default constructor (does nothing)
Context information for the DHCPv4 lease allocation.
boost::shared_ptr< Lease6 > Lease6Ptr
Pointer to a Lease6 structure.
Definition: lease.h:460
virtual uint64_t deleteExpiredReclaimedLeases6(const uint32_t secs)=0
Deletes all expired and reclaimed DHCPv6 leases.
std::string logFormatTotalDuration() const
Returns the total measured duration in the format directly usable in the log messages.
Definition: stopwatch.cc:80
This file provides the classes needed to embody, compose, and decompose DNS update requests that are ...
ConstHostPtr currentHost() const
Returns host from the most preferred subnet.
std::pair< Host::IdentifierType, std::vector< uint8_t > > IdentifierPair
A tuple holding host identifier type and value.
Definition: alloc_engine.h:289
Container for storing client class names.
Definition: classify.h:43
bool rev_dns_update_
Perform reverse DNS update.
boost::shared_ptr< Subnet > SubnetPtr
A generic pointer to either Subnet4 or Subnet6 object.
Definition: subnet.h:455
virtual void updateLease6(const Lease6Ptr &lease6)=0
Updates IPv6 lease.
AllocatorPtr getAllocator(Lease::Type type)
Returns allocator for a given pool type.
uint32_t SubnetID
Unique identifier for a subnet (both v4 and v6)
Definition: lease.h:24
IdentifierList host_identifiers_
A list holding host identifiers extracted from a message received by the server.
Definition: alloc_engine.h:349