Kea  2.3.4-git
alloc_engine.cc
Go to the documentation of this file.
1 // Copyright (C) 2012-2022 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/option_int.h>
13 #include <dhcp_ddns/ncr_msg.h>
14 #include <dhcpsrv/alloc_engine.h>
16 #include <dhcpsrv/cfgmgr.h>
17 #include <dhcpsrv/dhcpsrv_log.h>
18 #include <dhcpsrv/host_mgr.h>
19 #include <dhcpsrv/host.h>
22 #include <dhcpsrv/ncr_generator.h>
23 #include <dhcpsrv/network.h>
25 #include <dhcpsrv/shared_network.h>
26 #include <hooks/callout_handle.h>
27 #include <hooks/hooks_manager.h>
29 #include <stats/stats_mgr.h>
30 #include <util/encode/hex.h>
31 #include <util/stopwatch.h>
32 #include <hooks/server_hooks.h>
33 
34 #include <boost/foreach.hpp>
35 #include <boost/make_shared.hpp>
36 
37 #include <algorithm>
38 #include <limits>
39 #include <sstream>
40 #include <stdint.h>
41 #include <string.h>
42 #include <utility>
43 #include <vector>
44 
45 using namespace isc::asiolink;
46 using namespace isc::dhcp;
47 using namespace isc::dhcp_ddns;
48 using namespace isc::hooks;
49 using namespace isc::stats;
50 using namespace isc::util;
51 using namespace isc::data;
52 namespace ph = std::placeholders;
53 
54 namespace {
55 
57 struct AllocEngineHooks {
58  int hook_index_lease4_select_;
59  int hook_index_lease4_renew_;
60  int hook_index_lease4_expire_;
61  int hook_index_lease4_recover_;
62  int hook_index_lease6_select_;
63  int hook_index_lease6_renew_;
64  int hook_index_lease6_rebind_;
65  int hook_index_lease6_expire_;
66  int hook_index_lease6_recover_;
67 
69  AllocEngineHooks() {
70  hook_index_lease4_select_ = HooksManager::registerHook("lease4_select");
71  hook_index_lease4_renew_ = HooksManager::registerHook("lease4_renew");
72  hook_index_lease4_expire_ = HooksManager::registerHook("lease4_expire");
73  hook_index_lease4_recover_= HooksManager::registerHook("lease4_recover");
74  hook_index_lease6_select_ = HooksManager::registerHook("lease6_select");
75  hook_index_lease6_renew_ = HooksManager::registerHook("lease6_renew");
76  hook_index_lease6_rebind_ = HooksManager::registerHook("lease6_rebind");
77  hook_index_lease6_expire_ = HooksManager::registerHook("lease6_expire");
78  hook_index_lease6_recover_= HooksManager::registerHook("lease6_recover");
79  }
80 };
81 
82 // Declare a Hooks object. As this is outside any function or method, it
83 // will be instantiated (and the constructor run) when the module is loaded.
84 // As a result, the hook indexes will be defined before any method in this
85 // module is called.
86 AllocEngineHooks Hooks;
87 
88 } // namespace
89 
90 namespace isc {
91 namespace dhcp {
92 
93 AllocEngine::AllocEngine(uint64_t attempts)
94  : attempts_(attempts), incomplete_v4_reclamations_(0),
95  incomplete_v6_reclamations_(0) {
96 
97  // Register hook points
98  hook_index_lease4_select_ = Hooks.hook_index_lease4_select_;
99  hook_index_lease6_select_ = Hooks.hook_index_lease6_select_;
100 }
101 
102 } // end of namespace isc::dhcp
103 } // end of namespace isc
104 
105 namespace {
106 
116 getIPv6Resrv(const SubnetID& subnet_id, const IOAddress& address) {
117  ConstHostCollection reserved;
118  // The global parameter ip-reservations-unique controls whether it is allowed
119  // to specify multiple reservations for the same IP address or delegated prefix
120  // or IP reservations must be unique. Some host backends do not support the
121  // former, thus we can't always use getAll6 calls to get the reservations
122  // for the given IP. When we're in the default mode, when IP reservations
123  // are unique, we should call get6 (supported by all backends). If we're in
124  // the mode in which non-unique reservations are allowed the backends which
125  // don't support it are not used and we can safely call getAll6.
126  if (CfgMgr::instance().getCurrentCfg()->getCfgDbAccess()->getIPReservationsUnique()) {
127  auto host = HostMgr::instance().get6(subnet_id, address);
128  if (host) {
129  reserved.push_back(host);
130  }
131  } else {
132  auto hosts = HostMgr::instance().getAll6(subnet_id, address);
133  reserved.insert(reserved.end(), hosts.begin(), hosts.end());
134  }
135  return (reserved);
136 }
137 
150 bool
151 inAllowedPool(AllocEngine::ClientContext6& ctx, const Lease::Type& lease_type,
152  const IOAddress& address, bool check_subnet) {
153  // If the subnet belongs to a shared network we will be iterating
154  // over the subnets that belong to this shared network.
155  Subnet6Ptr current_subnet = ctx.subnet_;
156  auto const& classes = ctx.query_->getClasses();
157 
158  while (current_subnet) {
159  if (current_subnet->clientSupported(classes)) {
160  if (check_subnet) {
161  if (current_subnet->inPool(lease_type, address)) {
162  return (true);
163  }
164  } else {
165  if (current_subnet->inPool(lease_type, address, classes)) {
166  return (true);
167  }
168  }
169  }
170 
171  current_subnet = current_subnet->getNextSubnet(ctx.subnet_);
172  }
173 
174  return (false);
175 }
176 
177 }
178 
179 // ##########################################################################
180 // # DHCPv6 lease allocation code starts here.
181 // ##########################################################################
182 
183 namespace isc {
184 namespace dhcp {
185 
187  : query_(), fake_allocation_(false),
188  early_global_reservations_lookup_(false), subnet_(), host_subnet_(),
189  duid_(), hwaddr_(), host_identifiers_(), hosts_(),
190  fwd_dns_update_(false), rev_dns_update_(false), hostname_(),
191  callout_handle_(), ias_(), ddns_params_() {
192 }
193 
195  const DuidPtr& duid,
196  const bool fwd_dns,
197  const bool rev_dns,
198  const std::string& hostname,
199  const bool fake_allocation,
200  const Pkt6Ptr& query,
201  const CalloutHandlePtr& callout_handle)
202  : query_(query), fake_allocation_(fake_allocation),
204  duid_(duid), hwaddr_(), host_identifiers_(), hosts_(),
205  fwd_dns_update_(fwd_dns), rev_dns_update_(rev_dns), hostname_(hostname),
206  callout_handle_(callout_handle), allocated_resources_(), new_leases_(),
207  ias_(), ddns_params_() {
208 
209  // Initialize host identifiers.
210  if (duid) {
211  addHostIdentifier(Host::IDENT_DUID, duid->getDuid());
212  }
213 }
214 
216  : iaid_(0), type_(Lease::TYPE_NA), hints_(), old_leases_(),
217  changed_leases_(), new_resources_(), ia_rsp_() {
218 }
219 
220 void
223  const uint8_t prefix_len,
224  const uint32_t preferred,
225  const uint32_t valid) {
226  hints_.push_back(Resource(prefix, prefix_len, preferred, valid));
227 }
228 
229 void
232  if (!iaaddr) {
233  isc_throw(BadValue, "IAADDR option pointer is null.");
234  }
235  addHint(iaaddr->getAddress(), 128,
236  iaaddr->getPreferred(), iaaddr->getValid());
237 }
238 
239 void
242  if (!iaprefix) {
243  isc_throw(BadValue, "IAPREFIX option pointer is null.");
244  }
245  addHint(iaprefix->getAddress(), iaprefix->getLength(),
246  iaprefix->getPreferred(), iaprefix->getValid());
247 }
248 
249 void
252  const uint8_t prefix_len) {
253  static_cast<void>(new_resources_.insert(Resource(prefix, prefix_len)));
254 }
255 
256 bool
259  const uint8_t prefix_len) const {
260  return (static_cast<bool>(new_resources_.count(Resource(prefix,
261  prefix_len))));
262 }
263 
264 void
267  const uint8_t prefix_len) {
268  static_cast<void>(allocated_resources_.insert(Resource(prefix,
269  prefix_len)));
270 }
271 
272 bool
274 isAllocated(const asiolink::IOAddress& prefix, const uint8_t prefix_len) const {
275  return (static_cast<bool>
276  (allocated_resources_.count(Resource(prefix, prefix_len))));
277 }
278 
282  if (subnet && subnet->getReservationsInSubnet()) {
283  auto host = hosts_.find(subnet->getID());
284  if (host != hosts_.cend()) {
285  return (host->second);
286  }
287  }
288 
289  return (globalHost());
290 }
291 
295  if (subnet && subnet_->getReservationsGlobal()) {
296  auto host = hosts_.find(SUBNET_ID_GLOBAL);
297  if (host != hosts_.cend()) {
298  return (host->second);
299  }
300  }
301 
302  return (ConstHostPtr());
303 }
304 
305 bool
307  ConstHostPtr ghost = globalHost();
308  return (ghost && ghost->hasReservation(resv));
309 }
310 
313  // We already have it return it unless the context subnet has changed.
314  if (ddns_params_ && subnet_ && (subnet_->getID() == ddns_params_->getSubnetId())) {
315  return (ddns_params_);
316  }
317 
318  // Doesn't exist yet or is stale, (re)create it.
319  if (subnet_) {
320  ddns_params_ = CfgMgr::instance().getCurrentCfg()->getDdnsParams(subnet_);
321  return (ddns_params_);
322  }
323 
324  // Asked for it without a subnet? This case really shouldn't occur but
325  // for now let's return an instance with default values.
326  return (DdnsParamsPtr(new DdnsParams()));
327 }
328 
329 void
331  // If there is no subnet, there is nothing to do.
332  if (!ctx.subnet_) {
333  return;
334  }
335 
336  auto subnet = ctx.subnet_;
337 
338  // If already done just return.
340  !subnet->getReservationsInSubnet()) {
341  return;
342  }
343 
344  // @todo: This code can be trivially optimized.
346  subnet->getReservationsGlobal()) {
347  ConstHostPtr ghost = findGlobalReservation(ctx);
348  if (ghost) {
349  ctx.hosts_[SUBNET_ID_GLOBAL] = ghost;
350 
351  // If we had only to fetch global reservations it is done.
352  if (!subnet->getReservationsInSubnet()) {
353  return;
354  }
355  }
356  }
357 
358  std::map<SubnetID, ConstHostPtr> host_map;
359  SharedNetwork6Ptr network;
360  subnet->getSharedNetwork(network);
361 
362  // If the subnet belongs to a shared network it is usually going to be
363  // more efficient to make a query for all reservations for a particular
364  // client rather than a query for each subnet within this shared network.
365  // The only case when it is going to be less efficient is when there are
366  // more host identifier types in use than subnets within a shared network.
367  // As it breaks RADIUS use of host caching this can be disabled by the
368  // host manager.
369  const bool use_single_query = network &&
371  (network->getAllSubnets()->size() > ctx.host_identifiers_.size());
372 
373  if (use_single_query) {
374  for (const IdentifierPair& id_pair : ctx.host_identifiers_) {
375  ConstHostCollection hosts = HostMgr::instance().getAll(id_pair.first,
376  &id_pair.second[0],
377  id_pair.second.size());
378  // Store the hosts in the temporary map, because some hosts may
379  // belong to subnets outside of the shared network. We'll need
380  // to eliminate them.
381  for (auto host = hosts.begin(); host != hosts.end(); ++host) {
382  if ((*host)->getIPv6SubnetID() != SUBNET_ID_GLOBAL) {
383  host_map[(*host)->getIPv6SubnetID()] = *host;
384  }
385  }
386  }
387  }
388 
389  auto const& classes = ctx.query_->getClasses();
390 
391  // We can only search for the reservation if a subnet has been selected.
392  while (subnet) {
393 
394  // Only makes sense to get reservations if the client has access
395  // to the class and host reservations are enabled for this subnet.
396  if (subnet->clientSupported(classes) && subnet->getReservationsInSubnet()) {
397  // Iterate over configured identifiers in the order of preference
398  // and try to use each of them to search for the reservations.
399  if (use_single_query) {
400  if (host_map.count(subnet->getID()) > 0) {
401  ctx.hosts_[subnet->getID()] = host_map[subnet->getID()];
402  }
403  } else {
404  for (const IdentifierPair& id_pair : ctx.host_identifiers_) {
405  // Attempt to find a host using a specified identifier.
406  ConstHostPtr host = HostMgr::instance().get6(subnet->getID(),
407  id_pair.first,
408  &id_pair.second[0],
409  id_pair.second.size());
410  // If we found matching host for this subnet.
411  if (host) {
412  ctx.hosts_[subnet->getID()] = host;
413  break;
414  }
415  }
416  }
417  }
418 
419  // We need to get to the next subnet if this is a shared network. If it
420  // is not (a plain subnet), getNextSubnet will return NULL and we're
421  // done here.
422  subnet = subnet->getNextSubnet(ctx.subnet_, classes);
423  }
424 }
425 
428  ConstHostPtr host;
429  for (const IdentifierPair& id_pair : ctx.host_identifiers_) {
430  // Attempt to find a host using a specified identifier.
431  host = HostMgr::instance().get6(SUBNET_ID_GLOBAL, id_pair.first,
432  &id_pair.second[0], id_pair.second.size());
433 
434  // If we found matching global host we're done.
435  if (host) {
436  break;
437  }
438  }
439 
440  return (host);
441 }
442 
445 
446  try {
447  if (!ctx.subnet_) {
448  isc_throw(InvalidOperation, "Subnet is required for IPv6 lease allocation");
449  } else
450  if (!ctx.duid_) {
451  isc_throw(InvalidOperation, "DUID is mandatory for IPv6 lease allocation");
452  }
453 
454  // Check if there are existing leases for that shared network and
455  // DUID/IAID.
456  Subnet6Ptr subnet = ctx.subnet_;
457  Lease6Collection all_leases =
459  *ctx.duid_,
460  ctx.currentIA().iaid_);
461 
462  // Iterate over the leases and eliminate those that are outside of
463  // our shared network.
464  Lease6Collection leases;
465  while (subnet) {
466  for (auto l : all_leases) {
467  if ((l)->subnet_id_ == subnet->getID()) {
468  leases.push_back(l);
469  }
470  }
471 
472  subnet = subnet->getNextSubnet(ctx.subnet_);
473  }
474 
475  // Now do the checks:
476  // Case 1. if there are no leases, and there are reservations...
477  // 1.1. are the reserved addresses are used by someone else?
478  // yes: we have a problem
479  // no: assign them => done
480  // Case 2. if there are leases and there are no reservations...
481  // 2.1 are the leases reserved for someone else?
482  // yes: release them, assign something else
483  // no: renew them => done
484  // Case 3. if there are leases and there are reservations...
485  // 3.1 are the leases matching reservations?
486  // yes: renew them => done
487  // no: release existing leases, assign new ones based on reservations
488  // Case 4/catch-all. if there are no leases and no reservations...
489  // assign new leases
490 
491  // Case 1: There are no leases and there's a reservation for this host.
492  if (leases.empty() && !ctx.hosts_.empty()) {
493 
496  .arg(ctx.query_->getLabel());
497 
498  // Try to allocate leases that match reservations. Typically this will
499  // succeed, except cases where the reserved addresses are used by
500  // someone else.
501  allocateReservedLeases6(ctx, leases);
502 
503  leases = updateLeaseData(ctx, leases);
504 
505  // If not, we'll need to continue and will eventually fall into case 4:
506  // getting a regular lease. That could happen when we're processing
507  // request from client X, there's a reserved address A for X, but
508  // A is currently used by client Y. We can't immediately reassign A
509  // from X to Y, because Y keeps using it, so X would send Decline right
510  // away. Need to wait till Y renews, then we can release A, so it
511  // will become available for X.
512 
513  // Case 2: There are existing leases and there are no reservations.
514  //
515  // There is at least one lease for this client and there are no reservations.
516  // We will return these leases for the client, but we may need to update
517  // FQDN information.
518  } else if (!leases.empty() && ctx.hosts_.empty()) {
519 
522  .arg(ctx.query_->getLabel());
523 
524  // Check if the existing leases are reserved for someone else.
525  // If they're not, we're ok to keep using them.
526  removeNonmatchingReservedLeases6(ctx, leases);
527 
528  leases = updateLeaseData(ctx, leases);
529 
530  // If leases are empty at this stage, it means that we used to have
531  // leases for this client, but we checked and those leases are reserved
532  // for someone else, so we lost them. We will need to continue and
533  // will finally end up in case 4 (no leases, no reservations), so we'll
534  // assign something new.
535 
536  // Case 3: There are leases and there are reservations.
537  } else if (!leases.empty() && !ctx.hosts_.empty()) {
538 
541  .arg(ctx.query_->getLabel());
542 
543  // First, check if have leases matching reservations, and add new
544  // leases if we don't have them.
545  allocateReservedLeases6(ctx, leases);
546 
547  // leases now contain both existing and new leases that were created
548  // from reservations.
549 
550  // Second, let's remove leases that are reserved for someone else.
551  // This applies to any existing leases. This will not happen frequently,
552  // but it may happen with the following chain of events:
553  // 1. client A gets address X;
554  // 2. reservation for client B for address X is made by a administrator;
555  // 3. client A reboots
556  // 4. client A requests the address (X) he got previously
557  removeNonmatchingReservedLeases6(ctx, leases);
558 
559  // leases now contain existing and new leases, but we removed those
560  // leases that are reserved for someone else (non-matching reserved).
561 
562  // There's one more check to do. Let's remove leases that are not
563  // matching reservations, i.e. if client X has address A, but there's
564  // a reservation for address B, we should release A and reassign B.
565  // Caveat: do this only if we have at least one reserved address.
566  removeNonreservedLeases6(ctx, leases);
567 
568  // All checks are done. Let's hope we have some leases left.
569 
570  // Update any leases we have left.
571  leases = updateLeaseData(ctx, leases);
572 
573  // If we don't have any leases at this stage, it means that we hit
574  // one of the following cases:
575  // - we have a reservation, but it's not for this IAID/ia-type and
576  // we had to return the address we were using
577  // - we have a reservation for this iaid/ia-type, but the reserved
578  // address is currently used by someone else. We can't assign it
579  // yet.
580  // - we had an address, but we just discovered that it's reserved for
581  // someone else, so we released it.
582  }
583 
584  if (leases.empty()) {
585  // Case 4/catch-all: One of the following is true:
586  // - we don't have leases and there are no reservations
587  // - we used to have leases, but we lost them, because they are now
588  // reserved for someone else
589  // - we have a reservation, but it is not usable yet, because the address
590  // is still used by someone else
591  //
592  // In any case, we need to go through normal lease assignment process
593  // for now. This is also a catch-all or last resort approach, when we
594  // couldn't find any reservations (or couldn't use them).
595 
598  .arg(ctx.query_->getLabel());
599 
600  leases = allocateUnreservedLeases6(ctx);
601  }
602 
603  if (!leases.empty()) {
604  // If there are any leases allocated, let's store in them in the
605  // IA context so as they are available when we process subsequent
606  // IAs.
607  BOOST_FOREACH(Lease6Ptr lease, leases) {
608  ctx.addAllocatedResource(lease->addr_, lease->prefixlen_);
609  ctx.new_leases_.push_back(lease);
610  }
611  return (leases);
612  }
613 
614  } catch (const isc::Exception& e) {
615 
616  // Some other error, return an empty lease.
618  .arg(ctx.query_->getLabel())
619  .arg(e.what());
620  }
621 
622  return (Lease6Collection());
623 }
624 
626 AllocEngine::allocateUnreservedLeases6(ClientContext6& ctx) {
627 
628  Lease6Collection leases;
629 
631  if (!ctx.currentIA().hints_.empty()) {
633  hint = ctx.currentIA().hints_[0].getAddress();
634  }
635 
636  Subnet6Ptr original_subnet = ctx.subnet_;
637  Subnet6Ptr subnet = ctx.subnet_;
638 
639  Pool6Ptr pool;
640 
641  CalloutHandle::CalloutNextStep callout_status = CalloutHandle::NEXT_STEP_CONTINUE;
642 
643  auto const& classes = ctx.query_->getClasses();
644 
645  for (; subnet; subnet = subnet->getNextSubnet(original_subnet)) {
646  if (!subnet->clientSupported(classes)) {
647  continue;
648  }
649 
650  ctx.subnet_ = subnet;
651 
652  // check if the hint is in pool and is available
653  // This is equivalent of subnet->inPool(hint), but returns the pool
654  pool = boost::dynamic_pointer_cast<Pool6>
655  (subnet->getPool(ctx.currentIA().type_, classes, hint));
656 
657  // check if the pool is allowed
658  if (!pool || !pool->clientSupported(classes)) {
659  continue;
660  }
661 
662  bool in_subnet = subnet->getReservationsInSubnet();
663 
665  Lease6Ptr lease =
667  if (!lease) {
668 
669  // In-pool reservations: Check if this address is reserved for someone
670  // else. There is no need to check for whom it is reserved, because if
671  // it has been reserved for us we would have already allocated a lease.
672 
673  ConstHostCollection hosts;
674  // When out-of-pool flag is true the server may assume that all host
675  // reservations are for addresses that do not belong to the dynamic
676  // pool. Therefore, it can skip the reservation checks when dealing
677  // with in-pool addresses.
678  if (in_subnet &&
679  (!subnet->getReservationsOutOfPool() ||
680  !subnet->inPool(ctx.currentIA().type_, hint))) {
681  hosts = getIPv6Resrv(subnet->getID(), hint);
682  }
683 
684  if (hosts.empty()) {
685  // If the in-pool reservations are disabled, or there is no
686  // reservation for a given hint, we're good to go.
687 
688  // The hint is valid and not currently used, let's create a
689  // lease for it
690  lease = createLease6(ctx, hint, pool->getLength(), callout_status);
691 
692  // It can happen that the lease allocation failed (we could
693  // have lost the race condition. That means that the hint is
694  // no longer usable and we need to continue the regular
695  // allocation path.
696  if (lease) {
697 
699  Lease6Collection collection;
700  collection.push_back(lease);
701  return (collection);
702  }
703  } else {
706  .arg(ctx.query_->getLabel())
707  .arg(hint.toText());
708  }
709 
710  } else if (lease->expired()) {
711 
712  // If the lease is expired, we may likely reuse it, but...
713  ConstHostCollection hosts;
714  // When out-of-pool flag is true the server may assume that all host
715  // reservations are for addresses that do not belong to the dynamic
716  // pool. Therefore, it can skip the reservation checks when dealing
717  // with in-pool addresses.
718  if (in_subnet &&
719  (!subnet->getReservationsOutOfPool() ||
720  !subnet->inPool(ctx.currentIA().type_, hint))) {
721  hosts = getIPv6Resrv(subnet->getID(), hint);
722  }
723 
724  // Let's check if there is a reservation for this address.
725  if (hosts.empty()) {
726 
727  // Copy an existing, expired lease so as it can be returned
728  // to the caller.
729  Lease6Ptr old_lease(new Lease6(*lease));
730  ctx.currentIA().old_leases_.push_back(old_lease);
731 
733  lease = reuseExpiredLease(lease, ctx, pool->getLength(),
734  callout_status);
735 
737  leases.push_back(lease);
738  return (leases);
739 
740  } else {
743  .arg(ctx.query_->getLabel())
744  .arg(hint.toText());
745  }
746  }
747  }
748 
749  // We have the choice in the order checking the lease and
750  // the reservation. The default is to begin by the lease
751  // if the multi-threading is disabled.
752  bool check_reservation_first = MultiThreadingMgr::instance().getMode();
753  // If multi-threading is disabled, honor the configured order for host
754  // reservations lookup.
755  if (!check_reservation_first) {
756  check_reservation_first = CfgMgr::instance().getCurrentCfg()->getReservationsLookupFirst();
757  }
758 
759  uint64_t total_attempts = 0;
760 
761  // Need to check if the subnet belongs to a shared network. If so,
762  // we might be able to find a better subnet for lease allocation,
763  // for which it is more likely that there are some leases available.
764  // If we stick to the selected subnet, we may end up walking over
765  // the entire subnet (or more subnets) to discover that the pools
766  // have been exhausted. Using a subnet from which a lease was
767  // assigned most recently is an optimization which increases
768  // the likelihood of starting from the subnet which pools are not
769  // exhausted.
770  SharedNetwork6Ptr network;
771  original_subnet->getSharedNetwork(network);
772  if (network) {
773  // This would try to find a subnet with the same set of classes
774  // as the current subnet, but with the more recent "usage timestamp".
775  // This timestamp is only updated for the allocations made with an
776  // allocator (unreserved lease allocations), not the static
777  // allocations or requested addresses.
778  original_subnet = network->getPreferredSubnet(original_subnet, ctx.currentIA().type_);
779  }
780 
781  ctx.subnet_ = subnet = original_subnet;
782 
783  // The following counter tracks the number of subnets with matching client
784  // classes from which the allocation engine attempted to assign leases.
785  uint64_t subnets_with_unavail_leases = 0;
786  // The following counter tracks the number of subnets in which there were
787  // no matching pools for the client.
788  uint64_t subnets_with_unavail_pools = 0;
789 
790  for (; subnet; subnet = subnet->getNextSubnet(original_subnet)) {
791  if (!subnet->clientSupported(classes)) {
792  continue;
793  }
794 
795  // The hint was useless (it was not provided at all, was used by someone else,
796  // was out of pool or reserved for someone else). Search the pool until first
797  // of the following occurs:
798  // - we find a free address
799  // - we find an address for which the lease has expired
800  // - we exhaust number of tries
801  uint64_t possible_attempts =
802  subnet->getPoolCapacity(ctx.currentIA().type_, classes);
803 
804  // If the number of tries specified in the allocation engine constructor
805  // is set to 0 (unlimited) or the pools capacity is lower than that number,
806  // let's use the pools capacity as the maximum number of tries. Trying
807  // more than the actual pools capacity is a waste of time. If the specified
808  // number of tries is lower than the pools capacity, use that number.
809  uint64_t max_attempts = ((attempts_ == 0) || (possible_attempts < attempts_)) ? possible_attempts : attempts_;
810 
811  if (max_attempts > 0) {
812  // If max_attempts is greater than 0, there are some pools in this subnet
813  // from which we can potentially get a lease.
814  ++subnets_with_unavail_leases;
815  } else {
816  // If max_attempts is 0, it is an indication that there are no pools
817  // in the subnet from which we can get a lease.
818  ++subnets_with_unavail_pools;
819  continue;
820  }
821 
822  bool in_subnet = subnet->getReservationsInSubnet();
823  bool out_of_pool = subnet->getReservationsOutOfPool();
824 
825  // Set the default status code in case the lease6_select callouts
826  // do not exist and the callout handle has a status returned by
827  // any of the callouts already invoked for this packet.
828  if (ctx.callout_handle_) {
829  ctx.callout_handle_->setStatus(CalloutHandle::NEXT_STEP_CONTINUE);
830  }
831 
832  for (uint64_t i = 0; i < max_attempts; ++i) {
833 
834  ++total_attempts;
835 
836  auto allocator = subnet->getAllocator(ctx.currentIA().type_);
837  IOAddress candidate = allocator->pickAddress(classes,
838  ctx.duid_,
839  hint);
840  // The first step is to find out prefix length. It is 128 for
841  // non-PD leases.
842  uint8_t prefix_len = 128;
843  if (ctx.currentIA().type_ == Lease::TYPE_PD) {
844  pool = boost::dynamic_pointer_cast<Pool6>(
845  subnet->getPool(ctx.currentIA().type_,
846  classes,
847  candidate));
848  if (pool) {
849  prefix_len = pool->getLength();
850  }
851  }
852 
853  // First check for reservation when it is the choice.
854  if (check_reservation_first && in_subnet && !out_of_pool) {
855  auto hosts = getIPv6Resrv(subnet->getID(), candidate);
856  if (!hosts.empty()) {
857  // Don't allocate.
858  continue;
859  }
860  }
861 
862  // Check if the resource is busy i.e. can be being allocated
863  // by another thread to another client.
864  ResourceHandler resource_handler;
865  if (MultiThreadingMgr::instance().getMode() &&
866  !resource_handler.tryLock(ctx.currentIA().type_, candidate)) {
867  // Don't allocate.
868  continue;
869  }
870 
871  // Look for an existing lease for the candidate.
873  candidate);
874 
875  if (!existing) {
879  if (!check_reservation_first && in_subnet && !out_of_pool) {
880  auto hosts = getIPv6Resrv(subnet->getID(), candidate);
881  if (!hosts.empty()) {
882  // Don't allocate.
883  continue;
884  }
885  }
886 
887  // there's no existing lease for selected candidate, so it is
888  // free. Let's allocate it.
889 
890  ctx.subnet_ = subnet;
891  Lease6Ptr lease = createLease6(ctx, candidate, prefix_len, callout_status);
892  if (lease) {
893  // We are allocating a new lease (not renewing). So, the
894  // old lease should be NULL.
895  ctx.currentIA().old_leases_.clear();
896 
897  leases.push_back(lease);
898  return (leases);
899 
900  } else if (ctx.callout_handle_ &&
901  (callout_status != CalloutHandle::NEXT_STEP_CONTINUE)) {
902  // Don't retry when the callout status is not continue.
903  break;
904  }
905 
906  // Although the address was free just microseconds ago, it may have
907  // been taken just now. If the lease insertion fails, we continue
908  // allocation attempts.
909  } else if (existing->expired()) {
910  // Make sure it's not reserved.
911  if (!check_reservation_first && in_subnet && !out_of_pool) {
912  auto hosts = getIPv6Resrv(subnet->getID(), candidate);
913  if (!hosts.empty()) {
914  // Don't allocate.
915  continue;
916  }
917  }
918 
919  // Copy an existing, expired lease so as it can be returned
920  // to the caller.
921  Lease6Ptr old_lease(new Lease6(*existing));
922  ctx.currentIA().old_leases_.push_back(old_lease);
923 
924  ctx.subnet_ = subnet;
925  existing = reuseExpiredLease(existing, ctx, prefix_len,
926  callout_status);
927 
928  leases.push_back(existing);
929  return (leases);
930  }
931  }
932  }
933 
934  if (network) {
935  // The client is in the shared network. Let's log the high level message
936  // indicating which shared network the client belongs to.
938  .arg(ctx.query_->getLabel())
939  .arg(network->getName())
940  .arg(subnets_with_unavail_leases)
941  .arg(subnets_with_unavail_pools);
942  StatsMgr::instance().addValue("v6-allocation-fail-shared-network",
943  static_cast<int64_t>(1));
944  StatsMgr::instance().addValue(
945  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
946  "v6-allocation-fail-shared-network"),
947  static_cast<int64_t>(1));
948  } else {
949  // The client is not connected to a shared network. It is connected
950  // to a subnet. Let's log the ID of that subnet.
951  std::string shared_network = ctx.subnet_->getSharedNetworkName();
952  if (shared_network.empty()) {
953  shared_network = "(none)";
954  }
956  .arg(ctx.query_->getLabel())
957  .arg(ctx.subnet_->toText())
958  .arg(ctx.subnet_->getID())
959  .arg(shared_network);
960  StatsMgr::instance().addValue("v6-allocation-fail-subnet",
961  static_cast<int64_t>(1));
962  StatsMgr::instance().addValue(
963  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
964  "v6-allocation-fail-subnet"),
965  static_cast<int64_t>(1));
966  }
967  if (total_attempts == 0) {
968  // In this case, it seems that none of the pools in the subnets could
969  // be used for that client, both in case the client is connected to
970  // a shared network or to a single subnet. Apparently, the client was
971  // rejected to use the pools because of the client classes' mismatch.
973  .arg(ctx.query_->getLabel());
974  StatsMgr::instance().addValue("v6-allocation-fail-no-pools",
975  static_cast<int64_t>(1));
976  StatsMgr::instance().addValue(
977  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
978  "v6-allocation-fail-no-pools"),
979  static_cast<int64_t>(1));
980  } else {
981  // This is an old log message which provides a number of attempts
982  // made by the allocation engine to allocate a lease. The only case
983  // when we don't want to log this message is when the number of
984  // attempts is zero (condition above), because it would look silly.
986  .arg(ctx.query_->getLabel())
987  .arg(total_attempts);
988  StatsMgr::instance().addValue("v6-allocation-fail",
989  static_cast<int64_t>(1));
990  StatsMgr::instance().addValue(
991  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
992  "v6-allocation-fail"),
993  static_cast<int64_t>(1));
994  }
995 
996  if (!classes.empty()) {
998  .arg(ctx.query_->getLabel())
999  .arg(classes.toText());
1000  StatsMgr::instance().addValue("v6-allocation-fail-classes",
1001  static_cast<int64_t>(1));
1002  StatsMgr::instance().addValue(
1003  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
1004  "v6-allocation-fail-classes"),
1005  static_cast<int64_t>(1));
1006  }
1007 
1008  // We failed to allocate anything. Let's return empty collection.
1009  return (Lease6Collection());
1010 }
1011 
1012 void
1013 AllocEngine::allocateReservedLeases6(ClientContext6& ctx,
1014  Lease6Collection& existing_leases) {
1015 
1016  // If there are no reservations or the reservation is v4, there's nothing to do.
1017  if (ctx.hosts_.empty()) {
1020  .arg(ctx.query_->getLabel());
1021  return;
1022  }
1023 
1024  // Let's convert this from Lease::Type to IPv6Reserv::Type
1025  IPv6Resrv::Type type = ctx.currentIA().type_ == Lease::TYPE_NA ?
1027 
1028  // We want to avoid allocating new lease for an IA if there is already
1029  // a valid lease for which client has reservation. So, we first check if
1030  // we already have a lease for a reserved address or prefix.
1031  BOOST_FOREACH(const Lease6Ptr& lease, existing_leases) {
1032  if ((lease->valid_lft_ != 0)) {
1033  if ((ctx.hosts_.count(lease->subnet_id_) > 0) &&
1034  ctx.hosts_[lease->subnet_id_]->hasReservation(makeIPv6Resrv(*lease))) {
1035  // We found existing lease for a reserved address or prefix.
1036  // We'll simply extend the lifetime of the lease.
1039  .arg(ctx.query_->getLabel())
1040  .arg(lease->typeToText(lease->type_))
1041  .arg(lease->addr_.toText());
1042 
1043  // Besides IP reservations we're also going to return other reserved
1044  // parameters, such as hostname. We want to hand out the hostname value
1045  // from the same reservation entry as IP addresses. Thus, let's see if
1046  // there is any hostname reservation.
1047  if (!ctx.host_subnet_) {
1048  SharedNetwork6Ptr network;
1049  ctx.subnet_->getSharedNetwork(network);
1050  if (network) {
1051  // Remember the subnet that holds this preferred host
1052  // reservation. The server will use it to return appropriate
1053  // FQDN, classes etc.
1054  ctx.host_subnet_ = network->getSubnet(lease->subnet_id_);
1055  ConstHostPtr host = ctx.hosts_[lease->subnet_id_];
1056  // If there is a hostname reservation here we should stick
1057  // to this reservation. By updating the hostname in the
1058  // context we make sure that the database is updated with
1059  // this new value and the server doesn't need to do it and
1060  // its processing performance is not impacted by the hostname
1061  // updates.
1062  if (host && !host->getHostname().empty()) {
1063  // We have to determine whether the hostname is generated
1064  // in response to client's FQDN or not. If yes, we will
1065  // need to qualify the hostname. Otherwise, we just use
1066  // the hostname as it is specified for the reservation.
1067  OptionPtr fqdn = ctx.query_->getOption(D6O_CLIENT_FQDN);
1069  qualifyName(host->getHostname(), *ctx.getDdnsParams(),
1070  static_cast<bool>(fqdn));
1071  }
1072  }
1073  }
1074 
1075  // Got a lease for a reservation in this IA.
1076  return;
1077  }
1078  }
1079  }
1080 
1081  // There is no lease for a reservation in this IA. So, let's now iterate
1082  // over reservations specified and try to allocate one of them for the IA.
1083 
1084  auto const& classes = ctx.query_->getClasses();
1085  for (Subnet6Ptr subnet = ctx.subnet_; subnet;
1086  subnet = subnet->getNextSubnet(ctx.subnet_)) {
1087 
1088  SubnetID subnet_id = subnet->getID();
1089 
1090  // No hosts for this subnet or the subnet not supported.
1091  if (!subnet->clientSupported(classes) || ctx.hosts_.count(subnet_id) == 0) {
1092  continue;
1093  }
1094 
1095  ConstHostPtr host = ctx.hosts_[subnet_id];
1096 
1097  bool in_subnet = subnet->getReservationsInSubnet();
1098 
1099  // Get the IPv6 reservations of specified type.
1100  const IPv6ResrvRange& reservs = host->getIPv6Reservations(type);
1101  BOOST_FOREACH(IPv6ResrvTuple type_lease_tuple, reservs) {
1102  // We do have a reservation for address or prefix.
1103  const IOAddress& addr = type_lease_tuple.second.getPrefix();
1104  uint8_t prefix_len = type_lease_tuple.second.getPrefixLen();
1105 
1106  // We have allocated this address/prefix while processing one of the
1107  // previous IAs, so let's try another reservation.
1108  if (ctx.isAllocated(addr, prefix_len)) {
1109  continue;
1110  }
1111 
1112  // The out-of-pool flag indicates that no client should be assigned
1113  // reserved addresses from within the dynamic pool, and for that
1114  // reason look only for reservations that are outside the pools,
1115  // hence the inPool check.
1116  if (!in_subnet ||
1117  (subnet->getReservationsOutOfPool() &&
1118  subnet->inPool(ctx.currentIA().type_, addr))) {
1119  continue;
1120  }
1121 
1122  // If there's a lease for this address, let's not create it.
1123  // It doesn't matter whether it is for this client or for someone else.
1125  addr)) {
1126 
1127  // Let's remember the subnet from which the reserved address has been
1128  // allocated. We'll use this subnet for allocating other reserved
1129  // resources.
1130  ctx.subnet_ = subnet;
1131 
1132  if (!ctx.host_subnet_) {
1133  ctx.host_subnet_ = subnet;
1134  if (!host->getHostname().empty()) {
1135  // If there is a hostname reservation here we should stick
1136  // to this reservation. By updating the hostname in the
1137  // context we make sure that the database is updated with
1138  // this new value and the server doesn't need to do it and
1139  // its processing performance is not impacted by the hostname
1140  // updates.
1141 
1142  // We have to determine whether the hostname is generated
1143  // in response to client's FQDN or not. If yes, we will
1144  // need to qualify the hostname. Otherwise, we just use
1145  // the hostname as it is specified for the reservation.
1146  OptionPtr fqdn = ctx.query_->getOption(D6O_CLIENT_FQDN);
1148  qualifyName(host->getHostname(), *ctx.getDdnsParams(),
1149  static_cast<bool>(fqdn));
1150  }
1151  }
1152 
1153  // Ok, let's create a new lease...
1154  CalloutHandle::CalloutNextStep callout_status = CalloutHandle::NEXT_STEP_CONTINUE;
1155  Lease6Ptr lease = createLease6(ctx, addr, prefix_len, callout_status);
1156 
1157  // ... and add it to the existing leases list.
1158  existing_leases.push_back(lease);
1159 
1160  if (ctx.currentIA().type_ == Lease::TYPE_NA) {
1162  .arg(addr.toText())
1163  .arg(ctx.query_->getLabel());
1164  } else {
1166  .arg(addr.toText())
1167  .arg(static_cast<int>(prefix_len))
1168  .arg(ctx.query_->getLabel());
1169  }
1170 
1171  // We found a lease for this client and this IA. Let's return.
1172  // Returning after the first lease was assigned is useful if we
1173  // have multiple reservations for the same client. If the client
1174  // sends 2 IAs, the first time we call allocateReservedLeases6 will
1175  // use the first reservation and return. The second time, we'll
1176  // go over the first reservation, but will discover that there's
1177  // a lease corresponding to it and will skip it and then pick
1178  // the second reservation and turn it into the lease. This approach
1179  // would work for any number of reservations.
1180  return;
1181  }
1182  }
1183  }
1184 
1185  // Found no subnet reservations so now try the global reservation.
1186  allocateGlobalReservedLeases6(ctx, existing_leases);
1187 }
1188 
1189 void
1190 AllocEngine::allocateGlobalReservedLeases6(ClientContext6& ctx,
1191  Lease6Collection& existing_leases) {
1192  // Get the global host
1193  ConstHostPtr ghost = ctx.globalHost();
1194  if (!ghost) {
1195  return;
1196  }
1197 
1198  // We want to avoid allocating a new lease for an IA if there is already
1199  // a valid lease for which client has reservation. So, we first check if
1200  // we already have a lease for a reserved address or prefix.
1201  BOOST_FOREACH(const Lease6Ptr& lease, existing_leases) {
1202  if ((lease->valid_lft_ != 0) &&
1203  (ghost->hasReservation(makeIPv6Resrv(*lease)))) {
1204  // We found existing lease for a reserved address or prefix.
1205  // We'll simply extend the lifetime of the lease.
1208  .arg(ctx.query_->getLabel())
1209  .arg(lease->typeToText(lease->type_))
1210  .arg(lease->addr_.toText());
1211 
1212  // Besides IP reservations we're also going to return other reserved
1213  // parameters, such as hostname. We want to hand out the hostname value
1214  // from the same reservation entry as IP addresses. Thus, let's see if
1215  // there is any hostname reservation.
1216  if (!ghost->getHostname().empty()) {
1217  // We have to determine whether the hostname is generated
1218  // in response to client's FQDN or not. If yes, we will
1219  // need to qualify the hostname. Otherwise, we just use
1220  // the hostname as it is specified for the reservation.
1221  OptionPtr fqdn = ctx.query_->getOption(D6O_CLIENT_FQDN);
1223  qualifyName(ghost->getHostname(), *ctx.getDdnsParams(),
1224  static_cast<bool>(fqdn));
1225  }
1226 
1227  // Got a lease for a reservation in this IA.
1228  return;
1229  }
1230  }
1231 
1232  // There is no lease for a reservation in this IA. So, let's now iterate
1233  // over reservations specified and try to allocate one of them for the IA.
1234 
1235  // Let's convert this from Lease::Type to IPv6Reserv::Type
1236  IPv6Resrv::Type type = ctx.currentIA().type_ == Lease::TYPE_NA ?
1238 
1239  const IPv6ResrvRange& reservs = ghost->getIPv6Reservations(type);
1240  BOOST_FOREACH(IPv6ResrvTuple type_lease_tuple, reservs) {
1241  // We do have a reservation for address or prefix.
1242  const IOAddress& addr = type_lease_tuple.second.getPrefix();
1243  uint8_t prefix_len = type_lease_tuple.second.getPrefixLen();
1244 
1245  // We have allocated this address/prefix while processing one of the
1246  // previous IAs, so let's try another reservation.
1247  if (ctx.isAllocated(addr, prefix_len)) {
1248  continue;
1249  }
1250 
1251  // If there's a lease for this address, let's not create it.
1252  // It doesn't matter whether it is for this client or for someone else.
1253  if (!LeaseMgrFactory::instance().getLease6(ctx.currentIA().type_, addr)) {
1254 
1255  if (!ghost->getHostname().empty()) {
1256  // If there is a hostname reservation here we should stick
1257  // to this reservation. By updating the hostname in the
1258  // context we make sure that the database is updated with
1259  // this new value and the server doesn't need to do it and
1260  // its processing performance is not impacted by the hostname
1261  // updates.
1262 
1263  // We have to determine whether the hostname is generated
1264  // in response to client's FQDN or not. If yes, we will
1265  // need to qualify the hostname. Otherwise, we just use
1266  // the hostname as it is specified for the reservation.
1267  OptionPtr fqdn = ctx.query_->getOption(D6O_CLIENT_FQDN);
1269  qualifyName(ghost->getHostname(), *ctx.getDdnsParams(),
1270  static_cast<bool>(fqdn));
1271  }
1272 
1273  // Ok, let's create a new lease...
1274  CalloutHandle::CalloutNextStep callout_status = CalloutHandle::NEXT_STEP_CONTINUE;
1275  Lease6Ptr lease = createLease6(ctx, addr, prefix_len, callout_status);
1276 
1277  // ... and add it to the existing leases list.
1278  existing_leases.push_back(lease);
1279 
1280  if (ctx.currentIA().type_ == Lease::TYPE_NA) {
1282  .arg(addr.toText())
1283  .arg(ctx.query_->getLabel());
1284  } else {
1286  .arg(addr.toText())
1287  .arg(static_cast<int>(prefix_len))
1288  .arg(ctx.query_->getLabel());
1289  }
1290 
1291  // We found a lease for this client and this IA. Let's return.
1292  // Returning after the first lease was assigned is useful if we
1293  // have multiple reservations for the same client. If the client
1294  // sends 2 IAs, the first time we call allocateReservedLeases6 will
1295  // use the first reservation and return. The second time, we'll
1296  // go over the first reservation, but will discover that there's
1297  // a lease corresponding to it and will skip it and then pick
1298  // the second reservation and turn it into the lease. This approach
1299  // would work for any number of reservations.
1300  return;
1301  }
1302  }
1303 }
1304 
1305 void
1306 AllocEngine::removeNonmatchingReservedLeases6(ClientContext6& ctx,
1307  Lease6Collection& existing_leases) {
1308  // If there are no leases (so nothing to remove) just return.
1309  if (existing_leases.empty() || !ctx.subnet_) {
1310  return;
1311  }
1312  // If host reservation is disabled (so there are no reserved leases)
1313  // use the simplified version.
1314  if (!ctx.subnet_->getReservationsInSubnet() &&
1315  !ctx.subnet_->getReservationsGlobal()) {
1316  removeNonmatchingReservedNoHostLeases6(ctx, existing_leases);
1317  return;
1318  }
1319 
1320  // We need a copy, so we won't be iterating over a container and
1321  // removing from it at the same time. It's only a copy of pointers,
1322  // so the operation shouldn't be that expensive.
1323  Lease6Collection copy = existing_leases;
1324 
1325  BOOST_FOREACH(const Lease6Ptr& candidate, copy) {
1326  // If we have reservation we should check if the reservation is for
1327  // the candidate lease. If so, we simply accept the lease.
1328  IPv6Resrv resv = makeIPv6Resrv(*candidate);
1329  if ((ctx.hasGlobalReservation(resv)) ||
1330  ((ctx.hosts_.count(candidate->subnet_id_) > 0) &&
1331  (ctx.hosts_[candidate->subnet_id_]->hasReservation(resv)))) {
1332  // We have a subnet reservation
1333  continue;
1334  }
1335 
1336  // The candidate address doesn't appear to be reserved for us.
1337  // We have to make a bit more expensive operation here to retrieve
1338  // the reservation for the candidate lease and see if it is
1339  // reserved for someone else.
1340  auto hosts = getIPv6Resrv(ctx.subnet_->getID(), candidate->addr_);
1341  // If lease is not reserved to someone else, it means that it can
1342  // be allocated to us from a dynamic pool, but we must check if
1343  // this lease belongs to any pool. If it does, we can proceed to
1344  // checking the next lease.
1345  if (hosts.empty() && inAllowedPool(ctx, candidate->type_,
1346  candidate->addr_, false)) {
1347  continue;
1348  }
1349 
1350  if (!hosts.empty()) {
1351  // Ok, we have a problem. This host has a lease that is reserved
1352  // for someone else. We need to recover from this.
1353  if (hosts.size() == 1) {
1354  if (ctx.currentIA().type_ == Lease::TYPE_NA) {
1356  .arg(candidate->addr_.toText())
1357  .arg(ctx.duid_->toText())
1358  .arg(hosts.front()->getIdentifierAsText());
1359  } else {
1361  .arg(candidate->addr_.toText())
1362  .arg(static_cast<int>(candidate->prefixlen_))
1363  .arg(ctx.duid_->toText())
1364  .arg(hosts.front()->getIdentifierAsText());
1365  }
1366  } else {
1367  if (ctx.currentIA().type_ == Lease::TYPE_NA) {
1369  .arg(candidate->addr_.toText())
1370  .arg(ctx.duid_->toText())
1371  .arg(hosts.size());
1372  } else {
1374  .arg(candidate->addr_.toText())
1375  .arg(static_cast<int>(candidate->prefixlen_))
1376  .arg(ctx.duid_->toText())
1377  .arg(hosts.size());
1378  }
1379  }
1380  }
1381 
1382  // Remove this lease from LeaseMgr as it is reserved to someone
1383  // else or doesn't belong to a pool.
1384  if (!LeaseMgrFactory::instance().deleteLease(candidate)) {
1385  // Concurrent delete performed by other instance which should
1386  // properly handle dns and stats updates.
1387  continue;
1388  }
1389 
1390  // Update DNS if needed.
1391  queueNCR(CHG_REMOVE, candidate);
1392 
1393  // Need to decrease statistic for assigned addresses.
1394  StatsMgr::instance().addValue(
1395  StatsMgr::generateName("subnet", candidate->subnet_id_,
1396  ctx.currentIA().type_ == Lease::TYPE_NA ?
1397  "assigned-nas" : "assigned-pds"),
1398  static_cast<int64_t>(-1));
1399 
1400  // In principle, we could trigger a hook here, but we will do this
1401  // only if we get serious complaints from actual users. We want the
1402  // conflict resolution procedure to really work and user libraries
1403  // should not interfere with it.
1404 
1405  // Add this to the list of removed leases.
1406  ctx.currentIA().old_leases_.push_back(candidate);
1407 
1408  // Let's remove this candidate from existing leases
1409  removeLeases(existing_leases, candidate->addr_);
1410  }
1411 }
1412 
1413 void
1414 AllocEngine::removeNonmatchingReservedNoHostLeases6(ClientContext6& ctx,
1415  Lease6Collection& existing_leases) {
1416  // We need a copy, so we won't be iterating over a container and
1417  // removing from it at the same time. It's only a copy of pointers,
1418  // so the operation shouldn't be that expensive.
1419  Lease6Collection copy = existing_leases;
1420 
1421  BOOST_FOREACH(const Lease6Ptr& candidate, copy) {
1422  // Lease can be allocated to us from a dynamic pool, but we must
1423  // check if this lease belongs to any allowed pool. If it does,
1424  // we can proceed to checking the next lease.
1425  if (inAllowedPool(ctx, candidate->type_,
1426  candidate->addr_, false)) {
1427  continue;
1428  }
1429 
1430  // Remove this lease from LeaseMgr as it doesn't belong to a pool.
1431  if (!LeaseMgrFactory::instance().deleteLease(candidate)) {
1432  // Concurrent delete performed by other instance which should
1433  // properly handle dns and stats updates.
1434  continue;
1435  }
1436 
1437  // Update DNS if needed.
1438  queueNCR(CHG_REMOVE, candidate);
1439 
1440  // Need to decrease statistic for assigned addresses.
1441  StatsMgr::instance().addValue(
1442  StatsMgr::generateName("subnet", candidate->subnet_id_,
1443  ctx.currentIA().type_ == Lease::TYPE_NA ?
1444  "assigned-nas" : "assigned-pds"),
1445  static_cast<int64_t>(-1));
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 bool
1456 AllocEngine::removeLeases(Lease6Collection& container, const asiolink::IOAddress& addr) {
1457 
1458  bool removed = false;
1459  for (Lease6Collection::iterator lease = container.begin();
1460  lease != container.end(); ++lease) {
1461  if ((*lease)->addr_ == addr) {
1462  lease->reset();
1463  removed = true;
1464  }
1465  }
1466 
1467  // Remove all elements that have NULL value
1468  container.erase(std::remove(container.begin(), container.end(), Lease6Ptr()),
1469  container.end());
1470 
1471  return (removed);
1472 }
1473 
1474 void
1475 AllocEngine::removeNonreservedLeases6(ClientContext6& ctx,
1476  Lease6Collection& existing_leases) {
1477  // This method removes leases that are not reserved for this host.
1478  // It will keep at least one lease, though, as a fallback.
1479  int total = existing_leases.size();
1480  if (total <= 1) {
1481  return;
1482  }
1483 
1484  // This is officially not scary code anymore. iterates and marks specified
1485  // leases for deletion, by setting appropriate pointers to NULL.
1486  for (Lease6Collection::iterator lease = existing_leases.begin();
1487  lease != existing_leases.end(); ++lease) {
1488 
1489  // If there is reservation for this keep it.
1490  IPv6Resrv resv = makeIPv6Resrv(*(*lease));
1491  if (ctx.hasGlobalReservation(resv) ||
1492  ((ctx.hosts_.count((*lease)->subnet_id_) > 0) &&
1493  (ctx.hosts_[(*lease)->subnet_id_]->hasReservation(resv)))) {
1494  continue;
1495  }
1496 
1497  // @todo - If this is for a fake_allocation, we should probably
1498  // not be deleting the lease or removing DNS entries. We should
1499  // simply remove it from the list.
1500  // We have reservations, but not for this lease. Release it.
1501  // Remove this lease from LeaseMgr
1502  if (!LeaseMgrFactory::instance().deleteLease(*lease)) {
1503  // Concurrent delete performed by other instance which should
1504  // properly handle dns and stats updates.
1505  continue;
1506  }
1507 
1508  // Update DNS if required.
1509  queueNCR(CHG_REMOVE, *lease);
1510 
1511  // Need to decrease statistic for assigned addresses.
1512  StatsMgr::instance().addValue(
1513  StatsMgr::generateName("subnet", (*lease)->subnet_id_,
1514  ctx.currentIA().type_ == Lease::TYPE_NA ?
1515  "assigned-nas" : "assigned-pds"),
1516  static_cast<int64_t>(-1));
1517 
1519 
1520  // Add this to the list of removed leases.
1521  ctx.currentIA().old_leases_.push_back(*lease);
1522 
1523  // Set this pointer to NULL. The pointer is still valid. We're just
1524  // setting the Lease6Ptr to NULL value. We'll remove all NULL
1525  // pointers once the loop is finished.
1526  lease->reset();
1527 
1528  if (--total == 1) {
1529  // If there's only one lease left, break the loop.
1530  break;
1531  }
1532 
1533  }
1534 
1535  // Remove all elements that we previously marked for deletion (those that
1536  // have NULL value).
1537  existing_leases.erase(std::remove(existing_leases.begin(),
1538  existing_leases.end(), Lease6Ptr()), existing_leases.end());
1539 }
1540 
1541 Lease6Ptr
1542 AllocEngine::reuseExpiredLease(Lease6Ptr& expired, ClientContext6& ctx,
1543  uint8_t prefix_len,
1544  CalloutHandle::CalloutNextStep& callout_status) {
1545 
1546  if (!expired->expired()) {
1547  isc_throw(BadValue, "Attempt to recycle lease that is still valid");
1548  }
1549 
1550  if (expired->type_ != Lease::TYPE_PD) {
1551  prefix_len = 128; // non-PD lease types must be always /128
1552  }
1553 
1554  if (!ctx.fake_allocation_) {
1555  // The expired lease needs to be reclaimed before it can be reused.
1556  // This includes declined leases for which probation period has
1557  // elapsed.
1558  reclaimExpiredLease(expired, ctx.callout_handle_);
1559  }
1560 
1561  // address, lease type and prefixlen (0) stay the same
1562  expired->iaid_ = ctx.currentIA().iaid_;
1563  expired->duid_ = ctx.duid_;
1564  // Use subnet's preferred triplet to conditionally determine
1565  // preferred lifetime based on hint
1566  if (!ctx.currentIA().hints_.empty() &&
1567  ctx.currentIA().hints_[0].getPreferred()) {
1568  uint32_t preferred = ctx.currentIA().hints_[0].getPreferred();
1569  expired->preferred_lft_ = ctx.subnet_->getPreferred().get(preferred);
1570  } else {
1571  expired->preferred_lft_ = ctx.subnet_->getPreferred();
1572  }
1573  // Use subnet's valid triplet to conditionally determine
1574  // valid lifetime based on hint
1575  expired->reuseable_valid_lft_ = 0;
1576  if (!ctx.currentIA().hints_.empty() &&
1577  ctx.currentIA().hints_[0].getValid()) {
1578  uint32_t valid = ctx.currentIA().hints_[0].getValid();
1579  expired->valid_lft_ = ctx.subnet_->getValid().get(valid);
1580  } else {
1581  expired->valid_lft_ = ctx.subnet_->getValid();
1582  }
1583  expired->cltt_ = time(NULL);
1584  expired->subnet_id_ = ctx.subnet_->getID();
1585  expired->hostname_ = ctx.hostname_;
1586  expired->fqdn_fwd_ = ctx.fwd_dns_update_;
1587  expired->fqdn_rev_ = ctx.rev_dns_update_;
1588  expired->prefixlen_ = prefix_len;
1589  expired->state_ = Lease::STATE_DEFAULT;
1590 
1593  .arg(ctx.query_->getLabel())
1594  .arg(expired->toText());
1595 
1596  // Let's execute all callouts registered for lease6_select
1597  if (ctx.callout_handle_ &&
1598  HooksManager::calloutsPresent(hook_index_lease6_select_)) {
1599 
1600  // Use the RAII wrapper to make sure that the callout handle state is
1601  // reset when this object goes out of scope. All hook points must do
1602  // it to prevent possible circular dependency between the callout
1603  // handle and its arguments.
1604  ScopedCalloutHandleState callout_handle_state(ctx.callout_handle_);
1605 
1606  // Enable copying options from the packet within hook library.
1607  ScopedEnableOptionsCopy<Pkt6> query6_options_copy(ctx.query_);
1608 
1609  // Pass necessary arguments
1610 
1611  // Pass the original packet
1612  ctx.callout_handle_->setArgument("query6", ctx.query_);
1613 
1614  // Subnet from which we do the allocation
1615  ctx.callout_handle_->setArgument("subnet6", ctx.subnet_);
1616 
1617  // Is this solicit (fake = true) or request (fake = false)
1618  ctx.callout_handle_->setArgument("fake_allocation", ctx.fake_allocation_);
1619 
1620  // The lease that will be assigned to a client
1621  ctx.callout_handle_->setArgument("lease6", expired);
1622 
1623  // Call the callouts
1624  HooksManager::callCallouts(hook_index_lease6_select_, *ctx.callout_handle_);
1625 
1626  callout_status = ctx.callout_handle_->getStatus();
1627 
1628  // Callouts decided to skip the action. This means that the lease is not
1629  // assigned, so the client will get NoAddrAvail as a result. The lease
1630  // won't be inserted into the database.
1631  if (callout_status == CalloutHandle::NEXT_STEP_SKIP) {
1633  return (Lease6Ptr());
1634  }
1635 
1640 
1641  // Let's use whatever callout returned. Hopefully it is the same lease
1642  // we handed to it.
1643  ctx.callout_handle_->getArgument("lease6", expired);
1644  }
1645 
1646  if (!ctx.fake_allocation_) {
1647  // Add(update) the extended information on the lease.
1648  updateLease6ExtendedInfo(expired, ctx);
1649 
1650  // for REQUEST we do update the lease
1652 
1653  // If the lease is in the current subnet we need to account
1654  // for the re-assignment of The lease.
1655  if (ctx.subnet_->inPool(ctx.currentIA().type_, expired->addr_)) {
1656  StatsMgr::instance().addValue(
1657  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
1658  ctx.currentIA().type_ == Lease::TYPE_NA ?
1659  "assigned-nas" : "assigned-pds"),
1660  static_cast<int64_t>(1));
1661  StatsMgr::instance().addValue(
1662  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
1663  ctx.currentIA().type_ == Lease::TYPE_NA ?
1664  "cumulative-assigned-nas" :
1665  "cumulative-assigned-pds"),
1666  static_cast<int64_t>(1));
1667  StatsMgr::instance().addValue(ctx.currentIA().type_ == Lease::TYPE_NA ?
1668  "cumulative-assigned-nas" :
1669  "cumulative-assigned-pds",
1670  static_cast<int64_t>(1));
1671  }
1672  }
1673 
1674  // We do nothing for SOLICIT. We'll just update database when
1675  // the client gets back to us with REQUEST message.
1676 
1677  // it's not really expired at this stage anymore - let's return it as
1678  // an updated lease
1679  return (expired);
1680 }
1681 
1682 void
1683 AllocEngine::getLifetimes6(ClientContext6& ctx, uint32_t& preferred, uint32_t& valid) {
1684  // If the triplets are specified in one of our classes use it.
1685  // We use the first one we find for each lifetime.
1686  Triplet<uint32_t> candidate_preferred;
1687  Triplet<uint32_t> candidate_valid;
1688  const ClientClasses classes = ctx.query_->getClasses();
1689  if (!classes.empty()) {
1690  // Let's get class definitions
1691  const ClientClassDictionaryPtr& dict =
1692  CfgMgr::instance().getCurrentCfg()->getClientClassDictionary();
1693 
1694  // Iterate over the assigned class definitions.
1695  int have_both = 0;
1696  for (auto name = classes.cbegin();
1697  name != classes.cend() && have_both < 2; ++name) {
1698  ClientClassDefPtr cl = dict->findClass(*name);
1699  if (candidate_preferred.unspecified() &&
1700  (cl && (!cl->getPreferred().unspecified()))) {
1701  candidate_preferred = cl->getPreferred();
1702  ++have_both;
1703  }
1704 
1705  if (candidate_valid.unspecified() &&
1706  (cl && (!cl->getValid().unspecified()))) {
1707  candidate_valid = cl->getValid();
1708  ++have_both;
1709  }
1710  }
1711  }
1712 
1713  // If no classes specified preferred lifetime, get it from the subnet.
1714  if (!candidate_preferred) {
1715  candidate_preferred = ctx.subnet_->getPreferred();
1716  }
1717 
1718  // If no classes specified valid lifetime, get it from the subnet.
1719  if (!candidate_valid) {
1720  candidate_valid = ctx.subnet_->getValid();
1721  }
1722 
1723  // Set the outbound parameters to the values we have so far.
1724  preferred = candidate_preferred;
1725  valid = candidate_valid;
1726 
1727  // If client requested either value, use the requested value(s) bounded by
1728  // the candidate triplet(s).
1729  if (!ctx.currentIA().hints_.empty()) {
1730  if (ctx.currentIA().hints_[0].getPreferred()) {
1731  preferred = candidate_preferred.get(ctx.currentIA().hints_[0].getPreferred());
1732  }
1733 
1734  if (ctx.currentIA().hints_[0].getValid()) {
1735  valid = candidate_valid.get(ctx.currentIA().hints_[0].getValid());
1736  }
1737  }
1738 }
1739 
1740 Lease6Ptr AllocEngine::createLease6(ClientContext6& ctx,
1741  const IOAddress& addr,
1742  uint8_t prefix_len,
1743  CalloutHandle::CalloutNextStep& callout_status) {
1744 
1745  if (ctx.currentIA().type_ != Lease::TYPE_PD) {
1746  prefix_len = 128; // non-PD lease types must be always /128
1747  }
1748 
1749  uint32_t preferred = 0;
1750  uint32_t valid = 0;
1751  getLifetimes6(ctx, preferred, valid);
1752 
1753  Lease6Ptr lease(new Lease6(ctx.currentIA().type_, addr, ctx.duid_,
1754  ctx.currentIA().iaid_, preferred,
1755  valid, ctx.subnet_->getID(),
1756  ctx.hwaddr_, prefix_len));
1757 
1758  lease->fqdn_fwd_ = ctx.fwd_dns_update_;
1759  lease->fqdn_rev_ = ctx.rev_dns_update_;
1760  lease->hostname_ = ctx.hostname_;
1761 
1762  // Let's execute all callouts registered for lease6_select
1763  if (ctx.callout_handle_ &&
1764  HooksManager::calloutsPresent(hook_index_lease6_select_)) {
1765 
1766  // Use the RAII wrapper to make sure that the callout handle state is
1767  // reset when this object goes out of scope. All hook points must do
1768  // it to prevent possible circular dependency between the callout
1769  // handle and its arguments.
1770  ScopedCalloutHandleState callout_handle_state(ctx.callout_handle_);
1771 
1772  // Enable copying options from the packet within hook library.
1773  ScopedEnableOptionsCopy<Pkt6> query6_options_copy(ctx.query_);
1774 
1775  // Pass necessary arguments
1776 
1777  // Pass the original packet
1778  ctx.callout_handle_->setArgument("query6", ctx.query_);
1779 
1780  // Subnet from which we do the allocation
1781  ctx.callout_handle_->setArgument("subnet6", ctx.subnet_);
1782 
1783  // Is this solicit (fake = true) or request (fake = false)
1784  ctx.callout_handle_->setArgument("fake_allocation", ctx.fake_allocation_);
1785 
1786  // The lease that will be assigned to a client
1787  ctx.callout_handle_->setArgument("lease6", lease);
1788 
1789  // This is the first callout, so no need to clear any arguments
1790  HooksManager::callCallouts(hook_index_lease6_select_, *ctx.callout_handle_);
1791 
1792  callout_status = ctx.callout_handle_->getStatus();
1793 
1794  // Callouts decided to skip the action. This means that the lease is not
1795  // assigned, so the client will get NoAddrAvail as a result. The lease
1796  // won't be inserted into the database.
1797  if (callout_status == CalloutHandle::NEXT_STEP_SKIP) {
1799  return (Lease6Ptr());
1800  }
1801 
1802  // Let's use whatever callout returned. Hopefully it is the same lease
1803  // we handed to it.
1804  ctx.callout_handle_->getArgument("lease6", lease);
1805  }
1806 
1807  if (!ctx.fake_allocation_) {
1808  // Add(update) the extended information on the lease.
1809  updateLease6ExtendedInfo(lease, ctx);
1810 
1811  // That is a real (REQUEST) allocation
1812  bool status = LeaseMgrFactory::instance().addLease(lease);
1813 
1814  if (status) {
1815  // The lease insertion succeeded - if the lease is in the
1816  // current subnet lets bump up the statistic.
1817  if (ctx.subnet_->inPool(ctx.currentIA().type_, addr)) {
1818  StatsMgr::instance().addValue(
1819  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
1820  ctx.currentIA().type_ == Lease::TYPE_NA ?
1821  "assigned-nas" : "assigned-pds"),
1822  static_cast<int64_t>(1));
1823  StatsMgr::instance().addValue(
1824  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
1825  ctx.currentIA().type_ == Lease::TYPE_NA ?
1826  "cumulative-assigned-nas" :
1827  "cumulative-assigned-pds"),
1828  static_cast<int64_t>(1));
1829  StatsMgr::instance().addValue(ctx.currentIA().type_ == Lease::TYPE_NA ?
1830  "cumulative-assigned-nas" :
1831  "cumulative-assigned-pds",
1832  static_cast<int64_t>(1));
1833  }
1834 
1835  // Record it so it won't be updated twice.
1836  ctx.currentIA().addNewResource(addr, prefix_len);
1837 
1838  return (lease);
1839  } else {
1840  // One of many failures with LeaseMgr (e.g. lost connection to the
1841  // database, database failed etc.). One notable case for that
1842  // is that we are working in multi-process mode and we lost a race
1843  // (some other process got that address first)
1844  return (Lease6Ptr());
1845  }
1846  } else {
1847  // That is only fake (SOLICIT without rapid-commit) allocation
1848 
1849  // It is for advertise only. We should not insert the lease and callers
1850  // have already verified the lease does not exist in the database.
1851  return (lease);
1852  }
1853 }
1854 
1857  try {
1858  if (!ctx.subnet_) {
1859  isc_throw(InvalidOperation, "Subnet is required for allocation");
1860  }
1861 
1862  if (!ctx.duid_) {
1863  isc_throw(InvalidOperation, "DUID is mandatory for allocation");
1864  }
1865 
1866  // Check if there are any leases for this client.
1867  Subnet6Ptr subnet = ctx.subnet_;
1868  Lease6Collection leases;
1869  while (subnet) {
1870  Lease6Collection leases_subnet =
1872  *ctx.duid_,
1873  ctx.currentIA().iaid_,
1874  subnet->getID());
1875  leases.insert(leases.end(), leases_subnet.begin(), leases_subnet.end());
1876 
1877  subnet = subnet->getNextSubnet(ctx.subnet_);
1878  }
1879 
1880  if (!leases.empty()) {
1883  .arg(ctx.query_->getLabel());
1884 
1885  // Check if the existing leases are reserved for someone else.
1886  // If they're not, we're ok to keep using them.
1887  removeNonmatchingReservedLeases6(ctx, leases);
1888  }
1889 
1890  if (!ctx.hosts_.empty()) {
1891 
1894  .arg(ctx.query_->getLabel());
1895 
1896  // If we have host reservation, allocate those leases.
1897  allocateReservedLeases6(ctx, leases);
1898 
1899  // There's one more check to do. Let's remove leases that are not
1900  // matching reservations, i.e. if client X has address A, but there's
1901  // a reservation for address B, we should release A and reassign B.
1902  // Caveat: do this only if we have at least one reserved address.
1903  removeNonreservedLeases6(ctx, leases);
1904  }
1905 
1906  // If we happen to removed all leases, get something new for this guy.
1907  // Depending on the configuration, we may enable or disable granting
1908  // new leases during renewals. This is controlled with the
1909  // allow_new_leases_in_renewals_ field.
1910  if (leases.empty()) {
1911 
1914  .arg(ctx.query_->getLabel());
1915 
1916  leases = allocateUnreservedLeases6(ctx);
1917  }
1918 
1919  // Extend all existing leases that passed all checks.
1920  for (Lease6Collection::iterator l = leases.begin(); l != leases.end(); ++l) {
1921  if (ctx.currentIA().isNewResource((*l)->addr_,
1922  (*l)->prefixlen_)) {
1923  // This lease was just created so is already extended.
1924  continue;
1925  }
1928  .arg(ctx.query_->getLabel())
1929  .arg((*l)->typeToText((*l)->type_))
1930  .arg((*l)->addr_);
1931  extendLease6(ctx, *l);
1932  }
1933 
1934  if (!leases.empty()) {
1935  // If there are any leases allocated, let's store in them in the
1936  // IA context so as they are available when we process subsequent
1937  // IAs.
1938  BOOST_FOREACH(Lease6Ptr lease, leases) {
1939  ctx.addAllocatedResource(lease->addr_, lease->prefixlen_);
1940  ctx.new_leases_.push_back(lease);
1941  }
1942  }
1943 
1944  return (leases);
1945 
1946  } catch (const isc::Exception& e) {
1947 
1948  // Some other error, return an empty lease.
1950  .arg(ctx.query_->getLabel())
1951  .arg(e.what());
1952  }
1953 
1954  return (Lease6Collection());
1955 }
1956 
1957 void
1958 AllocEngine::extendLease6(ClientContext6& ctx, Lease6Ptr lease) {
1959 
1960  if (!lease || !ctx.subnet_) {
1961  return;
1962  }
1963 
1964  // It is likely that the lease for which we're extending the lifetime doesn't
1965  // belong to the current but a sibling subnet.
1966  if (ctx.subnet_->getID() != lease->subnet_id_) {
1967  SharedNetwork6Ptr network;
1968  ctx.subnet_->getSharedNetwork(network);
1969  if (network) {
1970  Subnet6Ptr subnet = network->getSubnet(SubnetID(lease->subnet_id_));
1971  // Found the actual subnet this lease belongs to. Stick to this
1972  // subnet.
1973  if (subnet) {
1974  ctx.subnet_ = subnet;
1975  }
1976  }
1977  }
1978 
1979  // If the lease is not global and it is either out of range (NAs only) or it
1980  // is not permitted by subnet client classification, delete it.
1981  if (!(ctx.hasGlobalReservation(makeIPv6Resrv(*lease))) &&
1982  (((lease->type_ != Lease::TYPE_PD) && !ctx.subnet_->inRange(lease->addr_)) ||
1983  !ctx.subnet_->clientSupported(ctx.query_->getClasses()))) {
1984  // Oh dear, the lease is no longer valid. We need to get rid of it.
1985 
1986  // Remove this lease from LeaseMgr
1987  if (!LeaseMgrFactory::instance().deleteLease(lease)) {
1988  // Concurrent delete performed by other instance which should
1989  // properly handle dns and stats updates.
1990  return;
1991  }
1992 
1993  // Updated DNS if required.
1994  queueNCR(CHG_REMOVE, lease);
1995 
1996  // Need to decrease statistic for assigned addresses.
1997  StatsMgr::instance().addValue(
1998  StatsMgr::generateName("subnet", ctx.subnet_->getID(), "assigned-nas"),
1999  static_cast<int64_t>(-1));
2000 
2001  // Add it to the removed leases list.
2002  ctx.currentIA().old_leases_.push_back(lease);
2003 
2004  return;
2005  }
2006 
2009  .arg(ctx.query_->getLabel())
2010  .arg(lease->toText());
2011 
2012  // Keep the old data in case the callout tells us to skip update.
2013  Lease6Ptr old_data(new Lease6(*lease));
2014 
2015  bool changed = false;
2016  uint32_t current_preferred_lft = lease->preferred_lft_;
2017  if (!ctx.currentIA().hints_.empty() &&
2018  ctx.currentIA().hints_[0].getPreferred()) {
2019  uint32_t preferred = ctx.currentIA().hints_[0].getPreferred();
2020  lease->preferred_lft_ = ctx.subnet_->getPreferred().get(preferred);
2021  } else {
2022  lease->preferred_lft_ = ctx.subnet_->getPreferred();
2023  }
2024  if (lease->preferred_lft_ < current_preferred_lft) {
2025  changed = true;
2026  }
2027  lease->reuseable_valid_lft_ = 0;
2028  if (!ctx.currentIA().hints_.empty() &&
2029  ctx.currentIA().hints_[0].getValid()) {
2030  uint32_t valid = ctx.currentIA().hints_[0].getValid();
2031  lease->valid_lft_ = ctx.subnet_->getValid().get(valid);
2032  } else {
2033  lease->valid_lft_ = ctx.subnet_->getValid();
2034  }
2035  if (lease->valid_lft_ < lease->current_valid_lft_) {
2036  changed = true;
2037  }
2038 
2039  lease->cltt_ = time(NULL);
2040  if ((lease->fqdn_fwd_ != ctx.fwd_dns_update_) ||
2041  (lease->fqdn_rev_ != ctx.rev_dns_update_) ||
2042  (lease->hostname_ != ctx.hostname_)) {
2043  changed = true;
2044  lease->hostname_ = ctx.hostname_;
2045  lease->fqdn_fwd_ = ctx.fwd_dns_update_;
2046  lease->fqdn_rev_ = ctx.rev_dns_update_;
2047  }
2048  if ((!ctx.hwaddr_ && lease->hwaddr_) ||
2049  (ctx.hwaddr_ &&
2050  (!lease->hwaddr_ || (*ctx.hwaddr_ != *lease->hwaddr_)))) {
2051  changed = true;
2052  lease->hwaddr_ = ctx.hwaddr_;
2053  }
2054  if (lease->state_ != Lease::STATE_DEFAULT) {
2055  changed = true;
2056  lease->state_ = Lease::STATE_DEFAULT;
2057  }
2060  .arg(ctx.query_->getLabel())
2061  .arg(lease->toText());
2062 
2063  bool skip = false;
2064  // Get the callouts specific for the processed message and execute them.
2065  int hook_point = ctx.query_->getType() == DHCPV6_RENEW ?
2066  Hooks.hook_index_lease6_renew_ : Hooks.hook_index_lease6_rebind_;
2067  if (HooksManager::calloutsPresent(hook_point)) {
2068  CalloutHandlePtr callout_handle = ctx.callout_handle_;
2069 
2070  // Use the RAII wrapper to make sure that the callout handle state is
2071  // reset when this object goes out of scope. All hook points must do
2072  // it to prevent possible circular dependency between the callout
2073  // handle and its arguments.
2074  ScopedCalloutHandleState callout_handle_state(callout_handle);
2075 
2076  // Enable copying options from the packet within hook library.
2077  ScopedEnableOptionsCopy<Pkt6> query6_options_copy(ctx.query_);
2078 
2079  // Pass the original packet
2080  callout_handle->setArgument("query6", ctx.query_);
2081 
2082  // Pass the lease to be updated
2083  callout_handle->setArgument("lease6", lease);
2084 
2085  // Pass the IA option to be sent in response
2086  if (lease->type_ == Lease::TYPE_NA) {
2087  callout_handle->setArgument("ia_na", ctx.currentIA().ia_rsp_);
2088  } else {
2089  callout_handle->setArgument("ia_pd", ctx.currentIA().ia_rsp_);
2090  }
2091 
2092  // Call all installed callouts
2093  HooksManager::callCallouts(hook_point, *callout_handle);
2094 
2095  // Callouts decided to skip the next processing step. The next
2096  // processing step would actually renew the lease, so skip at this
2097  // stage means "keep the old lease as it is".
2098  if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
2099  skip = true;
2102  .arg(ctx.query_->getName());
2103  }
2104 
2106  }
2107 
2108  if (!skip) {
2109  bool update_stats = false;
2110 
2111  // If the lease we're renewing has expired, we need to reclaim this
2112  // lease before we can renew it.
2113  if (old_data->expired()) {
2114  reclaimExpiredLease(old_data, ctx.callout_handle_);
2115 
2116  // If the lease is in the current subnet we need to account
2117  // for the re-assignment of the lease.
2118  if (ctx.subnet_->inPool(ctx.currentIA().type_, old_data->addr_)) {
2119  update_stats = true;
2120  }
2121  changed = true;
2122  }
2123 
2124  // @todo should we call storeLease6ExtendedInfo() here ?
2125  updateLease6ExtendedInfo(lease, ctx);
2126  if (lease->extended_info_action_ == Lease::ACTION_UPDATE) {
2127  changed = true;
2128  }
2129 
2130  // Try to reuse the lease.
2131  if (!changed) {
2132  setLeaseReusable(lease, current_preferred_lft, ctx);
2133  }
2134 
2135 
2136  // Now that the lease has been reclaimed, we can go ahead and update it
2137  // in the lease database.
2138  if (lease->reuseable_valid_lft_ == 0) {
2140  }
2141 
2142  if (update_stats) {
2143  StatsMgr::instance().addValue(
2144  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
2145  ctx.currentIA().type_ == Lease::TYPE_NA ?
2146  "assigned-nas" : "assigned-pds"),
2147  static_cast<int64_t>(1));
2148  StatsMgr::instance().addValue(
2149  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
2150  ctx.currentIA().type_ == Lease::TYPE_NA ?
2151  "cumulative-assigned-nas" :
2152  "cumulative-assigned-pds"),
2153  static_cast<int64_t>(1));
2154  StatsMgr::instance().addValue(ctx.currentIA().type_ == Lease::TYPE_NA ?
2155  "cumulative-assigned-nas" :
2156  "cumulative-assigned-pds",
2157  static_cast<int64_t>(1));
2158  }
2159 
2160  } else {
2161  // Copy back the original date to the lease. For MySQL it doesn't make
2162  // much sense, but for memfile, the Lease6Ptr points to the actual lease
2163  // in memfile, so the actual update is performed when we manipulate
2164  // fields of returned Lease6Ptr, the actual updateLease6() is no-op.
2165  *lease = *old_data;
2166  }
2167 
2168  // Add the old lease to the changed lease list. This allows the server
2169  // to make decisions regarding DNS updates.
2170  ctx.currentIA().changed_leases_.push_back(old_data);
2171 }
2172 
2174 AllocEngine::updateLeaseData(ClientContext6& ctx, const Lease6Collection& leases) {
2175  Lease6Collection updated_leases;
2176  for (Lease6Collection::const_iterator lease_it = leases.begin();
2177  lease_it != leases.end(); ++lease_it) {
2178  Lease6Ptr lease(new Lease6(**lease_it));
2179  if (ctx.currentIA().isNewResource(lease->addr_, lease->prefixlen_)) {
2180  // This lease was just created so is already up to date.
2181  updated_leases.push_back(lease);
2182  continue;
2183  }
2184 
2185  lease->reuseable_valid_lft_ = 0;
2186  lease->fqdn_fwd_ = ctx.fwd_dns_update_;
2187  lease->fqdn_rev_ = ctx.rev_dns_update_;
2188  lease->hostname_ = ctx.hostname_;
2189  if (!ctx.fake_allocation_) {
2190  bool update_stats = false;
2191 
2192  if (lease->state_ == Lease::STATE_EXPIRED_RECLAIMED) {
2193  // Transition lease state to default (aka assigned)
2194  lease->state_ = Lease::STATE_DEFAULT;
2195 
2196  // If the lease is in the current subnet we need to account
2197  // for the re-assignment of the lease.
2198  if (inAllowedPool(ctx, ctx.currentIA().type_,
2199  lease->addr_, true)) {
2200  update_stats = true;
2201  }
2202  }
2203 
2204  bool fqdn_changed = ((lease->type_ != Lease::TYPE_PD) &&
2205  !(lease->hasIdenticalFqdn(**lease_it)));
2206 
2207  lease->cltt_ = time(NULL);
2208  if (!fqdn_changed) {
2209  uint32_t current_preferred_lft = lease->preferred_lft_;
2210  setLeaseReusable(lease, current_preferred_lft, ctx);
2211  }
2212  if (lease->reuseable_valid_lft_ == 0) {
2213  ctx.currentIA().changed_leases_.push_back(*lease_it);
2215  }
2216 
2217  if (update_stats) {
2218  StatsMgr::instance().addValue(
2219  StatsMgr::generateName("subnet", lease->subnet_id_,
2220  ctx.currentIA().type_ == Lease::TYPE_NA ?
2221  "assigned-nas" : "assigned-pds"),
2222  static_cast<int64_t>(1));
2223  StatsMgr::instance().addValue(
2224  StatsMgr::generateName("subnet", lease->subnet_id_,
2225  ctx.currentIA().type_ == Lease::TYPE_NA ?
2226  "cumulative-assigned-nas" :
2227  "cumulative-assigned-pds"),
2228  static_cast<int64_t>(1));
2229  StatsMgr::instance().addValue(ctx.currentIA().type_ == Lease::TYPE_NA ?
2230  "cumulative-assigned-nas" :
2231  "cumulative-assigned-pds",
2232  static_cast<int64_t>(1));
2233  }
2234  }
2235 
2236  updated_leases.push_back(lease);
2237  }
2238 
2239  return (updated_leases);
2240 }
2241 
2242 void
2243 AllocEngine::reclaimExpiredLeases6(const size_t max_leases, const uint16_t timeout,
2244  const bool remove_lease,
2245  const uint16_t max_unwarned_cycles) {
2246 
2249  .arg(max_leases)
2250  .arg(timeout);
2251 
2252  // Create stopwatch and automatically start it to measure the time
2253  // taken by the routine.
2254  util::Stopwatch stopwatch;
2255 
2256  LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
2257 
2258  // This value indicates if we have been able to deal with all expired
2259  // leases in this pass.
2260  bool incomplete_reclamation = false;
2261  Lease6Collection leases;
2262  // The value of 0 has a special meaning - reclaim all.
2263  if (max_leases > 0) {
2264  // If the value is non-zero, the caller has limited the number of
2265  // leases to reclaim. We obtain one lease more to see if there will
2266  // be still leases left after this pass.
2267  lease_mgr.getExpiredLeases6(leases, max_leases + 1);
2268  // There are more leases expired leases than we will process in this
2269  // pass, so we should mark it as an incomplete reclamation. We also
2270  // remove this extra lease (which we don't want to process anyway)
2271  // from the collection.
2272  if (leases.size() > max_leases) {
2273  leases.pop_back();
2274  incomplete_reclamation = true;
2275  }
2276 
2277  } else {
2278  // If there is no limitation on the number of leases to reclaim,
2279  // we will try to process all. Hence, we don't mark it as incomplete
2280  // reclamation just yet.
2281  lease_mgr.getExpiredLeases6(leases, max_leases);
2282  }
2283 
2284  // Do not initialize the callout handle until we know if there are any
2285  // lease6_expire callouts installed.
2286  CalloutHandlePtr callout_handle;
2287  if (!leases.empty() &&
2288  HooksManager::calloutsPresent(Hooks.hook_index_lease6_expire_)) {
2289  callout_handle = HooksManager::createCalloutHandle();
2290  }
2291 
2292  size_t leases_processed = 0;
2293  BOOST_FOREACH(Lease6Ptr lease, leases) {
2294 
2295  try {
2296  // Reclaim the lease.
2297  if (MultiThreadingMgr::instance().getMode()) {
2298  // The reclamation is exclusive of packet processing.
2299  WriteLockGuard exclusive(rw_mutex_);
2300 
2301  reclaimExpiredLease(lease, remove_lease, callout_handle);
2302  ++leases_processed;
2303  } else {
2304  reclaimExpiredLease(lease, remove_lease, callout_handle);
2305  ++leases_processed;
2306  }
2307 
2308  } catch (const std::exception& ex) {
2310  .arg(lease->addr_.toText())
2311  .arg(ex.what());
2312  }
2313 
2314  // Check if we have hit the timeout for running reclamation routine and
2315  // return if we have. We're checking it here, because we always want to
2316  // allow reclaiming at least one lease.
2317  if ((timeout > 0) && (stopwatch.getTotalMilliseconds() >= timeout)) {
2318  // Timeout. This will likely mean that we haven't been able to process
2319  // all leases we wanted to process. The reclamation pass will be
2320  // probably marked as incomplete.
2321  if (!incomplete_reclamation) {
2322  if (leases_processed < leases.size()) {
2323  incomplete_reclamation = true;
2324  }
2325  }
2326 
2329  .arg(timeout);
2330  break;
2331  }
2332  }
2333 
2334  // Stop measuring the time.
2335  stopwatch.stop();
2336 
2337  // Mark completion of the lease reclamation routine and present some stats.
2340  .arg(leases_processed)
2341  .arg(stopwatch.logFormatTotalDuration());
2342 
2343  // Check if this was an incomplete reclamation and increase the number of
2344  // consecutive incomplete reclamations.
2345  if (incomplete_reclamation) {
2346  ++incomplete_v6_reclamations_;
2347  // If the number of incomplete reclamations is beyond the threshold, we
2348  // need to issue a warning.
2349  if ((max_unwarned_cycles > 0) &&
2350  (incomplete_v6_reclamations_ > max_unwarned_cycles)) {
2352  .arg(max_unwarned_cycles);
2353  // We issued a warning, so let's now reset the counter.
2354  incomplete_v6_reclamations_ = 0;
2355  }
2356 
2357  } else {
2358  // This was a complete reclamation, so let's reset the counter.
2359  incomplete_v6_reclamations_ = 0;
2360 
2363  }
2364 }
2365 
2366 void
2370  .arg(secs);
2371 
2372  uint64_t deleted_leases = 0;
2373  try {
2374  // Try to delete leases from the lease database.
2375  LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
2376  deleted_leases = lease_mgr.deleteExpiredReclaimedLeases6(secs);
2377 
2378  } catch (const std::exception& ex) {
2380  .arg(ex.what());
2381  }
2382 
2385  .arg(deleted_leases);
2386 }
2387 
2388 void
2389 AllocEngine::reclaimExpiredLeases4(const size_t max_leases, const uint16_t timeout,
2390  const bool remove_lease,
2391  const uint16_t max_unwarned_cycles) {
2392 
2395  .arg(max_leases)
2396  .arg(timeout);
2397 
2398  // Create stopwatch and automatically start it to measure the time
2399  // taken by the routine.
2400  util::Stopwatch stopwatch;
2401 
2402  LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
2403 
2404  // This value indicates if we have been able to deal with all expired
2405  // leases in this pass.
2406  bool incomplete_reclamation = false;
2407  Lease4Collection leases;
2408  // The value of 0 has a special meaning - reclaim all.
2409  if (max_leases > 0) {
2410  // If the value is non-zero, the caller has limited the number of
2411  // leases to reclaim. We obtain one lease more to see if there will
2412  // be still leases left after this pass.
2413  lease_mgr.getExpiredLeases4(leases, max_leases + 1);
2414  // There are more leases expired leases than we will process in this
2415  // pass, so we should mark it as an incomplete reclamation. We also
2416  // remove this extra lease (which we don't want to process anyway)
2417  // from the collection.
2418  if (leases.size() > max_leases) {
2419  leases.pop_back();
2420  incomplete_reclamation = true;
2421  }
2422 
2423  } else {
2424  // If there is no limitation on the number of leases to reclaim,
2425  // we will try to process all. Hence, we don't mark it as incomplete
2426  // reclamation just yet.
2427  lease_mgr.getExpiredLeases4(leases, max_leases);
2428  }
2429 
2430  // Do not initialize the callout handle until we know if there are any
2431  // lease4_expire callouts installed.
2432  CalloutHandlePtr callout_handle;
2433  if (!leases.empty() &&
2434  HooksManager::calloutsPresent(Hooks.hook_index_lease4_expire_)) {
2435  callout_handle = HooksManager::createCalloutHandle();
2436  }
2437 
2438  size_t leases_processed = 0;
2439  BOOST_FOREACH(Lease4Ptr lease, leases) {
2440 
2441  try {
2442  // Reclaim the lease.
2443  if (MultiThreadingMgr::instance().getMode()) {
2444  // The reclamation is exclusive of packet processing.
2445  WriteLockGuard exclusive(rw_mutex_);
2446 
2447  reclaimExpiredLease(lease, remove_lease, callout_handle);
2448  ++leases_processed;
2449  } else {
2450  reclaimExpiredLease(lease, remove_lease, callout_handle);
2451  ++leases_processed;
2452  }
2453 
2454  } catch (const std::exception& ex) {
2456  .arg(lease->addr_.toText())
2457  .arg(ex.what());
2458  }
2459 
2460  // Check if we have hit the timeout for running reclamation routine and
2461  // return if we have. We're checking it here, because we always want to
2462  // allow reclaiming at least one lease.
2463  if ((timeout > 0) && (stopwatch.getTotalMilliseconds() >= timeout)) {
2464  // Timeout. This will likely mean that we haven't been able to process
2465  // all leases we wanted to process. The reclamation pass will be
2466  // probably marked as incomplete.
2467  if (!incomplete_reclamation) {
2468  if (leases_processed < leases.size()) {
2469  incomplete_reclamation = true;
2470  }
2471  }
2472 
2475  .arg(timeout);
2476  break;
2477  }
2478  }
2479 
2480  // Stop measuring the time.
2481  stopwatch.stop();
2482 
2483  // Mark completion of the lease reclamation routine and present some stats.
2486  .arg(leases_processed)
2487  .arg(stopwatch.logFormatTotalDuration());
2488 
2489  // Check if this was an incomplete reclamation and increase the number of
2490  // consecutive incomplete reclamations.
2491  if (incomplete_reclamation) {
2492  ++incomplete_v4_reclamations_;
2493  // If the number of incomplete reclamations is beyond the threshold, we
2494  // need to issue a warning.
2495  if ((max_unwarned_cycles > 0) &&
2496  (incomplete_v4_reclamations_ > max_unwarned_cycles)) {
2498  .arg(max_unwarned_cycles);
2499  // We issued a warning, so let's now reset the counter.
2500  incomplete_v4_reclamations_ = 0;
2501  }
2502 
2503  } else {
2504  // This was a complete reclamation, so let's reset the counter.
2505  incomplete_v4_reclamations_ = 0;
2506 
2509  }
2510 }
2511 
2512 template<typename LeasePtrType>
2513 void
2514 AllocEngine::reclaimExpiredLease(const LeasePtrType& lease, const bool remove_lease,
2515  const CalloutHandlePtr& callout_handle) {
2516  reclaimExpiredLease(lease, remove_lease ? DB_RECLAIM_REMOVE : DB_RECLAIM_UPDATE,
2517  callout_handle);
2518 }
2519 
2520 template<typename LeasePtrType>
2521 void
2522 AllocEngine::reclaimExpiredLease(const LeasePtrType& lease,
2523  const CalloutHandlePtr& callout_handle) {
2524  // This variant of the method is used by the code which allocates or
2525  // renews leases. It may be the case that the lease has already been
2526  // reclaimed, so there is nothing to do.
2527  if (!lease->stateExpiredReclaimed()) {
2528  reclaimExpiredLease(lease, DB_RECLAIM_LEAVE_UNCHANGED, callout_handle);
2529  }
2530 }
2531 
2532 void
2533 AllocEngine::reclaimExpiredLease(const Lease6Ptr& lease,
2534  const DbReclaimMode& reclaim_mode,
2535  const CalloutHandlePtr& callout_handle) {
2536 
2539  .arg(Pkt6::makeLabel(lease->duid_, lease->hwaddr_))
2540  .arg(lease->addr_.toText())
2541  .arg(static_cast<int>(lease->prefixlen_));
2542 
2543  // The skip flag indicates if the callouts have taken responsibility
2544  // for reclaiming the lease. The callout will set this to true if
2545  // it reclaims the lease itself. In this case the reclamation routine
2546  // will not update DNS nor update the database.
2547  bool skipped = false;
2548  if (callout_handle) {
2549 
2550  // Use the RAII wrapper to make sure that the callout handle state is
2551  // reset when this object goes out of scope. All hook points must do
2552  // it to prevent possible circular dependency between the callout
2553  // handle and its arguments.
2554  ScopedCalloutHandleState callout_handle_state(callout_handle);
2555 
2556  callout_handle->deleteAllArguments();
2557  callout_handle->setArgument("lease6", lease);
2558  callout_handle->setArgument("remove_lease", reclaim_mode == DB_RECLAIM_REMOVE);
2559 
2560  HooksManager::callCallouts(Hooks.hook_index_lease6_expire_,
2561  *callout_handle);
2562 
2563  skipped = callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP;
2564  }
2565 
2568 
2569  if (!skipped) {
2570 
2571  // Generate removal name change request for D2, if required.
2572  // This will return immediately if the DNS wasn't updated
2573  // when the lease was created.
2574  queueNCR(CHG_REMOVE, lease);
2575 
2576  // Let's check if the lease that just expired is in DECLINED state.
2577  // If it is, we need to perform a couple extra steps.
2578  bool remove_lease = (reclaim_mode == DB_RECLAIM_REMOVE);
2579  if (lease->state_ == Lease::STATE_DECLINED) {
2580  // Do extra steps required for declined lease reclamation:
2581  // - call the recover hook
2582  // - bump decline-related stats
2583  // - log separate message
2584  // There's no point in keeping a declined lease after its
2585  // reclamation. A declined lease doesn't have any client
2586  // identifying information anymore. So we'll flag it for
2587  // removal unless the hook has set the skip flag.
2588  remove_lease = reclaimDeclined(lease);
2589  }
2590 
2591  if (reclaim_mode != DB_RECLAIM_LEAVE_UNCHANGED) {
2592  // Reclaim the lease - depending on the configuration, set the
2593  // expired-reclaimed state or simply remove it.
2594  LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
2595  reclaimLeaseInDatabase<Lease6Ptr>(lease, remove_lease,
2596  std::bind(&LeaseMgr::updateLease6,
2597  &lease_mgr, ph::_1));
2598  }
2599  }
2600 
2601  // Update statistics.
2602 
2603  // Decrease number of assigned leases.
2604  if (lease->type_ == Lease::TYPE_NA) {
2605  // IA_NA
2606  StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
2607  lease->subnet_id_,
2608  "assigned-nas"),
2609  int64_t(-1));
2610 
2611  } else if (lease->type_ == Lease::TYPE_PD) {
2612  // IA_PD
2613  StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
2614  lease->subnet_id_,
2615  "assigned-pds"),
2616  int64_t(-1));
2617 
2618  }
2619 
2620  // Increase total number of reclaimed leases.
2621  StatsMgr::instance().addValue("reclaimed-leases", int64_t(1));
2622 
2623  // Increase number of reclaimed leases for a subnet.
2624  StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
2625  lease->subnet_id_,
2626  "reclaimed-leases"),
2627  int64_t(1));
2628 }
2629 
2630 void
2631 AllocEngine::reclaimExpiredLease(const Lease4Ptr& lease,
2632  const DbReclaimMode& reclaim_mode,
2633  const CalloutHandlePtr& callout_handle) {
2634 
2637  .arg(Pkt4::makeLabel(lease->hwaddr_, lease->client_id_))
2638  .arg(lease->addr_.toText());
2639 
2640  // The skip flag indicates if the callouts have taken responsibility
2641  // for reclaiming the lease. The callout will set this to true if
2642  // it reclaims the lease itself. In this case the reclamation routine
2643  // will not update DNS nor update the database.
2644  bool skipped = false;
2645  if (callout_handle) {
2646 
2647  // Use the RAII wrapper to make sure that the callout handle state is
2648  // reset when this object goes out of scope. All hook points must do
2649  // it to prevent possible circular dependency between the callout
2650  // handle and its arguments.
2651  ScopedCalloutHandleState callout_handle_state(callout_handle);
2652 
2653  callout_handle->setArgument("lease4", lease);
2654  callout_handle->setArgument("remove_lease", reclaim_mode == DB_RECLAIM_REMOVE);
2655 
2656  HooksManager::callCallouts(Hooks.hook_index_lease4_expire_,
2657  *callout_handle);
2658 
2659  skipped = callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP;
2660  }
2661 
2664 
2665  if (!skipped) {
2666 
2667  // Generate removal name change request for D2, if required.
2668  // This will return immediately if the DNS wasn't updated
2669  // when the lease was created.
2670  queueNCR(CHG_REMOVE, lease);
2671  // Clear DNS fields so we avoid redundant removes.
2672  lease->hostname_.clear();
2673  lease->fqdn_fwd_ = false;
2674  lease->fqdn_rev_ = false;
2675 
2676  // Let's check if the lease that just expired is in DECLINED state.
2677  // If it is, we need to perform a couple extra steps.
2678  bool remove_lease = (reclaim_mode == DB_RECLAIM_REMOVE);
2679  if (lease->state_ == Lease::STATE_DECLINED) {
2680  // Do extra steps required for declined lease reclamation:
2681  // - call the recover hook
2682  // - bump decline-related stats
2683  // - log separate message
2684  // There's no point in keeping a declined lease after its
2685  // reclamation. A declined lease doesn't have any client
2686  // identifying information anymore. So we'll flag it for
2687  // removal unless the hook has set the skip flag.
2688  remove_lease = reclaimDeclined(lease);
2689  }
2690 
2691  if (reclaim_mode != DB_RECLAIM_LEAVE_UNCHANGED) {
2692  // Reclaim the lease - depending on the configuration, set the
2693  // expired-reclaimed state or simply remove it.
2694  LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
2695  reclaimLeaseInDatabase<Lease4Ptr>(lease, remove_lease,
2696  std::bind(&LeaseMgr::updateLease4,
2697  &lease_mgr, ph::_1));
2698  }
2699  }
2700 
2701  // Update statistics.
2702 
2703  // Decrease number of assigned addresses.
2704  StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
2705  lease->subnet_id_,
2706  "assigned-addresses"),
2707  int64_t(-1));
2708 
2709  // Increase total number of reclaimed leases.
2710  StatsMgr::instance().addValue("reclaimed-leases", int64_t(1));
2711 
2712  // Increase number of reclaimed leases for a subnet.
2713  StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
2714  lease->subnet_id_,
2715  "reclaimed-leases"),
2716  int64_t(1));
2717 }
2718 
2719 void
2723  .arg(secs);
2724 
2725  uint64_t deleted_leases = 0;
2726  try {
2727  // Try to delete leases from the lease database.
2728  LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
2729  deleted_leases = lease_mgr.deleteExpiredReclaimedLeases4(secs);
2730 
2731  } catch (const std::exception& ex) {
2733  .arg(ex.what());
2734  }
2735 
2738  .arg(deleted_leases);
2739 }
2740 
2741 bool
2742 AllocEngine::reclaimDeclined(const Lease4Ptr& lease) {
2743  if (!lease || (lease->state_ != Lease::STATE_DECLINED) ) {
2744  return (true);
2745  }
2746 
2747  if (HooksManager::calloutsPresent(Hooks.hook_index_lease4_recover_)) {
2748  CalloutHandlePtr callout_handle = HooksManager::createCalloutHandle();
2749 
2750  // Use the RAII wrapper to make sure that the callout handle state is
2751  // reset when this object goes out of scope. All hook points must do
2752  // it to prevent possible circular dependency between the callout
2753  // handle and its arguments.
2754  ScopedCalloutHandleState callout_handle_state(callout_handle);
2755 
2756  // Pass necessary arguments
2757  callout_handle->setArgument("lease4", lease);
2758 
2759  // Call the callouts
2760  HooksManager::callCallouts(Hooks.hook_index_lease4_recover_, *callout_handle);
2761 
2762  // Callouts decided to skip the action. This means that the lease is not
2763  // assigned, so the client will get NoAddrAvail as a result. The lease
2764  // won't be inserted into the database.
2765  if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
2767  .arg(lease->addr_.toText());
2768  return (false);
2769  }
2770  }
2771 
2773  .arg(lease->addr_.toText())
2774  .arg(lease->valid_lft_);
2775 
2776  StatsMgr& stats_mgr = StatsMgr::instance();
2777 
2778  // Decrease subnet specific counter for currently declined addresses
2779  stats_mgr.addValue(StatsMgr::generateName("subnet", lease->subnet_id_,
2780  "declined-addresses"), static_cast<int64_t>(-1));
2781 
2782  // Decrease global counter for declined addresses
2783  stats_mgr.addValue("declined-addresses", static_cast<int64_t>(-1));
2784 
2785  stats_mgr.addValue("reclaimed-declined-addresses", static_cast<int64_t>(1));
2786 
2787  stats_mgr.addValue(StatsMgr::generateName("subnet", lease->subnet_id_,
2788  "reclaimed-declined-addresses"), static_cast<int64_t>(1));
2789 
2790  // Note that we do not touch assigned-addresses counters. Those are
2791  // modified in whatever code calls this method.
2792  return (true);
2793 }
2794 
2795 bool
2796 AllocEngine::reclaimDeclined(const Lease6Ptr& lease) {
2797  if (!lease || (lease->state_ != Lease::STATE_DECLINED) ) {
2798  return (true);
2799  }
2800 
2801  if (HooksManager::calloutsPresent(Hooks.hook_index_lease6_recover_)) {
2802  CalloutHandlePtr callout_handle = HooksManager::createCalloutHandle();
2803 
2804  // Use the RAII wrapper to make sure that the callout handle state is
2805  // reset when this object goes out of scope. All hook points must do
2806  // it to prevent possible circular dependency between the callout
2807  // handle and its arguments.
2808  ScopedCalloutHandleState callout_handle_state(callout_handle);
2809 
2810  // Pass necessary arguments
2811  callout_handle->setArgument("lease6", lease);
2812 
2813  // Call the callouts
2814  HooksManager::callCallouts(Hooks.hook_index_lease6_recover_, *callout_handle);
2815 
2816  // Callouts decided to skip the action. This means that the lease is not
2817  // assigned, so the client will get NoAddrAvail as a result. The lease
2818  // won't be inserted into the database.
2819  if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
2821  .arg(lease->addr_.toText());
2822  return (false);
2823  }
2824  }
2825 
2827  .arg(lease->addr_.toText())
2828  .arg(lease->valid_lft_);
2829 
2830  StatsMgr& stats_mgr = StatsMgr::instance();
2831 
2832  // Decrease subnet specific counter for currently declined addresses
2833  stats_mgr.addValue(StatsMgr::generateName("subnet", lease->subnet_id_,
2834  "declined-addresses"), static_cast<int64_t>(-1));
2835 
2836  // Decrease global counter for declined addresses
2837  stats_mgr.addValue("declined-addresses", static_cast<int64_t>(-1));
2838 
2839  stats_mgr.addValue("reclaimed-declined-addresses", static_cast<int64_t>(1));
2840 
2841  stats_mgr.addValue(StatsMgr::generateName("subnet", lease->subnet_id_,
2842  "reclaimed-declined-addresses"), static_cast<int64_t>(1));
2843 
2844  // Note that we do not touch assigned-nas counters. Those are
2845  // modified in whatever code calls this method.
2846 
2847  return (true);
2848 }
2849 
2850 template<typename LeasePtrType>
2851 void AllocEngine::reclaimLeaseInDatabase(const LeasePtrType& lease,
2852  const bool remove_lease,
2853  const std::function<void (const LeasePtrType&)>&
2854  lease_update_fun) const {
2855 
2856  LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
2857 
2858  // Reclaim the lease - depending on the configuration, set the
2859  // expired-reclaimed state or simply remove it.
2860  if (remove_lease) {
2861  lease_mgr.deleteLease(lease);
2862  } else if (lease_update_fun) {
2863  // Clear FQDN information as we have already sent the
2864  // name change request to remove the DNS record.
2865  lease->reuseable_valid_lft_ = 0;
2866  lease->hostname_.clear();
2867  lease->fqdn_fwd_ = false;
2868  lease->fqdn_rev_ = false;
2869  lease->state_ = Lease::STATE_EXPIRED_RECLAIMED;
2870  if (lease->getContext()) {
2871  lease->extended_info_action_ = Lease::ACTION_DELETE;
2872  lease->setContext(ElementPtr());
2873  }
2874  lease_update_fun(lease);
2875 
2876  } else {
2877  return;
2878  }
2879 
2880  // Lease has been reclaimed.
2883  .arg(lease->addr_.toText());
2884 }
2885 
2886 } // namespace dhcp
2887 } // namespace isc
2888 
2889 // ##########################################################################
2890 // # DHCPv4 lease allocation code starts here.
2891 // ##########################################################################
2892 
2893 namespace {
2894 
2912 bool
2913 addressReserved(const IOAddress& address, const AllocEngine::ClientContext4& ctx) {
2914  // When out-of-pool flag is true the server may assume that all host
2915  // reservations are for addresses that do not belong to the dynamic pool.
2916  // Therefore, it can skip the reservation checks when dealing with in-pool
2917  // addresses.
2918  if (ctx.subnet_ && ctx.subnet_->getReservationsInSubnet() &&
2919  (!ctx.subnet_->getReservationsOutOfPool() ||
2920  !ctx.subnet_->inPool(Lease::TYPE_V4, address))) {
2921  // The global parameter ip-reservations-unique controls whether it is allowed
2922  // to specify multiple reservations for the same IP address or delegated prefix
2923  // or IP reservations must be unique. Some host backends do not support the
2924  // former, thus we can't always use getAll4 calls to get the reservations
2925  // for the given IP. When we're in the default mode, when IP reservations
2926  // are unique, we should call get4 (supported by all backends). If we're in
2927  // the mode in which non-unique reservations are allowed the backends which
2928  // don't support it are not used and we can safely call getAll4.
2929  ConstHostCollection hosts;
2930  if (CfgMgr::instance().getCurrentCfg()->getCfgDbAccess()->getIPReservationsUnique()) {
2931  // Reservations are unique. It is safe to call get4 to get the unique host.
2932  ConstHostPtr host = HostMgr::instance().get4(ctx.subnet_->getID(), address);
2933  if (host) {
2934  hosts.push_back(host);
2935  }
2936  } else {
2937  // Reservations can be non-unique. Need to get all reservations for that address.
2938  hosts = HostMgr::instance().getAll4(ctx.subnet_->getID(), address);
2939  }
2940 
2941  for (auto host : hosts) {
2942  for (const AllocEngine::IdentifierPair& id_pair : ctx.host_identifiers_) {
2943  // If we find the matching host we know that this address is reserved
2944  // for us and we can return immediately.
2945  if (id_pair.first == host->getIdentifierType() &&
2946  id_pair.second == host->getIdentifier()) {
2947  return (false);
2948  }
2949  }
2950  }
2951  // We didn't find a matching host. If there are any reservations it means that
2952  // address is reserved for another client or multiple clients. If there are
2953  // no reservations address is not reserved for another client.
2954  return (!hosts.empty());
2955  }
2956  return (false);
2957 }
2958 
2974 bool
2975 hasAddressReservation(AllocEngine::ClientContext4& ctx) {
2976  if (ctx.hosts_.empty()) {
2977  return (false);
2978  }
2979 
2980  // Flag used to perform search for global reservations only once.
2981  bool search_global_done = false;
2982 
2983  Subnet4Ptr subnet = ctx.subnet_;
2984  while (subnet) {
2985  // Skip search if the global reservations have already been examined.
2986  if (!search_global_done && subnet->getReservationsGlobal()) {
2987  auto host = ctx.hosts_.find(SUBNET_ID_GLOBAL);
2988  // if we want global + other modes we would need to
2989  // return only if true, else continue
2990  if (host != ctx.hosts_.end() && host->second &&
2991  !host->second->getIPv4Reservation().isV4Zero()) {
2992  return (true);
2993  }
2994  // No need to perform this search again as there are no global
2995  // reservations.
2996  search_global_done = true;
2997  }
2998 
2999  if (subnet->getReservationsInSubnet()) {
3000  auto host = ctx.hosts_.find(subnet->getID());
3001  // The out-of-pool flag indicates that no client should be assigned
3002  // reserved addresses from within the dynamic pool, and for that
3003  // reason look only for reservations that are outside the pools,
3004  // hence the inPool check.
3005  if (host != ctx.hosts_.end() && host->second) {
3006  auto reservation = host->second->getIPv4Reservation();
3007  if (!reservation.isV4Zero() &&
3008  (!subnet->getReservationsOutOfPool() ||
3009  !subnet->inPool(Lease::TYPE_V4, reservation))) {
3010  ctx.subnet_ = subnet;
3011  return (true);
3012  }
3013  }
3014  }
3015 
3016  // No address reservation found here, so let's try another subnet
3017  // within the same shared network.
3018  subnet = subnet->getNextSubnet(ctx.subnet_, ctx.query_->getClasses());
3019  }
3020 
3021  return (false);
3022 }
3023 
3039 void findClientLease(AllocEngine::ClientContext4& ctx, Lease4Ptr& client_lease) {
3040  LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
3041 
3042  Subnet4Ptr original_subnet = ctx.subnet_;
3043 
3044  auto const& classes = ctx.query_->getClasses();
3045 
3046  // Client identifier is optional. First check if we can try to lookup
3047  // by client-id.
3048  bool try_clientid_lookup = (ctx.clientid_ &&
3049  SharedNetwork4::subnetsIncludeMatchClientId(original_subnet, classes));
3050 
3051  // If it is possible to use client identifier to try to find client's lease.
3052  if (try_clientid_lookup) {
3053  // Get all leases for this client identifier. When shared networks are
3054  // in use it is more efficient to make a single query rather than
3055  // multiple queries, one for each subnet.
3056  Lease4Collection leases_client_id = lease_mgr.getLease4(*ctx.clientid_);
3057 
3058  // Iterate over the subnets within the shared network to see if any client's
3059  // lease belongs to them.
3060  for (Subnet4Ptr subnet = original_subnet; subnet;
3061  subnet = subnet->getNextSubnet(original_subnet, classes)) {
3062 
3063  // If client identifier has been supplied and the server wasn't
3064  // explicitly configured to ignore client identifiers for this subnet
3065  // check if there is a lease within this subnet.
3066  if (subnet->getMatchClientId()) {
3067  for (auto l = leases_client_id.begin(); l != leases_client_id.end(); ++l) {
3068  if ((*l)->subnet_id_ == subnet->getID()) {
3069  // Lease found, so stick to this lease.
3070  client_lease = (*l);
3071  ctx.subnet_ = subnet;
3072  return;
3073  }
3074  }
3075  }
3076  }
3077  }
3078 
3079  // If no lease found using the client identifier, try the lookup using
3080  // the HW address.
3081  if (!client_lease && ctx.hwaddr_) {
3082 
3083  // Get all leases for this HW address.
3084  Lease4Collection leases_hw_address = lease_mgr.getLease4(*ctx.hwaddr_);
3085 
3086  for (Subnet4Ptr subnet = original_subnet; subnet;
3087  subnet = subnet->getNextSubnet(original_subnet, classes)) {
3088  ClientIdPtr client_id;
3089  if (subnet->getMatchClientId()) {
3090  client_id = ctx.clientid_;
3091  }
3092 
3093  // Try to find the lease that matches current subnet and belongs to
3094  // this client, so both HW address and client identifier match.
3095  for (Lease4Collection::const_iterator client_lease_it = leases_hw_address.begin();
3096  client_lease_it != leases_hw_address.end(); ++client_lease_it) {
3097  Lease4Ptr existing_lease = *client_lease_it;
3098  if ((existing_lease->subnet_id_ == subnet->getID()) &&
3099  existing_lease->belongsToClient(ctx.hwaddr_, client_id)) {
3100  // Found the lease of this client, so return it.
3101  client_lease = existing_lease;
3102  // We got a lease but the subnet it belongs to may differ from
3103  // the original subnet. Let's now stick to this subnet.
3104  ctx.subnet_ = subnet;
3105  return;
3106  }
3107  }
3108  }
3109  }
3110 }
3111 
3124 bool
3125 inAllowedPool(AllocEngine::ClientContext4& ctx, const IOAddress& address) {
3126  // If the subnet belongs to a shared network we will be iterating
3127  // over the subnets that belong to this shared network.
3128  Subnet4Ptr current_subnet = ctx.subnet_;
3129  auto const& classes = ctx.query_->getClasses();
3130 
3131  while (current_subnet) {
3132  if (current_subnet->inPool(Lease::TYPE_V4, address, classes)) {
3133  // We found a subnet that this address belongs to, so it
3134  // seems that this subnet is the good candidate for allocation.
3135  // Let's update the selected subnet.
3136  ctx.subnet_ = current_subnet;
3137  return (true);
3138  }
3139 
3140  current_subnet = current_subnet->getNextSubnet(ctx.subnet_, classes);
3141  }
3142 
3143  return (false);
3144 }
3145 
3146 } // namespace
3147 
3148 namespace isc {
3149 namespace dhcp {
3150 
3153  subnet_(), clientid_(), hwaddr_(),
3154  requested_address_(IOAddress::IPV4_ZERO_ADDRESS()),
3155  fwd_dns_update_(false), rev_dns_update_(false),
3157  old_lease_(), new_lease_(), hosts_(), conflicting_lease_(),
3158  query_(), host_identifiers_(), unknown_requested_addr_(false),
3159  ddns_params_() {
3160 }
3161 
3163  const ClientIdPtr& clientid,
3164  const HWAddrPtr& hwaddr,
3165  const asiolink::IOAddress& requested_addr,
3166  const bool fwd_dns_update,
3167  const bool rev_dns_update,
3168  const std::string& hostname,
3169  const bool fake_allocation)
3171  subnet_(subnet), clientid_(clientid), hwaddr_(hwaddr),
3172  requested_address_(requested_addr),
3173  fwd_dns_update_(fwd_dns_update), rev_dns_update_(rev_dns_update),
3174  hostname_(hostname), callout_handle_(),
3175  fake_allocation_(fake_allocation), old_lease_(), new_lease_(),
3177  ddns_params_(new DdnsParams()) {
3178 
3179  // Initialize host identifiers.
3180  if (hwaddr) {
3181  addHostIdentifier(Host::IDENT_HWADDR, hwaddr->hwaddr_);
3182  }
3183 }
3184 
3187  if (subnet_ && subnet_->getReservationsInSubnet()) {
3188  auto host = hosts_.find(subnet_->getID());
3189  if (host != hosts_.cend()) {
3190  return (host->second);
3191  }
3192  }
3193 
3194  return (globalHost());
3195 }
3196 
3199  if (subnet_ && subnet_->getReservationsGlobal()) {
3200  auto host = hosts_.find(SUBNET_ID_GLOBAL);
3201  if (host != hosts_.cend()) {
3202  return (host->second);
3203  }
3204  }
3205 
3206  return (ConstHostPtr());
3207 }
3208 
3211  // We already have it return it unless the context subnet has changed.
3212  if (ddns_params_ && subnet_ && (subnet_->getID() == ddns_params_->getSubnetId())) {
3213  return (ddns_params_);
3214  }
3215 
3216  // Doesn't exist yet or is stale, (re)create it.
3217  if (subnet_) {
3218  ddns_params_ = CfgMgr::instance().getCurrentCfg()->getDdnsParams(subnet_);
3219  return (ddns_params_);
3220  }
3221 
3222  // Asked for it without a subnet? This case really shouldn't occur but
3223  // for now let's return an instance with default values.
3224  return (DdnsParamsPtr(new DdnsParams()));
3225 }
3226 
3227 Lease4Ptr
3229  // The NULL pointer indicates that the old lease didn't exist. It may
3230  // be later set to non NULL value if existing lease is found in the
3231  // database.
3232  ctx.old_lease_.reset();
3233  ctx.new_lease_.reset();
3234 
3235  // Before we start allocation process, we need to make sure that the
3236  // selected subnet is allowed for this client. If not, we'll try to
3237  // use some other subnet within the shared network. If there are no
3238  // subnets allowed for this client within the shared network, we
3239  // can't allocate a lease.
3240  Subnet4Ptr subnet = ctx.subnet_;
3241  auto const& classes = ctx.query_->getClasses();
3242  if (subnet && !subnet->clientSupported(classes)) {
3243  ctx.subnet_ = subnet->getNextSubnet(subnet, classes);
3244  }
3245 
3246  try {
3247  if (!ctx.subnet_) {
3248  isc_throw(BadValue, "Can't allocate IPv4 address without subnet");
3249  }
3250 
3251  if (!ctx.hwaddr_) {
3252  isc_throw(BadValue, "HWAddr must be defined");
3253  }
3254 
3255  if (ctx.fake_allocation_) {
3256  return (discoverLease4(ctx));
3257 
3258  } else {
3259  ctx.new_lease_ = requestLease4(ctx);
3260  }
3261 
3262  } catch (const isc::Exception& e) {
3263  // Some other error, return an empty lease.
3265  .arg(ctx.query_->getLabel())
3266  .arg(e.what());
3267  }
3268 
3269  return (ctx.new_lease_);
3270 }
3271 
3272 void
3274  // If there is no subnet, there is nothing to do.
3275  if (!ctx.subnet_) {
3276  return;
3277  }
3278 
3279  auto subnet = ctx.subnet_;
3280 
3281  // If already done just return.
3283  !subnet->getReservationsInSubnet()) {
3284  return;
3285  }
3286 
3287  // @todo: This code can be trivially optimized.
3289  subnet->getReservationsGlobal()) {
3290  ConstHostPtr ghost = findGlobalReservation(ctx);
3291  if (ghost) {
3292  ctx.hosts_[SUBNET_ID_GLOBAL] = ghost;
3293 
3294  // If we had only to fetch global reservations it is done.
3295  if (!subnet->getReservationsInSubnet()) {
3296  return;
3297  }
3298  }
3299  }
3300 
3301  std::map<SubnetID, ConstHostPtr> host_map;
3302  SharedNetwork4Ptr network;
3303  subnet->getSharedNetwork(network);
3304 
3305  // If the subnet belongs to a shared network it is usually going to be
3306  // more efficient to make a query for all reservations for a particular
3307  // client rather than a query for each subnet within this shared network.
3308  // The only case when it is going to be less efficient is when there are
3309  // more host identifier types in use than subnets within a shared network.
3310  // As it breaks RADIUS use of host caching this can be disabled by the
3311  // host manager.
3312  const bool use_single_query = network &&
3314  (network->getAllSubnets()->size() > ctx.host_identifiers_.size());
3315 
3316  if (use_single_query) {
3317  for (const IdentifierPair& id_pair : ctx.host_identifiers_) {
3318  ConstHostCollection hosts = HostMgr::instance().getAll(id_pair.first,
3319  &id_pair.second[0],
3320  id_pair.second.size());
3321  // Store the hosts in the temporary map, because some hosts may
3322  // belong to subnets outside of the shared network. We'll need
3323  // to eliminate them.
3324  for (auto host = hosts.begin(); host != hosts.end(); ++host) {
3325  if ((*host)->getIPv4SubnetID() != SUBNET_ID_GLOBAL) {
3326  host_map[(*host)->getIPv4SubnetID()] = *host;
3327  }
3328  }
3329  }
3330  }
3331 
3332  auto const& classes = ctx.query_->getClasses();
3333  // We can only search for the reservation if a subnet has been selected.
3334  while (subnet) {
3335 
3336  // Only makes sense to get reservations if the client has access
3337  // to the class and host reservations are enabled for this subnet.
3338  if (subnet->clientSupported(classes) && subnet->getReservationsInSubnet()) {
3339  // Iterate over configured identifiers in the order of preference
3340  // and try to use each of them to search for the reservations.
3341  if (use_single_query) {
3342  if (host_map.count(subnet->getID()) > 0) {
3343  ctx.hosts_[subnet->getID()] = host_map[subnet->getID()];
3344  }
3345  } else {
3346  for (const IdentifierPair& id_pair : ctx.host_identifiers_) {
3347  // Attempt to find a host using a specified identifier.
3348  ConstHostPtr host = HostMgr::instance().get4(subnet->getID(),
3349  id_pair.first,
3350  &id_pair.second[0],
3351  id_pair.second.size());
3352  // If we found matching host for this subnet.
3353  if (host) {
3354  ctx.hosts_[subnet->getID()] = host;
3355  break;
3356  }
3357  }
3358  }
3359  }
3360 
3361  // We need to get to the next subnet if this is a shared network. If it
3362  // is not (a plain subnet), getNextSubnet will return NULL and we're
3363  // done here.
3364  subnet = subnet->getNextSubnet(ctx.subnet_, classes);
3365  }
3366 }
3367 
3370  ConstHostPtr host;
3371  for (const IdentifierPair& id_pair : ctx.host_identifiers_) {
3372  // Attempt to find a host using a specified identifier.
3373  host = HostMgr::instance().get4(SUBNET_ID_GLOBAL, id_pair.first,
3374  &id_pair.second[0], id_pair.second.size());
3375 
3376  // If we found matching global host we're done.
3377  if (host) {
3378  break;
3379  }
3380  }
3381 
3382  return (host);
3383 }
3384 
3385 Lease4Ptr
3386 AllocEngine::discoverLease4(AllocEngine::ClientContext4& ctx) {
3387  // Find an existing lease for this client. This function will return null
3388  // if there is a conflict with existing lease and the allocation should
3389  // not be continued.
3390  Lease4Ptr client_lease;
3391  findClientLease(ctx, client_lease);
3392 
3393  // new_lease will hold the pointer to the lease that we will offer to the
3394  // caller.
3395  Lease4Ptr new_lease;
3396 
3397  CalloutHandle::CalloutNextStep callout_status = CalloutHandle::NEXT_STEP_CONTINUE;
3398 
3399  // Check if there is a reservation for the client. If there is, we want to
3400  // assign the reserved address, rather than any other one.
3401  if (hasAddressReservation(ctx)) {
3402 
3405  .arg(ctx.query_->getLabel())
3406  .arg(ctx.currentHost()->getIPv4Reservation().toText());
3407 
3408  // If the client doesn't have a lease or the leased address is different
3409  // than the reserved one then let's try to allocate the reserved address.
3410  // Otherwise the address that the client has is the one for which it
3411  // has a reservation, so just renew it.
3412  if (!client_lease || (client_lease->addr_ != ctx.currentHost()->getIPv4Reservation())) {
3413  // The call below will return a pointer to the lease for the address
3414  // reserved to this client, if the lease is available, i.e. is not
3415  // currently assigned to any other client.
3416  // Note that we don't remove the existing client's lease at this point
3417  // because this is not a real allocation, we just offer what we can
3418  // allocate in the DHCPREQUEST time.
3419  new_lease = allocateOrReuseLease4(ctx.currentHost()->getIPv4Reservation(), ctx,
3420  callout_status);
3421  if (!new_lease) {
3423  .arg(ctx.query_->getLabel())
3424  .arg(ctx.currentHost()->getIPv4Reservation().toText())
3425  .arg(ctx.conflicting_lease_ ? ctx.conflicting_lease_->toText() :
3426  "(no lease info)");
3427  StatsMgr::instance().addValue(StatsMgr::generateName(
3428  "subnet",
3429  ctx.conflicting_lease_->subnet_id_,
3430  "v4-reservation-conflicts"),
3431  static_cast<int64_t>(1));
3432  StatsMgr::instance().addValue("v4-reservation-conflicts",
3433  static_cast<int64_t>(1));
3434  }
3435 
3436  } else {
3437  new_lease = renewLease4(client_lease, ctx);
3438  }
3439  }
3440 
3441  // Client does not have a reservation or the allocation of the reserved
3442  // address has failed, probably because the reserved address is in use
3443  // by another client. If the client has a lease, we will check if we can
3444  // offer this lease to the client. The lease can't be offered in the
3445  // situation when it is reserved for another client or when the address
3446  // is not in the dynamic pool. The former may be the result of adding the
3447  // new reservation for the address used by this client. The latter may
3448  // be due to the client using the reserved out-of-the pool address, for
3449  // which the reservation has just been removed.
3450  if (!new_lease && client_lease && inAllowedPool(ctx, client_lease->addr_) &&
3451  !addressReserved(client_lease->addr_, ctx)) {
3452 
3455  .arg(ctx.query_->getLabel());
3456 
3457  new_lease = renewLease4(client_lease, ctx);
3458  }
3459 
3460  // The client doesn't have any lease or the lease can't be offered
3461  // because it is either reserved for some other client or the
3462  // address is not in the dynamic pool.
3463  // Let's use the client's hint (requested IP address), if the client
3464  // has provided it, and try to offer it. This address must not be
3465  // reserved for another client, and must be in the range of the
3466  // dynamic pool.
3467  if (!new_lease && !ctx.requested_address_.isV4Zero() &&
3468  inAllowedPool(ctx, ctx.requested_address_) &&
3469  !addressReserved(ctx.requested_address_, ctx)) {
3470 
3473  .arg(ctx.requested_address_.toText())
3474  .arg(ctx.query_->getLabel());
3475 
3476  new_lease = allocateOrReuseLease4(ctx.requested_address_, ctx,
3477  callout_status);
3478  }
3479 
3480  // The allocation engine failed to allocate all of the candidate
3481  // addresses. We will now use the allocator to pick the address
3482  // from the dynamic pool.
3483  if (!new_lease) {
3484 
3487  .arg(ctx.query_->getLabel());
3488 
3489  new_lease = allocateUnreservedLease4(ctx);
3490  }
3491 
3492  // Some of the methods like reuseExpiredLease4 may set the old lease to point
3493  // to the lease which they remove/override. If it is not set, but we have
3494  // found that the client has the lease the client's lease is the one
3495  // to return as an old lease.
3496  if (!ctx.old_lease_ && client_lease) {
3497  ctx.old_lease_ = client_lease;
3498  }
3499 
3500  return (new_lease);
3501 }
3502 
3503 Lease4Ptr
3504 AllocEngine::requestLease4(AllocEngine::ClientContext4& ctx) {
3505  // Find an existing lease for this client. This function will return null
3506  // if there is a conflict with existing lease and the allocation should
3507  // not be continued.
3508  Lease4Ptr client_lease;
3509  findClientLease(ctx, client_lease);
3510 
3511  // When the client sends the DHCPREQUEST, it should always specify the
3512  // address which it is requesting or renewing. That is, the client should
3513  // either use the requested IP address option or set the ciaddr. However,
3514  // we try to be liberal and allow the clients to not specify an address
3515  // in which case the allocation engine will pick a suitable address
3516  // for the client.
3517  if (!ctx.requested_address_.isV4Zero()) {
3518  // If the client has specified an address, make sure this address
3519  // is not reserved for another client. If it is, stop here because
3520  // we can't allocate this address.
3521  if (addressReserved(ctx.requested_address_, ctx)) {
3522 
3525  .arg(ctx.query_->getLabel())
3526  .arg(ctx.requested_address_.toText());
3527 
3528  return (Lease4Ptr());
3529  }
3530 
3531  } else if (hasAddressReservation(ctx)) {
3532  // The client hasn't specified an address to allocate, so the
3533  // allocation engine needs to find an appropriate address.
3534  // If there is a reservation for the client, let's try to
3535  // allocate the reserved address.
3536  ctx.requested_address_ = ctx.currentHost()->getIPv4Reservation();
3537 
3540  .arg(ctx.query_->getLabel())
3541  .arg(ctx.requested_address_.toText());
3542  }
3543 
3544  if (!ctx.requested_address_.isV4Zero()) {
3545  // There is a specific address to be allocated. Let's find out if
3546  // the address is in use.
3548  // If the address is in use (allocated and not expired), we check
3549  // if the address is in use by our client or another client.
3550  // If it is in use by another client, the address can't be
3551  // allocated.
3552  if (existing && !existing->expired() &&
3553  !existing->belongsToClient(ctx.hwaddr_, ctx.subnet_->getMatchClientId() ?
3554  ctx.clientid_ : ClientIdPtr())) {
3555 
3558  .arg(ctx.query_->getLabel())
3559  .arg(ctx.requested_address_.toText());
3560 
3561  return (Lease4Ptr());
3562  }
3563 
3564  // If the client has a reservation but it is requesting a different
3565  // address it is possible that the client was offered this different
3566  // address because the reserved address is in use. We will have to
3567  // check if the address is in use.
3568  if (hasAddressReservation(ctx) &&
3569  (ctx.currentHost()->getIPv4Reservation() != ctx.requested_address_)) {
3570  existing =
3571  LeaseMgrFactory::instance().getLease4(ctx.currentHost()->getIPv4Reservation());
3572  // If the reserved address is not in use, i.e. the lease doesn't
3573  // exist or is expired, and the client is requesting a different
3574  // address, return NULL. The client should go back to the
3575  // DHCPDISCOVER and the reserved address will be offered.
3576  if (!existing || existing->expired()) {
3577 
3580  .arg(ctx.query_->getLabel())
3581  .arg(ctx.currentHost()->getIPv4Reservation().toText())
3582  .arg(ctx.requested_address_.toText());
3583 
3584  return (Lease4Ptr());
3585  }
3586  }
3587 
3588  // The use of the out-of-pool addresses is only allowed when the requested
3589  // address is reserved for the client. If the address is not reserved one
3590  // and it doesn't belong to the dynamic pool, do not allocate it.
3591  if ((!hasAddressReservation(ctx) ||
3592  (ctx.currentHost()->getIPv4Reservation() != ctx.requested_address_)) &&
3593  !inAllowedPool(ctx, ctx.requested_address_)) {
3594 
3597  .arg(ctx.query_->getLabel())
3598  .arg(ctx.requested_address_);
3599 
3600  ctx.unknown_requested_addr_ = true;
3601  return (Lease4Ptr());
3602  }
3603  }
3604 
3605  // We have gone through all the checks, so we can now allocate the address
3606  // for the client.
3607 
3608  // If the client is requesting an address which is assigned to the client
3609  // let's just renew this address. Also, renew this address if the client
3610  // doesn't request any specific address.
3611  // Added extra checks: the address is reserved for this client or belongs
3612  // to the dynamic pool for the case the pool class has changed before the
3613  // request.
3614  if (client_lease) {
3615  if (((client_lease->addr_ == ctx.requested_address_) ||
3616  ctx.requested_address_.isV4Zero()) &&
3617  ((hasAddressReservation(ctx) &&
3618  (ctx.currentHost()->getIPv4Reservation() == ctx.requested_address_)) ||
3619  inAllowedPool(ctx, client_lease->addr_))) {
3620 
3623  .arg(ctx.query_->getLabel())
3624  .arg(ctx.requested_address_);
3625 
3626  return (renewLease4(client_lease, ctx));
3627  }
3628  }
3629 
3630  // new_lease will hold the pointer to the allocated lease if we allocate
3631  // successfully.
3632  Lease4Ptr new_lease;
3633 
3634  // The client doesn't have the lease or it is requesting an address
3635  // which it doesn't have. Let's try to allocate the requested address.
3636  if (!ctx.requested_address_.isV4Zero()) {
3637 
3640  .arg(ctx.query_->getLabel())
3641  .arg(ctx.requested_address_.toText());
3642 
3643  // The call below will return a pointer to the lease allocated
3644  // for the client if there is no lease for the requested address,
3645  // or the existing lease has expired. If the allocation fails,
3646  // e.g. because the lease is in use, we will return NULL to
3647  // indicate that we were unable to allocate the lease.
3648  CalloutHandle::CalloutNextStep callout_status = CalloutHandle::NEXT_STEP_CONTINUE;
3649  new_lease = allocateOrReuseLease4(ctx.requested_address_, ctx,
3650  callout_status);
3651 
3652  } else {
3653 
3656  .arg(ctx.query_->getLabel());
3657 
3658  // We will only get here if the client didn't specify which
3659  // address it wanted to be allocated. The allocation engine will
3660  // to pick the address from the dynamic pool.
3661  new_lease = allocateUnreservedLease4(ctx);
3662  }
3663 
3664  // If we allocated the lease for the client, but the client already had a
3665  // lease, we will need to return the pointer to the previous lease and
3666  // the previous lease needs to be removed from the lease database.
3667  if (new_lease && client_lease) {
3668  ctx.old_lease_ = Lease4Ptr(new Lease4(*client_lease));
3669 
3672  .arg(ctx.query_->getLabel())
3673  .arg(client_lease->addr_.toText());
3674 
3675  if (LeaseMgrFactory::instance().deleteLease(client_lease)) {
3676  // Need to decrease statistic for assigned addresses.
3677  StatsMgr::instance().addValue(
3678  StatsMgr::generateName("subnet", client_lease->subnet_id_,
3679  "assigned-addresses"),
3680  static_cast<int64_t>(-1));
3681  }
3682  }
3683 
3684  // Return the allocated lease or NULL pointer if allocation was
3685  // unsuccessful.
3686  return (new_lease);
3687 }
3688 
3689 uint32_t
3691 
3692  // If it's BOOTP, use infinite valid lifetime.
3693  if (ctx.query_->inClass("BOOTP")) {
3694  return (Lease::INFINITY_LFT);
3695  }
3696 
3697  // Use the dhcp-lease-time content from the client if it's there.
3698  uint32_t requested_lft = 0;
3699  OptionPtr opt = ctx.query_->getOption(DHO_DHCP_LEASE_TIME);
3700  if (opt) {
3701  OptionUint32Ptr opt_lft = boost::dynamic_pointer_cast<OptionInt<uint32_t> >(opt);
3702  if (opt_lft) {
3703  requested_lft = opt_lft->getValue();
3704  }
3705  }
3706 
3707  // If the triplet is specified in one of our classes use it.
3708  // We use the first one we find.
3709  Triplet<uint32_t> candidate_lft;
3710  const ClientClasses classes = ctx.query_->getClasses();
3711  if (!classes.empty()) {
3712  // Let's get class definitions
3713  const ClientClassDictionaryPtr& dict =
3714  CfgMgr::instance().getCurrentCfg()->getClientClassDictionary();
3715 
3716  // Iterate over the assigned class definitions.
3717  for (ClientClasses::const_iterator name = classes.cbegin();
3718  name != classes.cend(); ++name) {
3719  ClientClassDefPtr cl = dict->findClass(*name);
3720  if (cl && (!cl->getValid().unspecified())) {
3721  candidate_lft = cl->getValid();
3722  break;
3723  }
3724  }
3725  }
3726 
3727  // If no classes specified it, get it from the subnet.
3728  if (!candidate_lft) {
3729  candidate_lft = ctx.subnet_->getValid();
3730  }
3731 
3732  // If client requested a value, use the value bounded by
3733  // the candidate triplet.
3734  if (requested_lft > 0) {
3735  return (candidate_lft.get(requested_lft));
3736  }
3737 
3738  // Use the candidate's default value.
3739  return (candidate_lft.get());
3740 }
3741 
3742 Lease4Ptr
3743 AllocEngine::createLease4(const ClientContext4& ctx, const IOAddress& addr,
3744  CalloutHandle::CalloutNextStep& callout_status) {
3745  if (!ctx.hwaddr_) {
3746  isc_throw(BadValue, "Can't create a lease with NULL HW address");
3747  }
3748  if (!ctx.subnet_) {
3749  isc_throw(BadValue, "Can't create a lease without a subnet");
3750  }
3751 
3752  // Get the context appropriate valid lifetime.
3753  uint32_t valid_lft = getValidLft(ctx);
3754 
3755  time_t now = time(NULL);
3756 
3757  ClientIdPtr client_id;
3758  if (ctx.subnet_->getMatchClientId()) {
3759  client_id = ctx.clientid_;
3760  }
3761 
3762  Lease4Ptr lease(new Lease4(addr, ctx.hwaddr_, client_id,
3763  valid_lft, now, ctx.subnet_->getID()));
3764 
3765  // Set FQDN specific lease parameters.
3766  lease->fqdn_fwd_ = ctx.fwd_dns_update_;
3767  lease->fqdn_rev_ = ctx.rev_dns_update_;
3768  lease->hostname_ = ctx.hostname_;
3769 
3770  // Add(update) the extended information on the lease.
3771  updateLease4ExtendedInfo(lease, ctx);
3772 
3773  // Let's execute all callouts registered for lease4_select
3774  if (ctx.callout_handle_ &&
3775  HooksManager::calloutsPresent(hook_index_lease4_select_)) {
3776 
3777  // Use the RAII wrapper to make sure that the callout handle state is
3778  // reset when this object goes out of scope. All hook points must do
3779  // it to prevent possible circular dependency between the callout
3780  // handle and its arguments.
3781  ScopedCalloutHandleState callout_handle_state(ctx.callout_handle_);
3782 
3783  // Enable copying options from the packet within hook library.
3784  ScopedEnableOptionsCopy<Pkt4> query4_options_copy(ctx.query_);
3785 
3786  // Pass necessary arguments
3787  // Pass the original client query
3788  ctx.callout_handle_->setArgument("query4", ctx.query_);
3789 
3790  // Subnet from which we do the allocation (That's as far as we can go
3791  // with using SubnetPtr to point to Subnet4 object. Users should not
3792  // be confused with dynamic_pointer_casts. They should get a concrete
3793  // pointer (Subnet4Ptr) pointing to a Subnet4 object.
3794  Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(ctx.subnet_);
3795  ctx.callout_handle_->setArgument("subnet4", subnet4);
3796 
3797  // Is this solicit (fake = true) or request (fake = false)
3798  ctx.callout_handle_->setArgument("fake_allocation", ctx.fake_allocation_);
3799 
3800  // Pass the intended lease as well
3801  ctx.callout_handle_->setArgument("lease4", lease);
3802 
3803  // This is the first callout, so no need to clear any arguments
3804  HooksManager::callCallouts(hook_index_lease4_select_, *ctx.callout_handle_);
3805 
3806  callout_status = ctx.callout_handle_->getStatus();
3807 
3808  // Callouts decided to skip the action. This means that the lease is not
3809  // assigned, so the client will get NoAddrAvail as a result. The lease
3810  // won't be inserted into the database.
3811  if (callout_status == CalloutHandle::NEXT_STEP_SKIP) {
3813  return (Lease4Ptr());
3814  }
3815 
3816  // Let's use whatever callout returned. Hopefully it is the same lease
3817  // we handled to it.
3818  ctx.callout_handle_->getArgument("lease4", lease);
3819  }
3820 
3821  if (!ctx.fake_allocation_) {
3822  // That is a real (REQUEST) allocation
3823  bool status = LeaseMgrFactory::instance().addLease(lease);
3824  if (status) {
3825 
3826  // The lease insertion succeeded, let's bump up the statistic.
3827  StatsMgr::instance().addValue(
3828  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
3829  "assigned-addresses"),
3830  static_cast<int64_t>(1));
3831  StatsMgr::instance().addValue(
3832  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
3833  "cumulative-assigned-addresses"),
3834  static_cast<int64_t>(1));
3835  StatsMgr::instance().addValue("cumulative-assigned-addresses",
3836  static_cast<int64_t>(1));
3837 
3838  return (lease);
3839  } else {
3840  // One of many failures with LeaseMgr (e.g. lost connection to the
3841  // database, database failed etc.). One notable case for that
3842  // is that we are working in multi-process mode and we lost a race
3843  // (some other process got that address first)
3844  return (Lease4Ptr());
3845  }
3846  } else {
3847  // That is only fake (DISCOVER) allocation
3848 
3849  // It is for OFFER only. We should not insert the lease and callers
3850  // have already verified the lease does not exist in the database.
3851  return (lease);
3852  }
3853 }
3854 
3855 Lease4Ptr
3856 AllocEngine::renewLease4(const Lease4Ptr& lease,
3858  if (!lease) {
3859  isc_throw(BadValue, "null lease specified for renewLease4");
3860  }
3861 
3862  // Let's keep the old data. This is essential if we are using memfile
3863  // (the lease returned points directly to the lease4 object in the database)
3864  // We'll need it if we want to skip update (i.e. roll back renewal)
3866  Lease4Ptr old_values = boost::make_shared<Lease4>(*lease);
3867  ctx.old_lease_.reset(new Lease4(*old_values));
3868 
3869  // Update the lease with the information from the context.
3870  // If there was no significant changes, try reuse.
3871  lease->reuseable_valid_lft_ = 0;
3872  if (!updateLease4Information(lease, ctx)) {
3873  setLeaseReusable(lease, ctx);
3874  }
3875 
3876  if (!ctx.fake_allocation_) {
3877  // If the lease is expired we have to reclaim it before
3878  // re-assigning it to the client. The lease reclamation
3879  // involves execution of hooks and DNS update.
3880  if (ctx.old_lease_->expired()) {
3881  reclaimExpiredLease(ctx.old_lease_, ctx.callout_handle_);
3882  }
3883 
3884  lease->state_ = Lease::STATE_DEFAULT;
3885  }
3886 
3887  bool skip = false;
3888  // Execute all callouts registered for lease4_renew.
3889  if (HooksManager::calloutsPresent(Hooks.hook_index_lease4_renew_)) {
3890 
3891  // Use the RAII wrapper to make sure that the callout handle state is
3892  // reset when this object goes out of scope. All hook points must do
3893  // it to prevent possible circular dependency between the callout
3894  // handle and its arguments.
3895  ScopedCalloutHandleState callout_handle_state(ctx.callout_handle_);
3896 
3897  // Enable copying options from the packet within hook library.
3898  ScopedEnableOptionsCopy<Pkt4> query4_options_copy(ctx.query_);
3899 
3900  // Subnet from which we do the allocation. Convert the general subnet
3901  // pointer to a pointer to a Subnet4. Note that because we are using
3902  // boost smart pointers here, we need to do the cast using the boost
3903  // version of dynamic_pointer_cast.
3904  Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(ctx.subnet_);
3905 
3906  // Pass the parameters. Note the clientid is passed only if match-client-id
3907  // is set. This is done that way, because the lease4-renew hook point is
3908  // about renewing a lease and the configuration parameter says the
3909  // client-id should be ignored. Hence no clientid value if match-client-id
3910  // is false.
3911  ctx.callout_handle_->setArgument("query4", ctx.query_);
3912  ctx.callout_handle_->setArgument("subnet4", subnet4);
3913  ctx.callout_handle_->setArgument("clientid", subnet4->getMatchClientId() ?
3914  ctx.clientid_ : ClientIdPtr());
3915  ctx.callout_handle_->setArgument("hwaddr", ctx.hwaddr_);
3916 
3917  // Pass the lease to be updated
3918  ctx.callout_handle_->setArgument("lease4", lease);
3919 
3920  // Call all installed callouts
3921  HooksManager::callCallouts(Hooks.hook_index_lease4_renew_,
3922  *ctx.callout_handle_);
3923 
3924  // Callouts decided to skip the next processing step. The next
3925  // processing step would actually renew the lease, so skip at this
3926  // stage means "keep the old lease as it is".
3927  if (ctx.callout_handle_->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
3928  skip = true;
3931  }
3932 
3934  }
3935 
3936  if (!ctx.fake_allocation_ && !skip && (lease->reuseable_valid_lft_ == 0)) {
3937  // for REQUEST we do update the lease
3939 
3940  // We need to account for the re-assignment of The lease.
3941  if (ctx.old_lease_->expired() || ctx.old_lease_->state_ == Lease::STATE_EXPIRED_RECLAIMED) {
3942  StatsMgr::instance().addValue(
3943  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
3944  "assigned-addresses"),
3945  static_cast<int64_t>(1));
3946  StatsMgr::instance().addValue(
3947  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
3948  "cumulative-assigned-addresses"),
3949  static_cast<int64_t>(1));
3950  StatsMgr::instance().addValue("cumulative-assigned-addresses",
3951  static_cast<int64_t>(1));
3952  }
3953  }
3954  if (skip) {
3955  // Rollback changes (really useful only for memfile)
3957  *lease = *old_values;
3958  }
3959 
3960  return (lease);
3961 }
3962 
3963 Lease4Ptr
3964 AllocEngine::reuseExpiredLease4(Lease4Ptr& expired,
3966  CalloutHandle::CalloutNextStep& callout_status) {
3967  if (!expired) {
3968  isc_throw(BadValue, "null lease specified for reuseExpiredLease");
3969  }
3970 
3971  if (!ctx.subnet_) {
3972  isc_throw(BadValue, "null subnet specified for the reuseExpiredLease");
3973  }
3974 
3975  if (!ctx.fake_allocation_) {
3976  // The expired lease needs to be reclaimed before it can be reused.
3977  // This includes declined leases for which probation period has
3978  // elapsed.
3979  reclaimExpiredLease(expired, ctx.callout_handle_);
3980  expired->state_ = Lease::STATE_DEFAULT;
3981  }
3982 
3983  expired->reuseable_valid_lft_ = 0;
3984  static_cast<void>(updateLease4Information(expired, ctx));
3985 
3988  .arg(ctx.query_->getLabel())
3989  .arg(expired->toText());
3990 
3991  // Let's execute all callouts registered for lease4_select
3992  if (ctx.callout_handle_ &&
3993  HooksManager::calloutsPresent(hook_index_lease4_select_)) {
3994 
3995  // Enable copying options from the packet within hook library.
3996  ScopedEnableOptionsCopy<Pkt4> query4_options_copy(ctx.query_);
3997 
3998  // Use the RAII wrapper to make sure that the callout handle state is
3999  // reset when this object goes out of scope. All hook points must do
4000  // it to prevent possible circular dependency between the callout
4001  // handle and its arguments.
4002  ScopedCalloutHandleState callout_handle_state(ctx.callout_handle_);
4003 
4004  // Pass necessary arguments
4005  // Pass the original client query
4006  ctx.callout_handle_->setArgument("query4", ctx.query_);
4007 
4008  // Subnet from which we do the allocation. Convert the general subnet
4009  // pointer to a pointer to a Subnet4. Note that because we are using
4010  // boost smart pointers here, we need to do the cast using the boost
4011  // version of dynamic_pointer_cast.
4012  Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(ctx.subnet_);
4013  ctx.callout_handle_->setArgument("subnet4", subnet4);
4014 
4015  // Is this solicit (fake = true) or request (fake = false)
4016  ctx.callout_handle_->setArgument("fake_allocation", ctx.fake_allocation_);
4017 
4018  // The lease that will be assigned to a client
4019  ctx.callout_handle_->setArgument("lease4", expired);
4020 
4021  // Call the callouts
4022  HooksManager::callCallouts(hook_index_lease4_select_, *ctx.callout_handle_);
4023 
4024  callout_status = ctx.callout_handle_->getStatus();
4025 
4026  // Callouts decided to skip the action. This means that the lease is not
4027  // assigned, so the client will get NoAddrAvail as a result. The lease
4028  // won't be inserted into the database.
4029  if (callout_status == CalloutHandle::NEXT_STEP_SKIP) {
4032  return (Lease4Ptr());
4033  }
4034 
4036 
4037  // Let's use whatever callout returned. Hopefully it is the same lease
4038  // we handed to it.
4039  ctx.callout_handle_->getArgument("lease4", expired);
4040  }
4041 
4042  if (!ctx.fake_allocation_) {
4043  // for REQUEST we do update the lease
4045 
4046  // We need to account for the re-assignment of The lease.
4047  StatsMgr::instance().addValue(
4048  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4049  "assigned-addresses"),
4050  static_cast<int64_t>(1));
4051  StatsMgr::instance().addValue(
4052  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4053  "cumulative-assigned-addresses"),
4054  static_cast<int64_t>(1));
4055  StatsMgr::instance().addValue("cumulative-assigned-addresses",
4056  static_cast<int64_t>(1));
4057  }
4058 
4059  // We do nothing for SOLICIT. We'll just update database when
4060  // the client gets back to us with REQUEST message.
4061 
4062  // it's not really expired at this stage anymore - let's return it as
4063  // an updated lease
4064  return (expired);
4065 }
4066 
4067 Lease4Ptr
4068 AllocEngine::allocateOrReuseLease4(const IOAddress& candidate, ClientContext4& ctx,
4069  CalloutHandle::CalloutNextStep& callout_status) {
4070  ctx.conflicting_lease_.reset();
4071 
4072  Lease4Ptr exist_lease = LeaseMgrFactory::instance().getLease4(candidate);
4073  if (exist_lease) {
4074  if (exist_lease->expired()) {
4075  ctx.old_lease_ = Lease4Ptr(new Lease4(*exist_lease));
4076  // reuseExpiredLease4() will reclaim the use which will
4077  // queue an NCR remove it needed. Clear the DNS fields in
4078  // the old lease to avoid a redundant remove in server logic.
4079  ctx.old_lease_->hostname_.clear();
4080  ctx.old_lease_->fqdn_fwd_ = false;
4081  ctx.old_lease_->fqdn_rev_ = false;
4082  return (reuseExpiredLease4(exist_lease, ctx, callout_status));
4083 
4084  } else {
4085  // If there is a lease and it is not expired, pass this lease back
4086  // to the caller in the context. The caller may need to know
4087  // which lease we're conflicting with.
4088  ctx.conflicting_lease_ = exist_lease;
4089  }
4090 
4091  } else {
4092  return (createLease4(ctx, candidate, callout_status));
4093  }
4094  return (Lease4Ptr());
4095 }
4096 
4097 Lease4Ptr
4098 AllocEngine::allocateUnreservedLease4(ClientContext4& ctx) {
4099  Lease4Ptr new_lease;
4100  Subnet4Ptr subnet = ctx.subnet_;
4101 
4102  // Need to check if the subnet belongs to a shared network. If so,
4103  // we might be able to find a better subnet for lease allocation,
4104  // for which it is more likely that there are some leases available.
4105  // If we stick to the selected subnet, we may end up walking over
4106  // the entire subnet (or more subnets) to discover that the address
4107  // pools have been exhausted. Using a subnet from which an address
4108  // was assigned most recently is an optimization which increases
4109  // the likelihood of starting from the subnet which address pools
4110  // are not exhausted.
4111  SharedNetwork4Ptr network;
4112  ctx.subnet_->getSharedNetwork(network);
4113  if (network) {
4114  // This would try to find a subnet with the same set of classes
4115  // as the current subnet, but with the more recent "usage timestamp".
4116  // This timestamp is only updated for the allocations made with an
4117  // allocator (unreserved lease allocations), not the static
4118  // allocations or requested addresses.
4119  ctx.subnet_ = subnet = network->getPreferredSubnet(ctx.subnet_);
4120  }
4121 
4122  // We have the choice in the order checking the lease and
4123  // the reservation. The default is to begin by the lease
4124  // if the multi-threading is disabled.
4125  bool check_reservation_first = MultiThreadingMgr::instance().getMode();
4126 
4127  Subnet4Ptr original_subnet = subnet;
4128 
4129  uint64_t total_attempts = 0;
4130 
4131  // The following counter tracks the number of subnets with matching client
4132  // classes from which the allocation engine attempted to assign leases.
4133  uint64_t subnets_with_unavail_leases = 0;
4134  // The following counter tracks the number of subnets in which there were
4135  // no matching pools for the client.
4136  uint64_t subnets_with_unavail_pools = 0;
4137 
4138  auto const& classes = ctx.query_->getClasses();
4139 
4140  while (subnet) {
4141  ClientIdPtr client_id;
4142  if (subnet->getMatchClientId()) {
4143  client_id = ctx.clientid_;
4144  }
4145 
4146  uint64_t possible_attempts =
4147  subnet->getPoolCapacity(Lease::TYPE_V4, classes);
4148 
4149  // If the number of tries specified in the allocation engine constructor
4150  // is set to 0 (unlimited) or the pools capacity is lower than that number,
4151  // let's use the pools capacity as the maximum number of tries. Trying
4152  // more than the actual pools capacity is a waste of time. If the specified
4153  // number of tries is lower than the pools capacity, use that number.
4154  uint64_t max_attempts = ((attempts_ == 0 || possible_attempts < attempts_) ? possible_attempts : attempts_);
4155 
4156  if (max_attempts > 0) {
4157  // If max_attempts is greater than 0, there are some pools in this subnet
4158  // from which we can potentially get a lease.
4159  ++subnets_with_unavail_leases;
4160  } else {
4161  // If max_attempts is 0, it is an indication that there are no pools
4162  // in the subnet from which we can get a lease.
4163  ++subnets_with_unavail_pools;
4164  }
4165 
4166  CalloutHandle::CalloutNextStep callout_status = CalloutHandle::NEXT_STEP_CONTINUE;
4167 
4168  for (uint64_t i = 0; i < max_attempts; ++i) {
4169 
4170  ++total_attempts;
4171 
4172  auto allocator = subnet->getAllocator(Lease::TYPE_V4);
4173  IOAddress candidate = allocator->pickAddress(classes,
4174  client_id,
4175  ctx.requested_address_);
4176  // First check for reservation when it is the choice.
4177  if (check_reservation_first && addressReserved(candidate, ctx)) {
4178  // Don't allocate.
4179  continue;
4180  }
4181 
4182  // Check if the resource is busy i.e. can be being allocated
4183  // by another thread to another client.
4184  ResourceHandler4 resource_handler;
4185  if (MultiThreadingMgr::instance().getMode() &&
4186  !resource_handler.tryLock4(candidate)) {
4187  // Don't allocate.
4188  continue;
4189  }
4190 
4191  // Check for an existing lease for the candidate address.
4192  Lease4Ptr exist_lease = LeaseMgrFactory::instance().getLease4(candidate);
4193  if (!exist_lease) {
4194  // No existing lease, is it reserved?
4195  if (check_reservation_first || !addressReserved(candidate, ctx)) {
4196  // Not reserved use it.
4197  new_lease = createLease4(ctx, candidate, callout_status);
4198  }
4199  } else {
4200  // An lease exists, is expired, and not reserved use it.
4201  if (exist_lease->expired() &&
4202  (check_reservation_first || !addressReserved(candidate, ctx))) {
4203  ctx.old_lease_ = Lease4Ptr(new Lease4(*exist_lease));
4204  new_lease = reuseExpiredLease4(exist_lease, ctx, callout_status);
4205  }
4206  }
4207 
4208  // We found a lease we can use, return it.
4209  if (new_lease) {
4210  return (new_lease);
4211  }
4212 
4213  if (ctx.callout_handle_ && (callout_status != CalloutHandle::NEXT_STEP_CONTINUE)) {
4214  // Don't retry when the callout status is not continue.
4215  subnet.reset();
4216  break;
4217  }
4218  }
4219 
4220  // This pointer may be set to NULL if hooks set SKIP status.
4221  if (subnet) {
4222  subnet = subnet->getNextSubnet(original_subnet, classes);
4223 
4224  if (subnet) {
4225  ctx.subnet_ = subnet;
4226  }
4227  }
4228  }
4229 
4230  if (network) {
4231  // The client is in the shared network. Let's log the high level message
4232  // indicating which shared network the client belongs to.
4234  .arg(ctx.query_->getLabel())
4235  .arg(network->getName())
4236  .arg(subnets_with_unavail_leases)
4237  .arg(subnets_with_unavail_pools);
4238  StatsMgr::instance().addValue("v4-allocation-fail-shared-network",
4239  static_cast<int64_t>(1));
4240  StatsMgr::instance().addValue(
4241  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4242  "v4-allocation-fail-shared-network"),
4243  static_cast<int64_t>(1));
4244  } else {
4245  // The client is not connected to a shared network. It is connected
4246  // to a subnet. Let's log some details about the subnet.
4247  std::string shared_network = ctx.subnet_->getSharedNetworkName();
4248  if (shared_network.empty()) {
4249  shared_network = "(none)";
4250  }
4252  .arg(ctx.query_->getLabel())
4253  .arg(ctx.subnet_->toText())
4254  .arg(ctx.subnet_->getID())
4255  .arg(shared_network);
4256  StatsMgr::instance().addValue("v4-allocation-fail-subnet",
4257  static_cast<int64_t>(1));
4258  StatsMgr::instance().addValue(
4259  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4260  "v4-allocation-fail-subnet"),
4261  static_cast<int64_t>(1));
4262  }
4263  if (total_attempts == 0) {
4264  // In this case, it seems that none of the pools in the subnets could
4265  // be used for that client, both in case the client is connected to
4266  // a shared network or to a single subnet. Apparently, the client was
4267  // rejected to use the pools because of the client classes' mismatch.
4269  .arg(ctx.query_->getLabel());
4270  StatsMgr::instance().addValue("v4-allocation-fail-no-pools",
4271  static_cast<int64_t>(1));
4272  StatsMgr::instance().addValue(
4273  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4274  "v4-allocation-fail-no-pools"),
4275  static_cast<int64_t>(1));
4276  } else {
4277  // This is an old log message which provides a number of attempts
4278  // made by the allocation engine to allocate a lease. The only case
4279  // when we don't want to log this message is when the number of
4280  // attempts is zero (condition above), because it would look silly.
4282  .arg(ctx.query_->getLabel())
4283  .arg(total_attempts);
4284  StatsMgr::instance().addValue("v4-allocation-fail",
4285  static_cast<int64_t>(1));
4286  StatsMgr::instance().addValue(
4287  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4288  "v4-allocation-fail"),
4289  static_cast<int64_t>(1));
4290  }
4291 
4292  if (!classes.empty()) {
4294  .arg(ctx.query_->getLabel())
4295  .arg(classes.toText());
4296  StatsMgr::instance().addValue("v4-allocation-fail-classes",
4297  static_cast<int64_t>(1));
4298  StatsMgr::instance().addValue(
4299  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4300  "v4-allocation-fail-classes"),
4301  static_cast<int64_t>(1));
4302  }
4303 
4304  return (new_lease);
4305 }
4306 
4307 bool
4308 AllocEngine::updateLease4Information(const Lease4Ptr& lease,
4309  AllocEngine::ClientContext4& ctx) const {
4310  bool changed = false;
4311  if (lease->subnet_id_ != ctx.subnet_->getID()) {
4312  changed = true;
4313  lease->subnet_id_ = ctx.subnet_->getID();
4314  }
4315  if ((!ctx.hwaddr_ && lease->hwaddr_) ||
4316  (ctx.hwaddr_ &&
4317  (!lease->hwaddr_ || (*ctx.hwaddr_ != *lease->hwaddr_)))) {
4318  changed = true;
4319  lease->hwaddr_ = ctx.hwaddr_;
4320  }
4321  if (ctx.subnet_->getMatchClientId() && ctx.clientid_) {
4322  if (!lease->client_id_ || (*ctx.clientid_ != *lease->client_id_)) {
4323  changed = true;
4324  lease->client_id_ = ctx.clientid_;
4325  }
4326  } else if (lease->client_id_) {
4327  changed = true;
4328  lease->client_id_ = ClientIdPtr();
4329  }
4330  lease->cltt_ = time(NULL);
4331 
4332  // Get the context appropriate valid lifetime.
4333  lease->valid_lft_ = getValidLft(ctx);
4334 
4335  // Reduced valid lifetime is a significant change.
4336  if (lease->valid_lft_ < lease->current_valid_lft_) {
4337  changed = true;
4338  }
4339 
4340  if ((lease->fqdn_fwd_ != ctx.fwd_dns_update_) ||
4341  (lease->fqdn_rev_ != ctx.rev_dns_update_) ||
4342  (lease->hostname_ != ctx.hostname_)) {
4343  changed = true;
4344  lease->fqdn_fwd_ = ctx.fwd_dns_update_;
4345  lease->fqdn_rev_ = ctx.rev_dns_update_;
4346  lease->hostname_ = ctx.hostname_;
4347  }
4348 
4349  // Add(update) the extended information on the lease.
4350  updateLease4ExtendedInfo(lease, ctx);
4351  if (lease->extended_info_action_ == Lease::ACTION_UPDATE) {
4352  changed = true;
4353  }
4354 
4355  return (changed);
4356 }
4357 
4358 void
4360  const AllocEngine::ClientContext4& ctx) const {
4361  // The extended info action is a transient value but be safe so reset it.
4362  lease->extended_info_action_ = Lease::ACTION_IGNORE;
4363 
4364  // If storage is not enabled then punt.
4365  if (!ctx.subnet_->getStoreExtendedInfo()) {
4366  return;
4367  }
4368 
4369  // Look for relay agent information option (option 82)
4370  OptionPtr rai = ctx.query_->getOption(DHO_DHCP_AGENT_OPTIONS);
4371  if (!rai) {
4372  // Pkt4 doesn't have it, so nothing to store (or update).
4373  return;
4374  }
4375 
4376  // Create a StringElement with the hex string for relay-agent-info.
4377  ElementPtr relay_agent(new StringElement(rai->toHexString()));
4378 
4379  // Now we wrap the agent info in a map. This allows for future expansion.
4380  ElementPtr extended_info = Element::createMap();
4381  extended_info->set("sub-options", relay_agent);
4382 
4383  OptionPtr remote_id = rai->getOption(RAI_OPTION_REMOTE_ID);
4384  if (remote_id) {
4385  std::vector<uint8_t> bytes = remote_id->toBinary(false);
4386  if (bytes.size() > 0) {
4387  extended_info->set("remote-id",
4389  }
4390  }
4391 
4392  OptionPtr relay_id = rai->getOption(RAI_OPTION_RELAY_ID);
4393  if (relay_id) {
4394  std::vector<uint8_t> bytes = relay_id->toBinary(false);
4395  if (bytes.size() > 0) {
4396  extended_info->set("relay-id",
4398  }
4399  }
4400 
4401  // Get a mutable copy of the lease's current user context.
4402  ConstElementPtr user_context = lease->getContext();
4403  ElementPtr mutable_user_context;
4404  if (user_context && (user_context->getType() == Element::map)) {
4405  mutable_user_context = copy(user_context, 0);
4406  } else {
4407  mutable_user_context = Element::createMap();
4408  }
4409 
4410  // Get a mutable copy of the ISC entry.
4411  ConstElementPtr isc = mutable_user_context->get("ISC");
4412  ElementPtr mutable_isc;
4413  if (isc && (isc->getType() == Element::map)) {
4414  mutable_isc = copy(isc, 0);
4415  } else {
4416  mutable_isc = Element::createMap();
4417  }
4418 
4419  // Add/replace the extended info entry.
4420  ConstElementPtr old_extended_info = mutable_isc->get("relay-agent-info");
4421  if (!old_extended_info || (*old_extended_info != *extended_info)) {
4422  lease->extended_info_action_ = Lease::ACTION_UPDATE;
4423  mutable_isc->set("relay-agent-info", extended_info);
4424  mutable_user_context->set("ISC", mutable_isc);
4425  }
4426 
4427  // Update the lease's user_context.
4428  lease->setContext(mutable_user_context);
4429 }
4430 
4431 void
4433  const AllocEngine::ClientContext6& ctx) const {
4434  // The extended info action is a transient value but be safe so reset it.
4435  lease->extended_info_action_ = Lease::ACTION_IGNORE;
4436 
4437  // If storage is not enabled then punt.
4438  if (!ctx.subnet_->getStoreExtendedInfo()) {
4439  return;
4440  }
4441 
4442  // If we do not have relay information, then punt.
4443  if (ctx.query_->relay_info_.empty()) {
4444  return;
4445  }
4446 
4447  // We need to convert the vector of RelayInfo instances in
4448  // into an Element hierarchy like this:
4449  // "relay-info": [
4450  // {
4451  // "hop": 123,
4452  // "link": "2001:db8::1",
4453  // "peer": "2001:db8::2",
4454  // "options": "0x..."
4455  // },..]
4456  //
4457  ElementPtr extended_info = Element::createList();
4458  for (auto relay : ctx.query_->relay_info_) {
4459  ElementPtr relay_elem = Element::createMap();
4460  relay_elem->set("hop", ElementPtr(new IntElement(relay.hop_count_)));
4461  relay_elem->set("link", ElementPtr(new StringElement(relay.linkaddr_.toText())));
4462  relay_elem->set("peer", ElementPtr(new StringElement(relay.peeraddr_.toText())));
4463 
4464  // If there are relay options, we'll pack them into a buffer and then
4465  // convert that into a hex string. If there are no options, we omit
4466  // then entry.
4467  if (!relay.options_.empty()) {
4468  OutputBuffer buf(128);
4469  LibDHCP::packOptions6(buf, relay.options_);
4470 
4471  if (buf.getLength() > 0) {
4472  const uint8_t* cp = static_cast<const uint8_t*>(buf.getData());
4473  std::vector<uint8_t> bytes;
4474  std::stringstream ss;
4475 
4476  bytes.assign(cp, cp + buf.getLength());
4477  ss << "0x" << encode::encodeHex(bytes);
4478  relay_elem->set("options", ElementPtr(new StringElement(ss.str())));
4479  }
4480 
4481  auto remote_id_it = relay.options_.find(D6O_REMOTE_ID);
4482  if (remote_id_it != relay.options_.end()) {
4483  OptionPtr remote_id = remote_id_it->second;
4484  if (remote_id) {
4485  std::vector<uint8_t> bytes = remote_id->toBinary(false);
4486  if (bytes.size() > 0) {
4487  relay_elem->set("remote-id",
4489  }
4490  }
4491  }
4492 
4493  auto relay_id_it = relay.options_.find(D6O_RELAY_ID);
4494  if (relay_id_it != relay.options_.end()) {
4495  OptionPtr relay_id = relay_id_it->second;
4496  if (relay_id) {
4497  std::vector<uint8_t> bytes = relay_id->toBinary(false);
4498  if (bytes.size() > 0) {
4499  relay_elem->set("relay-id",
4501  }
4502  }
4503  }
4504  }
4505 
4506  extended_info->add(relay_elem);
4507  }
4508 
4509  // Get a mutable copy of the lease's current user context.
4510  ConstElementPtr user_context = lease->getContext();
4511  ElementPtr mutable_user_context;
4512  if (user_context && (user_context->getType() == Element::map)) {
4513  mutable_user_context = copy(user_context, 0);
4514  } else {
4515  mutable_user_context = Element::createMap();
4516  }
4517 
4518  // Get a mutable copy of the ISC entry.
4519  ConstElementPtr isc = mutable_user_context->get("ISC");
4520  ElementPtr mutable_isc;
4521  if (isc && (isc->getType() == Element::map)) {
4522  mutable_isc = copy(isc, 0);
4523  } else {
4524  mutable_isc = Element::createMap();
4525  }
4526 
4527  // Add/replace the extended info entry.
4528  ConstElementPtr old_extended_info = mutable_isc->get("relay-info");
4529  if (!old_extended_info || (*old_extended_info != *extended_info)) {
4530  lease->extended_info_action_ = Lease::ACTION_UPDATE;
4531  mutable_isc->set("relay-info", extended_info);
4532  mutable_user_context->set("ISC", mutable_isc);
4533  }
4534 
4535  // Update the lease's user context.
4536  lease->setContext(mutable_user_context);
4537 }
4538 
4539 void
4540 AllocEngine::setLeaseReusable(const Lease4Ptr& lease,
4541  const ClientContext4& ctx) const {
4542  // Sanity.
4543  lease->reuseable_valid_lft_ = 0;
4544  const Subnet4Ptr& subnet = ctx.subnet_;
4545  if (!subnet) {
4546  return;
4547  }
4548  if (lease->state_ != Lease::STATE_DEFAULT) {
4549  return;
4550  }
4551 
4552  // Always reuse infinite lifetime leases.
4553  if (lease->valid_lft_ == Lease::INFINITY_LFT) {
4554  lease->reuseable_valid_lft_ = Lease::INFINITY_LFT;
4555  return;
4556  }
4557 
4558  // Refuse time not going forward.
4559  if (lease->cltt_ < lease->current_cltt_) {
4560  return;
4561  }
4562 
4563  uint32_t age = lease->cltt_ - lease->current_cltt_;
4564  // Already expired.
4565  if (age >= lease->current_valid_lft_) {
4566  return;
4567  }
4568 
4569  // Try cache max age.
4570  uint32_t max_age = 0;
4571  if (!subnet->getCacheMaxAge().unspecified()) {
4572  max_age = subnet->getCacheMaxAge().get();
4573  if ((max_age == 0) || (age > max_age)) {
4574  return;
4575  }
4576  }
4577 
4578  // Try cache threshold.
4579  if (!subnet->getCacheThreshold().unspecified()) {
4580  double threshold = subnet->getCacheThreshold().get();
4581  if ((threshold <= 0.) || (threshold > 1.)) {
4582  return;
4583  }
4584  max_age = lease->valid_lft_ * threshold;
4585  if (age > max_age) {
4586  return;
4587  }
4588  }
4589 
4590  // No cache.
4591  if (max_age == 0) {
4592  return;
4593  }
4594 
4595  // Seems to be reusable.
4596  lease->reuseable_valid_lft_ = lease->current_valid_lft_ - age;
4597 }
4598 
4599 void
4600 AllocEngine::setLeaseReusable(const Lease6Ptr& lease,
4601  uint32_t current_preferred_lft,
4602  const ClientContext6& ctx) const {
4603  // Sanity.
4604  lease->reuseable_valid_lft_ = 0;
4605  lease->reuseable_preferred_lft_ = 0;
4606  const Subnet6Ptr& subnet = ctx.subnet_;
4607  if (!subnet) {
4608  return;
4609  }
4610  if (lease->state_ != Lease::STATE_DEFAULT) {
4611  return;
4612  }
4613 
4614  // Refuse time not going forward.
4615  if (lease->cltt_ < lease->current_cltt_) {
4616  return;
4617  }
4618 
4619  uint32_t age = lease->cltt_ - lease->current_cltt_;
4620  // Already expired.
4621  if (age >= lease->current_valid_lft_) {
4622  return;
4623  }
4624 
4625  // Try cache max age.
4626  uint32_t max_age = 0;
4627  if (!subnet->getCacheMaxAge().unspecified()) {
4628  max_age = subnet->getCacheMaxAge().get();
4629  if ((max_age == 0) || (age > max_age)) {
4630  return;
4631  }
4632  }
4633 
4634  // Try cache threshold.
4635  if (!subnet->getCacheThreshold().unspecified()) {
4636  double threshold = subnet->getCacheThreshold().get();
4637  if ((threshold <= 0.) || (threshold > 1.)) {
4638  return;
4639  }
4640  max_age = lease->valid_lft_ * threshold;
4641  if (age > max_age) {
4642  return;
4643  }
4644  }
4645 
4646  // No cache.
4647  if (max_age == 0) {
4648  return;
4649  }
4650 
4651  // Seems to be reusable.
4652  if ((current_preferred_lft == Lease::INFINITY_LFT) ||
4653  (current_preferred_lft == 0)) {
4654  // Keep these values.
4655  lease->reuseable_preferred_lft_ = current_preferred_lft;
4656  } else if (current_preferred_lft > age) {
4657  lease->reuseable_preferred_lft_ = current_preferred_lft - age;
4658  } else {
4659  // Can be a misconfiguration so stay safe...
4660  return;
4661  }
4662  if (lease->current_valid_lft_ == Lease::INFINITY_LFT) {
4663  lease->reuseable_valid_lft_ = Lease::INFINITY_LFT;
4664  } else {
4665  lease->reuseable_valid_lft_ = lease->current_valid_lft_ - age;
4666  }
4667 }
4668 
4669 } // namespace dhcp
4670 } // namespace isc
#define LOG_WARN(LOGGER, MESSAGE)
Macro to conveniently test warn output and log it.
Definition: macros.h:26
const isc::log::MessageID DHCPSRV_HOOK_LEASE6_SELECT_SKIP
static HostMgr & instance()
Returns a sole instance of the HostMgr.
Definition: host_mgr.cc:105
std::map< SubnetID, ConstHostPtr > hosts_
Holds a map of hosts belonging to the client within different subnets.
const isc::log::MessageID ALLOC_ENGINE_V6_LEASES_RECLAMATION_COMPLETE
bool fake_allocation_
Indicates if this is a real or fake allocation.
boost::shared_ptr< DUID > DuidPtr
Definition: duid.h:20
const isc::log::MessageID ALLOC_ENGINE_V4_REQUEST_EXTEND_LEASE
void unspecified(bool unspecified)
Modifies the flag that indicates whether the value is specified or unspecified.
Definition: optional.h:136
virtual void updateLease4(const Lease4Ptr &lease4)=0
Updates IPv4 lease.
const isc::log::MessageID ALLOC_ENGINE_V6_RECLAIMED_LEASES_DELETE_COMPLETE
const int ALLOC_ENGINE_DBG_TRACE
Logging levels for the AllocEngine.
static bool subnetsIncludeMatchClientId(const Subnet4Ptr &first_subnet, const ClientClasses &client_classes)
Checks if the shared network includes a subnet with the match client ID flag set to true...
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:397
HWAddrPtr hwaddr_
Hardware/MAC address (if available, may be NULL)
Definition: alloc_engine.h:252
Defines a single hint.
Definition: alloc_engine.h:83
static const uint32_t STATE_EXPIRED_RECLAIMED
Expired and reclaimed lease.
Definition: lease.h:75
Structure that holds a lease for IPv4 address.
Definition: lease.h:305
Lease6Collection changed_leases_
A pointer to any leases that have changed FQDN information.
Definition: alloc_engine.h:323
const isc::log::MessageID ALLOC_ENGINE_V4_REQUEST_IN_USE
Abstract Lease Manager.
Definition: lease_mgr.h:225
HintContainer hints_
Client&#39;s hints.
Definition: alloc_engine.h:306
#define LOG_INFO(LOGGER, MESSAGE)
Macro to conveniently test info output and log it.
Definition: macros.h:20
void updateLease4ExtendedInfo(const Lease4Ptr &lease, const ClientContext4 &ctx) const
Stores additional client query parameters on a V4 lease.
static void packOptions6(isc::util::OutputBuffer &buf, const isc::dhcp::OptionCollection &options)
Stores DHCPv6 options in a buffer.
Definition: libdhcp++.cc:1070
static void findReservation(ClientContext6 &ctx)
Attempts to find appropriate host reservation.
boost::shared_ptr< HWAddr > HWAddrPtr
Shared pointer to a hardware address structure.
Definition: hwaddr.h:154
isc::util::ReadWriteMutex rw_mutex_
The read-write mutex.
boost::shared_ptr< Pool6 > Pool6Ptr
a pointer an IPv6 Pool
Definition: pool.h:298
const isc::log::MessageID ALLOC_ENGINE_V4_LEASES_RECLAMATION_START
const isc::log::MessageID ALLOC_ENGINE_V6_ALLOC_ERROR
virtual ConstHostCollection getAll6(const SubnetID &subnet_id) const
Return all hosts in a DHCPv6 subnet.
Definition: host_mgr.cc:140
bool getDisableSingleQuery() const
Returns the disable single query flag.
Definition: host_mgr.h:596
const isc::log::MessageID ALLOC_ENGINE_V6_LEASES_RECLAMATION_TIMEOUT
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:754
Lease6Collection old_leases_
A pointer to any old leases that the client had before update but are no longer valid after the updat...
Definition: alloc_engine.h:315
const isc::log::MessageID ALLOC_ENGINE_V6_RENEW_REMOVE_RESERVED
const isc::log::MessageID ALLOC_ENGINE_V4_LEASES_RECLAMATION_SLOW
const isc::log::MessageID DHCPSRV_HOOK_LEASE4_RENEW_SKIP
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 isc::log::MessageID ALLOC_ENGINE_V6_ALLOC_FAIL
Write mutex RAII handler.
const isc::log::MessageID ALLOC_ENGINE_V4_LEASE_RECLAMATION_FAILED
const isc::log::MessageID ALLOC_ENGINE_V6_HR_ADDR_GRANTED
const int DHCPSRV_DBG_HOOKS
Definition: dhcpsrv_log.h:46
const isc::log::MessageID ALLOC_ENGINE_V6_ALLOC_UNRESERVED
const isc::log::MessageID ALLOC_ENGINE_V6_ALLOC_LEASES_HR
std::vector< Lease4Ptr > Lease4Collection
A collection of IPv4 leases.
Definition: lease.h:508
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:114
boost::shared_ptr< Option > OptionPtr
Definition: option.h:36
const isc::log::MessageID ALLOC_ENGINE_V4_NO_MORE_EXPIRED_LEASES
boost::shared_ptr< Subnet4 > Subnet4Ptr
A pointer to a Subnet4 object.
Definition: subnet.h:446
static void getLifetimes6(ClientContext6 &ctx, uint32_t &preferred, uint32_t &valid)
Determines the preferred and valid v6 lease lifetimes.
const isc::log::MessageID ALLOC_ENGINE_V4_DISCOVER_HR
bool early_global_reservations_lookup_
Indicates if early global reservation is enabled.
Resource race avoidance RAII handler for DHCPv4.
#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:49
boost::shared_ptr< Element > ElementPtr
Definition: data.h:24
const int ALLOC_ENGINE_DBG_TRACE_DETAIL
Record detailed traces.
SrvConfigPtr getCurrentCfg()
Returns a pointer to the current configuration.
Definition: cfgmgr.cc:161
virtual uint64_t deleteExpiredReclaimedLeases4(const uint32_t secs)=0
Deletes all expired and reclaimed DHCPv4 leases.
bool fwd_dns_update_
A boolean value which indicates that server takes responsibility for the forward DNS Update for this ...
Definition: alloc_engine.h:268
DuidPtr duid_
Client identifier.
Definition: alloc_engine.h:249
long getTotalMilliseconds() const
Retrieves the total measured duration in milliseconds.
Definition: stopwatch.cc:60
Lease4Ptr allocateLease4(ClientContext4 &ctx)
Returns IPv4 lease.
bool isAllocated(const asiolink::IOAddress &prefix, const uint8_t prefix_len=128) const
Checks if specified address or prefix was allocated.
A configuration holder for IPv4 subnet.
Definition: subnet.h:453
Forward declaration to OptionInt.
const isc::log::MessageID ALLOC_ENGINE_V4_LEASES_RECLAMATION_TIMEOUT
const isc::log::MessageID ALLOC_ENGINE_V4_REQUEST_ADDRESS_RESERVED
IPv6 reservation for a host.
Definition: host.h:161
const isc::log::MessageID ALLOC_ENGINE_V6_EXTEND_ERROR
ignore extended info,
Definition: lease.h:189
static ElementPtr createMap(const Position &pos=ZERO_POSITION())
Creates an empty MapElement type ElementPtr.
Definition: data.cc:291
const_iterator cbegin() const
Iterators to the first element.
Definition: classify.h:152
boost::shared_ptr< OptionUint32 > OptionUint32Ptr
Definition: option_int.h:35
DdnsParamsPtr getDdnsParams()
Returns the set of DDNS behavioral parameters based on the selected subnet.
hooks::CalloutHandlePtr callout_handle_
Callout handle associated with the client&#39;s message.
RAII object enabling copying options retrieved from the packet.
Definition: pkt.h:40
static ElementPtr createList(const Position &pos=ZERO_POSITION())
Creates an empty ListElement type ElementPtr.
Definition: data.cc:286
const isc::log::MessageID ALLOC_ENGINE_V4_ALLOC_FAIL_SHARED_NETWORK
virtual const char * what() const
Returns a C-style character string of the cause of the exception.
const isc::log::MessageID ALLOC_ENGINE_V6_ALLOC_LEASES_NO_HR
const isc::log::MessageID ALLOC_ENGINE_V4_OFFER_NEW_LEASE
IdentifierList host_identifiers_
A list holding host identifiers extracted from a message received by the server.
const isc::log::MessageID DHCPSRV_HOOK_LEASE6_RECOVER_SKIP
virtual void getExpiredLeases6(Lease6Collection &expired_leases, const size_t max_leases) const =0
Returns a collection of expired DHCPv6 leases.
Statistics Manager class.
boost::shared_ptr< DdnsParams > DdnsParamsPtr
Defines a pointer for DdnsParams instances.
Definition: srv_config.h:172
asiolink::IOAddress requested_address_
An address that the client desires.
Resource race avoidance RAII handler.
void deleteExpiredReclaimedLeases4(const uint32_t secs)
Deletes reclaimed leases expired more than specified amount of time ago.
const isc::log::MessageID ALLOC_ENGINE_V6_HR_PREFIX_GRANTED
void addNewResource(const asiolink::IOAddress &prefix, const uint8_t prefix_len=128)
Convenience method adding new prefix or address.
const isc::log::MessageID ALLOC_ENGINE_V6_ALLOC_FAIL_SHARED_NETWORK
bool early_global_reservations_lookup_
Indicates if early global reservation is enabled.
Definition: alloc_engine.h:238
bool tryLock(Lease::Type type, const asiolink::IOAddress &addr)
Tries to acquires a resource.
ResourceContainer new_resources_
Holds addresses and prefixes allocated for this IA.
Definition: alloc_engine.h:328
#define isc_throw(type, stream)
A shortcut macro to insert known values into exception arguments.
const isc::log::MessageID ALLOC_ENGINE_V6_LEASE_RECLAMATION_FAILED
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.
ConstHostPtr globalHost() const
Returns global host reservation if there is one.
boost::shared_ptr< Pkt6 > Pkt6Ptr
A pointer to Pkt6 packet.
Definition: pkt6.h:28
ClientClassContainer::const_iterator const_iterator
Type of iterators.
Definition: classify.h:112
Subnet6Ptr subnet_
Subnet selected for the client by the server.
Definition: alloc_engine.h:241
ResourceContainer allocated_resources_
Holds addresses and prefixes allocated for all IAs.
Definition: alloc_engine.h:285
Definition: edns.h:19
std::pair< IPv6ResrvIterator, IPv6ResrvIterator > IPv6ResrvRange
Definition: host.h:243
Pool information for IPv6 addresses and prefixes.
Definition: pool.h:307
const int ALLOC_ENGINE_DBG_TRACE_DETAIL_DATA
Records detailed results of various operations.
Lease4Ptr conflicting_lease_
A pointer to the object representing a lease in conflict.
const isc::log::MessageID DHCPSRV_HOOK_LEASE4_RECOVER_SKIP
ElementPtr copy(ConstElementPtr from, int level)
Copy the data up to a nesting level.
Definition: data.cc:1360
boost::shared_ptr< Option6IAPrefix > Option6IAPrefixPtr
Pointer to the Option6IAPrefix object.
boost::shared_ptr< Lease4 > Lease4Ptr
Pointer to a Lease4 structure.
Definition: lease.h:294
const isc::log::MessageID ALLOC_ENGINE_V4_ALLOC_FAIL
const isc::log::MessageID ALLOC_ENGINE_V6_HINT_RESERVED
std::vector< ConstHostPtr > ConstHostCollection
Collection of the const Host objects.
Definition: host.h:807
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
const isc::log::MessageID ALLOC_ENGINE_V6_EXTEND_LEASE_DATA
std::map< SubnetID, ConstHostPtr > hosts_
Holds a map of hosts belonging to the client within different subnets.
Definition: alloc_engine.h:263
const isc::log::MessageID ALLOC_ENGINE_V6_REVOKED_SHARED_PREFIX_LEASE
const isc::log::MessageID ALLOC_ENGINE_V4_REQUEST_OUT_OF_POOL
std::vector< IAContext > ias_
Container holding IA specific contexts.
Definition: alloc_engine.h:380
Context information for the DHCPv6 leases allocation.
Definition: alloc_engine.h:218
const isc::log::MessageID ALLOC_ENGINE_V4_REUSE_EXPIRED_LEASE_DATA
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:246
boost::shared_ptr< ClientClassDictionary > ClientClassDictionaryPtr
Defines a pointer to a ClientClassDictionary.
Notes: IntElement type is changed to int64_t.
Definition: data.h:590
Lease6Collection renewLeases6(ClientContext6 &ctx)
Renews existing DHCPv6 leases for a given IA.
Wrapper class around callout handle which automatically resets handle&#39;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.
IPv4 lease.
Definition: lease.h:50
T get(T hint) const
Returns value with a hint.
Definition: triplet.h:99
bool unknown_requested_addr_
True when the address DHCPREQUEST&#39;ed by client is not within a dynamic pool the server knows about...
Pkt4Ptr query_
A pointer to the client&#39;s message.
const isc::log::MessageID ALLOC_ENGINE_V4_LEASE_RECLAIM
const isc::log::MessageID ALLOC_ENGINE_V6_LEASES_RECLAMATION_START
Option6IAPtr ia_rsp_
A pointer to the IA_NA/IA_PD option to be sent in response.
Definition: alloc_engine.h:332
CalloutNextStep
Specifies allowed next steps.
boost::shared_ptr< const Element > ConstElementPtr
Definition: data.h:27
const void * getData() const
Return a pointer to the head of the data stored in the buffer.
Definition: buffer.h:401
boost::shared_ptr< const Host > ConstHostPtr
Const pointer to the Host object.
Definition: host.h:804
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:410
Structure that holds a lease for IPv6 address and/or prefix.
Definition: lease.h:524
const isc::log::MessageID ALLOC_ENGINE_V6_ALLOC_FAIL_CLASSES
void addHint(const asiolink::IOAddress &prefix, const uint8_t prefix_len=128, const uint32_t preferred=0, const uint32_t valid=0)
Convenience method adding new hint.
const isc::log::MessageID ALLOC_ENGINE_V6_ALLOC_FAIL_NO_POOLS
const isc::log::MessageID ALLOC_ENGINE_V6_LEASES_RECLAMATION_SLOW
std::vector< Lease6Ptr > Lease6Collection
A collection of IPv6 leases.
Definition: lease.h:671
virtual Lease6Ptr getLease6(Lease::Type type, const isc::asiolink::IOAddress &addr) const =0
Returns existing IPv6 lease for a given IPv6 address.
const isc::log::MessageID ALLOC_ENGINE_V6_REUSE_EXPIRED_LEASE_DATA
boost::shared_ptr< ClientId > ClientIdPtr
Shared pointer to a Client ID.
Definition: duid.h:103
Type
Type of the reservation.
Definition: host.h:167
virtual void getExpiredLeases4(Lease4Collection &expired_leases, const size_t max_leases) const =0
Returns a collection of expired DHCPv4 leases.
const isc::log::MessageID ALLOC_ENGINE_V6_RECLAIMED_LEASES_DELETE_FAILED
boost::shared_ptr< SharedNetwork6 > SharedNetwork6Ptr
Pointer to SharedNetwork6 object.
Convenience container for conveying DDNS behavioral parameters It is intended to be created per Packe...
Definition: srv_config.h:47
bool empty() const
Check if classes is empty.
Definition: classify.h:138
The OutputBuffer class is a buffer abstraction for manipulating mutable data.
Definition: buffer.h:294
void addHostIdentifier(const Host::IdentifierType &id_type, const std::vector< uint8_t > &identifier)
Convenience function adding host identifier into host_identifiers_ list.
boost::shared_ptr< ClientClassDef > ClientClassDefPtr
a pointer to an ClientClassDef
the lease contains non-temporary IPv6 address
Definition: lease.h:47
boost::shared_ptr< SharedNetwork4 > SharedNetwork4Ptr
Pointer to SharedNetwork4 object.
const isc::log::MessageID ALLOC_ENGINE_V6_ALLOC_FAIL_SUBNET
size_t getLength() const
Return the length of data written in the buffer.
Definition: buffer.h:403
const isc::log::MessageID ALLOC_ENGINE_V4_OFFER_EXISTING_LEASE
void addValue(const std::string &name, const int64_t value)
Records incremental integer observation.
ConstHostPtr currentHost() const
Returns host for currently selected subnet.
const isc::log::MessageID ALLOC_ENGINE_V6_RENEW_HR
bool fake_allocation_
Indicates if this is a real or fake allocation.
Definition: alloc_engine.h:233
const isc::log::MessageID ALLOC_ENGINE_V4_ALLOC_FAIL_CLASSES
This is a base class for exceptions thrown from the DNS library module.
Defines the logger used by the top-level component of kea-lfc.
const isc::log::MessageID ALLOC_ENGINE_V6_EXPIRED_HINT_RESERVED
bool isNewResource(const asiolink::IOAddress &prefix, const uint8_t prefix_len=128) const
Checks if specified address or prefix was new.
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:696
Lease6Collection new_leases_
A collection of newly allocated leases.
Definition: alloc_engine.h:288
string encodeHex(const vector< uint8_t > &binary)
Encode binary data in the base16 (&#39;hex&#39;) format.
Definition: base_n.cc:483
ClientIdPtr clientid_
Client identifier from the DHCP message.
uint32_t iaid_
The IAID field from IA_NA or IA_PD that is being processed.
Definition: alloc_engine.h:297
const isc::log::MessageID ALLOC_ENGINE_V6_ALLOC_NO_V6_HR
update extended info tables.
Definition: lease.h:191
const isc::log::MessageID ALLOC_ENGINE_V6_LEASE_RECLAIM
Lease::Type type_
Lease type (IA or PD)
Definition: alloc_engine.h:300
const isc::log::MessageID ALLOC_ENGINE_V4_RECLAIMED_LEASES_DELETE_COMPLETE
Pkt6Ptr query_
A pointer to the client&#39;s message.
Definition: alloc_engine.h:226
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:368
Lease6Collection allocateLeases6(ClientContext6 &ctx)
Allocates IPv6 leases for a given IA container.
boost::shared_ptr< CalloutHandle > CalloutHandlePtr
A shared pointer to a CalloutHandle object.
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:498
const isc::log::MessageID ALLOC_ENGINE_V4_RECLAIMED_LEASES_DELETE
const isc::log::MessageID ALLOC_ENGINE_V4_ALLOC_FAIL_NO_POOLS
CtrlAgentHooks Hooks
Lease4Ptr new_lease_
A pointer to a newly allocated lease.
static const uint32_t INFINITY_LFT
Infinity (means static, i.e. never expire)
Definition: lease.h:34
const isc::log::MessageID ALLOC_ENGINE_V4_LEASES_RECLAMATION_COMPLETE
static ElementPtr create(const Position &pos=ZERO_POSITION())
Definition: data.cc:241
const isc::log::MessageID ALLOC_ENGINE_V6_EXTEND_NEW_LEASE_DATA
a common structure for IPv4 and IPv6 leases
Definition: lease.h:31
const isc::log::MessageID ALLOC_ENGINE_V6_EXTEND_ALLOC_UNRESERVED
Type
Type of lease or pool.
Definition: lease.h:46
const isc::log::MessageID DHCPSRV_HOOK_LEASE4_SELECT_SKIP
const isc::log::MessageID ALLOC_ENGINE_V4_REQUEST_REMOVE_LEASE
bool rev_dns_update_
A boolean value which indicates that server takes responsibility for the reverse DNS Update for this ...
Definition: alloc_engine.h:273
bool fwd_dns_update_
Perform forward DNS update.
const isc::log::MessageID ALLOC_ENGINE_V4_ALLOC_FAIL_SUBNET
isc::log::Logger alloc_engine_logger("alloc-engine")
Logger for the AllocEngine.
const isc::log::MessageID DHCPSRV_HOOK_LEASE6_EXTEND_SKIP
virtual ConstHostCollection getAll4(const SubnetID &subnet_id) const
Return all hosts in a DHCPv4 subnet.
Definition: host_mgr.cc:129
A generic exception that is thrown if a function is called in a prohibited way.
static uint32_t getValidLft(const ClientContext4 &ctx)
Returns the valid lifetime based on the v4 context.
const isc::log::MessageID ALLOC_ENGINE_V6_REVOKED_SHARED_ADDR_LEASE
const_iterator cend() const
Iterators to the past the end element.
Definition: classify.h:165
const isc::log::MessageID ALLOC_ENGINE_V4_OFFER_REQUESTED_LEASE
#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.
const isc::log::MessageID ALLOC_ENGINE_V6_RECLAIMED_LEASES_DELETE
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:420
static const uint32_t STATE_DEFAULT
A lease in the default state.
Definition: lease.h:69
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.
const isc::log::MessageID ALLOC_ENGINE_V4_DECLINED_RECOVERED
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:66
virtual bool deleteLease(const Lease4Ptr &lease)=0
Deletes an IPv4 lease.
const isc::log::MessageID ALLOC_ENGINE_LEASE_RECLAIMED
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:72
const isc::log::MessageID ALLOC_ENGINE_V4_REQUEST_PICK_ADDRESS
boost::shared_ptr< Subnet6 > Subnet6Ptr
A pointer to a Subnet6 object.
Definition: subnet.h:604
const isc::log::MessageID ALLOC_ENGINE_V4_ALLOC_ERROR
const isc::log::MessageID ALLOC_ENGINE_V4_RECLAIMED_LEASES_DELETE_FAILED
const isc::log::MessageID ALLOC_ENGINE_V6_REVOKED_PREFIX_LEASE
T getValue() const
Return option value.
Definition: option_int.h:191
bool hasGlobalReservation(const IPv6Resrv &resv) const
Determines if a global reservation exists.
hooks::CalloutHandlePtr callout_handle_
Callout handle associated with the client&#39;s message.
Definition: alloc_engine.h:282
std::pair< IPv6Resrv::Type, IPv6Resrv > IPv6ResrvTuple
Definition: host.h:242
HWAddrPtr hwaddr_
HW address from the DHCP message.
static LeaseMgr & instance()
Return current lease manager.
virtual Lease6Collection getLeases6(Lease::Type type, const DUID &duid, uint32_t iaid) const =0
Returns existing IPv6 leases for a given DUID+IA combination.
Context information for the DHCPv4 lease allocation.
const isc::log::MessageID ALLOC_ENGINE_V6_REVOKED_ADDR_LEASE
const isc::log::MessageID ALLOC_ENGINE_V4_REQUEST_INVALID
boost::shared_ptr< Lease6 > Lease6Ptr
Pointer to a Lease6 structure.
Definition: lease.h:513
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
delete reference to the lease
Definition: lease.h:190
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:191
const isc::log::MessageID ALLOC_ENGINE_V4_REQUEST_ALLOC_REQUESTED
Container for storing client class names.
Definition: classify.h:108
boost::shared_ptr< Option6IAAddr > Option6IAAddrPtr
A pointer to the isc::dhcp::Option6IAAddr object.
const isc::log::MessageID ALLOC_ENGINE_V6_ALLOC_HR_LEASE_EXISTS
bool rev_dns_update_
Perform reverse DNS update.
const isc::log::MessageID ALLOC_ENGINE_V4_REQUEST_USE_HR
const isc::log::MessageID ALLOC_ENGINE_V6_EXTEND_LEASE
virtual void updateLease6(const Lease6Ptr &lease6)=0
Updates IPv6 lease.
const isc::log::MessageID ALLOC_ENGINE_V6_NO_MORE_EXPIRED_LEASES
DdnsParamsPtr getDdnsParams()
Returns the set of DDNS behavioral parameters based on the selected subnet.
const isc::log::MessageID ALLOC_ENGINE_V6_ALLOC_NO_LEASES_HR
void updateLease6ExtendedInfo(const Lease6Ptr &lease, const ClientContext6 &ctx) const
Stores additional client query parameters on a V6 lease.
uint32_t SubnetID
Defines unique IPv4 or IPv6 subnet identifier.
Definition: subnet_id.h:25
IdentifierList host_identifiers_
A list holding host identifiers extracted from a message received by the server.
Definition: alloc_engine.h:256
const isc::log::MessageID ALLOC_ENGINE_V4_DISCOVER_ADDRESS_CONFLICT
ClientContext6()
Default constructor.
bool tryLock4(const asiolink::IOAddress &addr)
Tries to acquires a resource.
const isc::log::MessageID ALLOC_ENGINE_V6_DECLINED_RECOVERED