Kea  2.3.6-git
alloc_engine.cc
Go to the documentation of this file.
1 // Copyright (C) 2012-2023 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  uint8_t hint_prefix_length = 128;
632  if (!ctx.currentIA().hints_.empty()) {
634  hint = ctx.currentIA().hints_[0].getAddress();
635  hint_prefix_length = ctx.currentIA().hints_[0].getPrefixLength();
636  }
637 
638  Subnet6Ptr original_subnet = ctx.subnet_;
639 
640  Subnet6Ptr subnet = original_subnet;
641 
642  SharedNetwork6Ptr network;
643 
644  uint64_t total_attempts = 0;
645 
646  // The following counter tracks the number of subnets with matching client
647  // classes from which the allocation engine attempted to assign leases.
648  uint64_t subnets_with_unavail_leases = 0;
649  // The following counter tracks the number of subnets in which there were
650  // no matching pools for the client.
651  uint64_t subnets_with_unavail_pools = 0;
652 
653  CalloutHandle::CalloutNextStep callout_status = CalloutHandle::NEXT_STEP_CONTINUE;
654 
655  // In the case of PDs, the allocation engine will try to match pools with
656  // the delegated prefix length matching the one provided in the hint. If the
657  // hint does not provide a preferred delegated prefix length (value is 0),
658  // the allocation engine will match any pool (any greater delegated prefix
659  // length pool). The match type for the pools is ignored for non PDs.
660  Lease6Ptr hint_lease;
661  bool search_hint_lease = true;
663  if (ctx.currentIA().type_ == Lease::TYPE_PD) {
664  // If the hint has a value of 128, the code might be broken as the hint
665  // was added with the default value 128 for prefix_len by the addHint
666  // function instead of 0. However 128 is not a valid value anyway so it
667  // is reset to 0 (use any delegated prefix length available).
668  if (hint_prefix_length == 128) {
669  hint_prefix_length = 0;
670  }
671  if (!hint_prefix_length) {
672  prefix_length_match = Allocator::PREFIX_LEN_HIGHER;
673  }
674  }
675 
676  // Try the first allocation using PREFIX_LEN_EQUAL (or in case of PDs,
677  // PREFIX_LEN_HIGHER when there is no valid delegated prefix length in the
678  // provided hint)
679  Lease6Ptr lease = allocateBestMatch(ctx, hint_lease, search_hint_lease,
680  hint, hint_prefix_length, subnet,
681  network, total_attempts,
682  subnets_with_unavail_leases,
683  subnets_with_unavail_pools,
684  callout_status, prefix_length_match);
685 
686  // Try the second allocation using PREFIX_LEN_LOWER only for PDs if the
687  // first allocation using PREFIX_LEN_EQUAL failed (there was a specific
688  // delegated prefix length hint requested).
689  if (!lease && ctx.currentIA().type_ == Lease::TYPE_PD &&
690  prefix_length_match == Allocator::PREFIX_LEN_EQUAL) {
691  prefix_length_match = Allocator::PREFIX_LEN_LOWER;
692  lease = allocateBestMatch(ctx, hint_lease, search_hint_lease, hint,
693  hint_prefix_length, subnet, network,
694  total_attempts, subnets_with_unavail_leases,
695  subnets_with_unavail_pools, callout_status,
696  prefix_length_match);
697  }
698 
699  // Try the third allocation using PREFIX_LEN_HIGHER only for PDs if the
700  // second allocation using PREFIX_LEN_LOWER failed (there was a specific
701  // delegated prefix length hint requested).
702  if (!lease && ctx.currentIA().type_ == Lease::TYPE_PD &&
703  prefix_length_match == Allocator::PREFIX_LEN_LOWER) {
704  prefix_length_match = Allocator::PREFIX_LEN_HIGHER;
705  lease = allocateBestMatch(ctx, hint_lease, search_hint_lease, hint,
706  hint_prefix_length, subnet, network,
707  total_attempts, subnets_with_unavail_leases,
708  subnets_with_unavail_pools, callout_status,
709  prefix_length_match);
710  }
711 
712  if (lease) {
713  leases.push_back(lease);
714  return (leases);
715  }
716 
717  auto const& classes = ctx.query_->getClasses();
718 
719  if (network) {
720  // The client is in the shared network. Let's log the high level message
721  // indicating which shared network the client belongs to.
723  .arg(ctx.query_->getLabel())
724  .arg(network->getName())
725  .arg(subnets_with_unavail_leases)
726  .arg(subnets_with_unavail_pools);
727  StatsMgr::instance().addValue("v6-allocation-fail-shared-network",
728  static_cast<int64_t>(1));
729  StatsMgr::instance().addValue(
730  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
731  "v6-allocation-fail-shared-network"),
732  static_cast<int64_t>(1));
733  } else {
734  // The client is not connected to a shared network. It is connected
735  // to a subnet. Let's log the ID of that subnet.
736  std::string shared_network = ctx.subnet_->getSharedNetworkName();
737  if (shared_network.empty()) {
738  shared_network = "(none)";
739  }
741  .arg(ctx.query_->getLabel())
742  .arg(ctx.subnet_->toText())
743  .arg(ctx.subnet_->getID())
744  .arg(shared_network);
745  StatsMgr::instance().addValue("v6-allocation-fail-subnet",
746  static_cast<int64_t>(1));
747  StatsMgr::instance().addValue(
748  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
749  "v6-allocation-fail-subnet"),
750  static_cast<int64_t>(1));
751  }
752  if (total_attempts == 0) {
753  // In this case, it seems that none of the pools in the subnets could
754  // be used for that client, both in case the client is connected to
755  // a shared network or to a single subnet. Apparently, the client was
756  // rejected to use the pools because of the client classes' mismatch.
758  .arg(ctx.query_->getLabel());
759  StatsMgr::instance().addValue("v6-allocation-fail-no-pools",
760  static_cast<int64_t>(1));
761  StatsMgr::instance().addValue(
762  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
763  "v6-allocation-fail-no-pools"),
764  static_cast<int64_t>(1));
765  } else {
766  // This is an old log message which provides a number of attempts
767  // made by the allocation engine to allocate a lease. The only case
768  // when we don't want to log this message is when the number of
769  // attempts is zero (condition above), because it would look silly.
771  .arg(ctx.query_->getLabel())
772  .arg(total_attempts);
773  StatsMgr::instance().addValue("v6-allocation-fail",
774  static_cast<int64_t>(1));
775  StatsMgr::instance().addValue(
776  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
777  "v6-allocation-fail"),
778  static_cast<int64_t>(1));
779  }
780 
781  if (!classes.empty()) {
783  .arg(ctx.query_->getLabel())
784  .arg(classes.toText());
785  StatsMgr::instance().addValue("v6-allocation-fail-classes",
786  static_cast<int64_t>(1));
787  StatsMgr::instance().addValue(
788  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
789  "v6-allocation-fail-classes"),
790  static_cast<int64_t>(1));
791  }
792 
793  // We failed to allocate anything. Let's return empty collection.
794  return (Lease6Collection());
795 }
796 
797 Lease6Ptr
798 AllocEngine::allocateBestMatch(ClientContext6& ctx,
799  Lease6Ptr& hint_lease,
800  bool& search_hint_lease,
801  const isc::asiolink::IOAddress& hint,
802  uint8_t hint_prefix_length,
803  Subnet6Ptr original_subnet,
804  SharedNetwork6Ptr& network,
805  uint64_t& total_attempts,
806  uint64_t& subnets_with_unavail_leases,
807  uint64_t& subnets_with_unavail_pools,
809  Allocator::PrefixLenMatchType prefix_length_match) {
810  auto const& classes = ctx.query_->getClasses();
811  Pool6Ptr pool;
812  Subnet6Ptr subnet = original_subnet;
813 
814  Lease6Ptr usable_hint_lease;
815  if (!search_hint_lease) {
816  usable_hint_lease = hint_lease;
817  }
818  for (; subnet; subnet = subnet->getNextSubnet(original_subnet)) {
819  if (!subnet->clientSupported(classes)) {
820  continue;
821  }
822 
823  ctx.subnet_ = subnet;
824 
825  // check if the hint is in pool and is available
826  // This is equivalent of subnet->inPool(hint), but returns the pool
827  pool = boost::dynamic_pointer_cast<Pool6>
828  (subnet->getPool(ctx.currentIA().type_, classes, hint));
829 
830  // check if the pool is allowed
831  if (!pool || !pool->clientSupported(classes)) {
832  continue;
833  }
834 
835  if (ctx.currentIA().type_ == Lease::TYPE_PD &&
836  !Allocator::isValidPrefixPool(prefix_length_match, pool,
837  hint_prefix_length)) {
838  continue;
839  }
840 
841  bool in_subnet = subnet->getReservationsInSubnet();
842 
844  if (search_hint_lease) {
845  search_hint_lease = false;
846  hint_lease = LeaseMgrFactory::instance().getLease6(ctx.currentIA().type_, hint);
847  usable_hint_lease = hint_lease;
848  }
849  if (!usable_hint_lease) {
850 
851  // In-pool reservations: Check if this address is reserved for someone
852  // else. There is no need to check for whom it is reserved, because if
853  // it has been reserved for us we would have already allocated a lease.
854 
855  ConstHostCollection hosts;
856  // When out-of-pool flag is true the server may assume that all host
857  // reservations are for addresses that do not belong to the dynamic
858  // pool. Therefore, it can skip the reservation checks when dealing
859  // with in-pool addresses.
860  if (in_subnet &&
861  (!subnet->getReservationsOutOfPool() ||
862  !subnet->inPool(ctx.currentIA().type_, hint))) {
863  hosts = getIPv6Resrv(subnet->getID(), hint);
864  }
865 
866  if (hosts.empty()) {
867 
868  // If the in-pool reservations are disabled, or there is no
869  // reservation for a given hint, we're good to go.
870 
871  // The hint is valid and not currently used, let's create a
872  // lease for it
873  Lease6Ptr new_lease = createLease6(ctx, hint, pool->getLength(), callout_status);
874 
875  // It can happen that the lease allocation failed (we could
876  // have lost the race condition. That means that the hint is
877  // no longer usable and we need to continue the regular
878  // allocation path.
879  if (new_lease) {
881  return (new_lease);
882  }
883  } else {
886  .arg(ctx.query_->getLabel())
887  .arg(hint.toText());
888  }
889 
890  } else if (usable_hint_lease->expired()) {
891 
892  // If the lease is expired, we may likely reuse it, but...
893  ConstHostCollection hosts;
894  // When out-of-pool flag is true the server may assume that all host
895  // reservations are for addresses that do not belong to the dynamic
896  // pool. Therefore, it can skip the reservation checks when dealing
897  // with in-pool addresses.
898  if (in_subnet &&
899  (!subnet->getReservationsOutOfPool() ||
900  !subnet->inPool(ctx.currentIA().type_, hint))) {
901  hosts = getIPv6Resrv(subnet->getID(), hint);
902  }
903 
904  // Let's check if there is a reservation for this address.
905  if (hosts.empty()) {
906 
907  // Copy an existing, expired lease so as it can be returned
908  // to the caller.
909  Lease6Ptr old_lease(new Lease6(*usable_hint_lease));
910  ctx.currentIA().old_leases_.push_back(old_lease);
911 
913  Lease6Ptr lease = reuseExpiredLease(usable_hint_lease, ctx,
914  pool->getLength(),
915  callout_status);
916 
918  return (lease);
919 
920  } else {
923  .arg(ctx.query_->getLabel())
924  .arg(hint.toText());
925  }
926  }
927  }
928 
929  // We have the choice in the order checking the lease and
930  // the reservation. The default is to begin by the lease
931  // if the multi-threading is disabled.
932  bool check_reservation_first = MultiThreadingMgr::instance().getMode();
933  // If multi-threading is disabled, honor the configured order for host
934  // reservations lookup.
935  if (!check_reservation_first) {
936  check_reservation_first = CfgMgr::instance().getCurrentCfg()->getReservationsLookupFirst();
937  }
938 
939  // Need to check if the subnet belongs to a shared network. If so,
940  // we might be able to find a better subnet for lease allocation,
941  // for which it is more likely that there are some leases available.
942  // If we stick to the selected subnet, we may end up walking over
943  // the entire subnet (or more subnets) to discover that the pools
944  // have been exhausted. Using a subnet from which a lease was
945  // assigned most recently is an optimization which increases
946  // the likelihood of starting from the subnet which pools are not
947  // exhausted.
948 
949  original_subnet->getSharedNetwork(network);
950  if (network) {
951  // This would try to find a subnet with the same set of classes
952  // as the current subnet, but with the more recent "usage timestamp".
953  // This timestamp is only updated for the allocations made with an
954  // allocator (unreserved lease allocations), not the static
955  // allocations or requested addresses.
956  original_subnet = network->getPreferredSubnet(original_subnet, ctx.currentIA().type_);
957  }
958 
959  ctx.subnet_ = subnet = original_subnet;
960 
961  for (; subnet; subnet = subnet->getNextSubnet(original_subnet)) {
962  if (!subnet->clientSupported(classes)) {
963  continue;
964  }
965 
966  // The hint was useless (it was not provided at all, was used by someone else,
967  // was out of pool or reserved for someone else). Search the pool until first
968  // of the following occurs:
969  // - we find a free address
970  // - we find an address for which the lease has expired
971  // - we exhaust number of tries
972  uint64_t possible_attempts = subnet->getPoolCapacity(ctx.currentIA().type_,
973  classes,
974  prefix_length_match,
975  hint_prefix_length);
976 
977  // If the number of tries specified in the allocation engine constructor
978  // is set to 0 (unlimited) or the pools capacity is lower than that number,
979  // let's use the pools capacity as the maximum number of tries. Trying
980  // more than the actual pools capacity is a waste of time. If the specified
981  // number of tries is lower than the pools capacity, use that number.
982  uint64_t max_attempts = ((attempts_ == 0) || (possible_attempts < attempts_)) ? possible_attempts : attempts_;
983 
984  if (max_attempts > 0) {
985  // If max_attempts is greater than 0, there are some pools in this subnet
986  // from which we can potentially get a lease.
987  ++subnets_with_unavail_leases;
988  } else {
989  // If max_attempts is 0, it is an indication that there are no pools
990  // in the subnet from which we can get a lease.
991  ++subnets_with_unavail_pools;
992  continue;
993  }
994 
995  bool in_subnet = subnet->getReservationsInSubnet();
996  bool out_of_pool = subnet->getReservationsOutOfPool();
997 
998  // Set the default status code in case the lease6_select callouts
999  // do not exist and the callout handle has a status returned by
1000  // any of the callouts already invoked for this packet.
1001  if (ctx.callout_handle_) {
1002  ctx.callout_handle_->setStatus(CalloutHandle::NEXT_STEP_CONTINUE);
1003  }
1004 
1005  for (uint64_t i = 0; i < max_attempts; ++i) {
1006  ++total_attempts;
1007 
1008  auto allocator = subnet->getAllocator(ctx.currentIA().type_);
1009  IOAddress candidate("::");
1010 
1011  // The first step is to find out prefix length. It is 128 for
1012  // non-PD leases.
1013  uint8_t prefix_len = 128;
1014  if (ctx.currentIA().type_ == Lease::TYPE_PD) {
1015  candidate = allocator->pickPrefix(classes, pool, ctx.duid_,
1016  prefix_length_match, hint,
1017  hint_prefix_length);
1018  if (pool) {
1019  prefix_len = pool->getLength();
1020  }
1021  } else {
1022  candidate = allocator->pickAddress(classes, ctx.duid_, hint);
1023  }
1024 
1025  // First check for reservation when it is the choice.
1026  if (check_reservation_first && in_subnet && !out_of_pool) {
1027  auto hosts = getIPv6Resrv(subnet->getID(), candidate);
1028  if (!hosts.empty()) {
1029  // Don't allocate.
1030  continue;
1031  }
1032  }
1033 
1034  // Check if the resource is busy i.e. can be being allocated
1035  // by another thread to another client.
1036  ResourceHandler resource_handler;
1037  if (MultiThreadingMgr::instance().getMode() &&
1038  !resource_handler.tryLock(ctx.currentIA().type_, candidate)) {
1039  // Don't allocate.
1040  continue;
1041  }
1042 
1043  // Look for an existing lease for the candidate.
1045  candidate);
1046 
1047  if (!existing) {
1051  if (!check_reservation_first && in_subnet && !out_of_pool) {
1052  auto hosts = getIPv6Resrv(subnet->getID(), candidate);
1053  if (!hosts.empty()) {
1054  // Don't allocate.
1055  continue;
1056  }
1057  }
1058 
1059  // there's no existing lease for selected candidate, so it is
1060  // free. Let's allocate it.
1061 
1062  ctx.subnet_ = subnet;
1063  Lease6Ptr new_lease = createLease6(ctx, candidate, prefix_len, callout_status);
1064  if (new_lease) {
1065  // We are allocating a new lease (not renewing). So, the
1066  // old lease should be NULL.
1067  ctx.currentIA().old_leases_.clear();
1068 
1069  return (new_lease);
1070 
1071  } else if (ctx.callout_handle_ &&
1072  (callout_status != CalloutHandle::NEXT_STEP_CONTINUE)) {
1073  // Don't retry when the callout status is not continue.
1074  break;
1075  }
1076 
1077  // Although the address was free just microseconds ago, it may have
1078  // been taken just now. If the lease insertion fails, we continue
1079  // allocation attempts.
1080  } else if (existing->expired()) {
1081  // Make sure it's not reserved.
1082  if (!check_reservation_first && in_subnet && !out_of_pool) {
1083  auto hosts = getIPv6Resrv(subnet->getID(), candidate);
1084  if (!hosts.empty()) {
1085  // Don't allocate.
1086  continue;
1087  }
1088  }
1089 
1090  // Copy an existing, expired lease so as it can be returned
1091  // to the caller.
1092  Lease6Ptr old_lease(new Lease6(*existing));
1093  ctx.currentIA().old_leases_.push_back(old_lease);
1094 
1095  ctx.subnet_ = subnet;
1096  existing = reuseExpiredLease(existing, ctx, prefix_len,
1097  callout_status);
1098 
1099  return (existing);
1100  }
1101  }
1102  }
1103  return (Lease6Ptr());
1104 }
1105 
1106 void
1107 AllocEngine::allocateReservedLeases6(ClientContext6& ctx,
1108  Lease6Collection& existing_leases) {
1109 
1110  // If there are no reservations or the reservation is v4, there's nothing to do.
1111  if (ctx.hosts_.empty()) {
1114  .arg(ctx.query_->getLabel());
1115  return;
1116  }
1117 
1118  // Let's convert this from Lease::Type to IPv6Reserv::Type
1119  IPv6Resrv::Type type = ctx.currentIA().type_ == Lease::TYPE_NA ?
1121 
1122  // We want to avoid allocating new lease for an IA if there is already
1123  // a valid lease for which client has reservation. So, we first check if
1124  // we already have a lease for a reserved address or prefix.
1125  BOOST_FOREACH(const Lease6Ptr& lease, existing_leases) {
1126  if ((lease->valid_lft_ != 0)) {
1127  if ((ctx.hosts_.count(lease->subnet_id_) > 0) &&
1128  ctx.hosts_[lease->subnet_id_]->hasReservation(makeIPv6Resrv(*lease))) {
1129  // We found existing lease for a reserved address or prefix.
1130  // We'll simply extend the lifetime of the lease.
1133  .arg(ctx.query_->getLabel())
1134  .arg(lease->typeToText(lease->type_))
1135  .arg(lease->addr_.toText());
1136 
1137  // Besides IP reservations we're also going to return other reserved
1138  // parameters, such as hostname. We want to hand out the hostname value
1139  // from the same reservation entry as IP addresses. Thus, let's see if
1140  // there is any hostname reservation.
1141  if (!ctx.host_subnet_) {
1142  SharedNetwork6Ptr network;
1143  ctx.subnet_->getSharedNetwork(network);
1144  if (network) {
1145  // Remember the subnet that holds this preferred host
1146  // reservation. The server will use it to return appropriate
1147  // FQDN, classes etc.
1148  ctx.host_subnet_ = network->getSubnet(lease->subnet_id_);
1149  ConstHostPtr host = ctx.hosts_[lease->subnet_id_];
1150  // If there is a hostname reservation here we should stick
1151  // to this reservation. By updating the hostname in the
1152  // context we make sure that the database is updated with
1153  // this new value and the server doesn't need to do it and
1154  // its processing performance is not impacted by the hostname
1155  // updates.
1156  if (host && !host->getHostname().empty()) {
1157  // We have to determine whether the hostname is generated
1158  // in response to client's FQDN or not. If yes, we will
1159  // need to qualify the hostname. Otherwise, we just use
1160  // the hostname as it is specified for the reservation.
1161  OptionPtr fqdn = ctx.query_->getOption(D6O_CLIENT_FQDN);
1163  qualifyName(host->getHostname(), *ctx.getDdnsParams(),
1164  static_cast<bool>(fqdn));
1165  }
1166  }
1167  }
1168 
1169  // Got a lease for a reservation in this IA.
1170  return;
1171  }
1172  }
1173  }
1174 
1175  // There is no lease for a reservation in this IA. So, let's now iterate
1176  // over reservations specified and try to allocate one of them for the IA.
1177 
1178  auto const& classes = ctx.query_->getClasses();
1179  for (Subnet6Ptr subnet = ctx.subnet_; subnet;
1180  subnet = subnet->getNextSubnet(ctx.subnet_)) {
1181 
1182  SubnetID subnet_id = subnet->getID();
1183 
1184  // No hosts for this subnet or the subnet not supported.
1185  if (!subnet->clientSupported(classes) || ctx.hosts_.count(subnet_id) == 0) {
1186  continue;
1187  }
1188 
1189  ConstHostPtr host = ctx.hosts_[subnet_id];
1190 
1191  bool in_subnet = subnet->getReservationsInSubnet();
1192 
1193  // Get the IPv6 reservations of specified type.
1194  const IPv6ResrvRange& reservs = host->getIPv6Reservations(type);
1195  BOOST_FOREACH(IPv6ResrvTuple type_lease_tuple, reservs) {
1196  // We do have a reservation for address or prefix.
1197  const IOAddress& addr = type_lease_tuple.second.getPrefix();
1198  uint8_t prefix_len = type_lease_tuple.second.getPrefixLen();
1199 
1200  // We have allocated this address/prefix while processing one of the
1201  // previous IAs, so let's try another reservation.
1202  if (ctx.isAllocated(addr, prefix_len)) {
1203  continue;
1204  }
1205 
1206  // The out-of-pool flag indicates that no client should be assigned
1207  // reserved addresses from within the dynamic pool, and for that
1208  // reason look only for reservations that are outside the pools,
1209  // hence the inPool check.
1210  if (!in_subnet ||
1211  (subnet->getReservationsOutOfPool() &&
1212  subnet->inPool(ctx.currentIA().type_, addr))) {
1213  continue;
1214  }
1215 
1216  // If there's a lease for this address, let's not create it.
1217  // It doesn't matter whether it is for this client or for someone else.
1219  addr)) {
1220 
1221  // Let's remember the subnet from which the reserved address has been
1222  // allocated. We'll use this subnet for allocating other reserved
1223  // resources.
1224  ctx.subnet_ = subnet;
1225 
1226  if (!ctx.host_subnet_) {
1227  ctx.host_subnet_ = subnet;
1228  if (!host->getHostname().empty()) {
1229  // If there is a hostname reservation here we should stick
1230  // to this reservation. By updating the hostname in the
1231  // context we make sure that the database is updated with
1232  // this new value and the server doesn't need to do it and
1233  // its processing performance is not impacted by the hostname
1234  // updates.
1235 
1236  // We have to determine whether the hostname is generated
1237  // in response to client's FQDN or not. If yes, we will
1238  // need to qualify the hostname. Otherwise, we just use
1239  // the hostname as it is specified for the reservation.
1240  OptionPtr fqdn = ctx.query_->getOption(D6O_CLIENT_FQDN);
1242  qualifyName(host->getHostname(), *ctx.getDdnsParams(),
1243  static_cast<bool>(fqdn));
1244  }
1245  }
1246 
1247  // Ok, let's create a new lease...
1248  CalloutHandle::CalloutNextStep callout_status = CalloutHandle::NEXT_STEP_CONTINUE;
1249  Lease6Ptr lease = createLease6(ctx, addr, prefix_len, callout_status);
1250 
1251  // ... and add it to the existing leases list.
1252  existing_leases.push_back(lease);
1253 
1254  if (ctx.currentIA().type_ == Lease::TYPE_NA) {
1256  .arg(addr.toText())
1257  .arg(ctx.query_->getLabel());
1258  } else {
1260  .arg(addr.toText())
1261  .arg(static_cast<int>(prefix_len))
1262  .arg(ctx.query_->getLabel());
1263  }
1264 
1265  // We found a lease for this client and this IA. Let's return.
1266  // Returning after the first lease was assigned is useful if we
1267  // have multiple reservations for the same client. If the client
1268  // sends 2 IAs, the first time we call allocateReservedLeases6 will
1269  // use the first reservation and return. The second time, we'll
1270  // go over the first reservation, but will discover that there's
1271  // a lease corresponding to it and will skip it and then pick
1272  // the second reservation and turn it into the lease. This approach
1273  // would work for any number of reservations.
1274  return;
1275  }
1276  }
1277  }
1278 
1279  // Found no subnet reservations so now try the global reservation.
1280  allocateGlobalReservedLeases6(ctx, existing_leases);
1281 }
1282 
1283 void
1284 AllocEngine::allocateGlobalReservedLeases6(ClientContext6& ctx,
1285  Lease6Collection& existing_leases) {
1286  // Get the global host
1287  ConstHostPtr ghost = ctx.globalHost();
1288  if (!ghost) {
1289  return;
1290  }
1291 
1292  // We want to avoid allocating a new lease for an IA if there is already
1293  // a valid lease for which client has reservation. So, we first check if
1294  // we already have a lease for a reserved address or prefix.
1295  BOOST_FOREACH(const Lease6Ptr& lease, existing_leases) {
1296  if ((lease->valid_lft_ != 0) &&
1297  (ghost->hasReservation(makeIPv6Resrv(*lease)))) {
1298  // We found existing lease for a reserved address or prefix.
1299  // We'll simply extend the lifetime of the lease.
1302  .arg(ctx.query_->getLabel())
1303  .arg(lease->typeToText(lease->type_))
1304  .arg(lease->addr_.toText());
1305 
1306  // Besides IP reservations we're also going to return other reserved
1307  // parameters, such as hostname. We want to hand out the hostname value
1308  // from the same reservation entry as IP addresses. Thus, let's see if
1309  // there is any hostname reservation.
1310  if (!ghost->getHostname().empty()) {
1311  // We have to determine whether the hostname is generated
1312  // in response to client's FQDN or not. If yes, we will
1313  // need to qualify the hostname. Otherwise, we just use
1314  // the hostname as it is specified for the reservation.
1315  OptionPtr fqdn = ctx.query_->getOption(D6O_CLIENT_FQDN);
1317  qualifyName(ghost->getHostname(), *ctx.getDdnsParams(),
1318  static_cast<bool>(fqdn));
1319  }
1320 
1321  // Got a lease for a reservation in this IA.
1322  return;
1323  }
1324  }
1325 
1326  // There is no lease for a reservation in this IA. So, let's now iterate
1327  // over reservations specified and try to allocate one of them for the IA.
1328 
1329  // Let's convert this from Lease::Type to IPv6Reserv::Type
1330  IPv6Resrv::Type type = ctx.currentIA().type_ == Lease::TYPE_NA ?
1332 
1333  const IPv6ResrvRange& reservs = ghost->getIPv6Reservations(type);
1334  BOOST_FOREACH(IPv6ResrvTuple type_lease_tuple, reservs) {
1335  // We do have a reservation for address or prefix.
1336  const IOAddress& addr = type_lease_tuple.second.getPrefix();
1337  uint8_t prefix_len = type_lease_tuple.second.getPrefixLen();
1338 
1339  // We have allocated this address/prefix while processing one of the
1340  // previous IAs, so let's try another reservation.
1341  if (ctx.isAllocated(addr, prefix_len)) {
1342  continue;
1343  }
1344 
1345  // If there's a lease for this address, let's not create it.
1346  // It doesn't matter whether it is for this client or for someone else.
1347  if (!LeaseMgrFactory::instance().getLease6(ctx.currentIA().type_, addr)) {
1348 
1349  // Check the feasibility of this address within this shared-network.
1350  // Assign the context's subnet accordingly.
1351  // Only necessary for IA_NA
1352  if (type == IPv6Resrv::TYPE_NA) {
1353  bool valid_subnet = false;
1354  auto subnet = ctx.subnet_;
1355  while (subnet) {
1356  if (subnet->inRange(addr)) {
1357  valid_subnet = true;
1358  break;
1359  }
1360 
1361  subnet = subnet->getNextSubnet(ctx.subnet_);
1362  }
1363 
1364  if (!valid_subnet) {
1367  .arg(addr.toText())
1368  .arg(labelNetworkOrSubnet(ctx.subnet_));
1369  continue;
1370  }
1371 
1372  ctx.subnet_ = subnet;
1373  }
1374 
1375  if (!ghost->getHostname().empty()) {
1376  // If there is a hostname reservation here we should stick
1377  // to this reservation. By updating the hostname in the
1378  // context we make sure that the database is updated with
1379  // this new value and the server doesn't need to do it and
1380  // its processing performance is not impacted by the hostname
1381  // updates.
1382 
1383  // We have to determine whether the hostname is generated
1384  // in response to client's FQDN or not. If yes, we will
1385  // need to qualify the hostname. Otherwise, we just use
1386  // the hostname as it is specified for the reservation.
1387  OptionPtr fqdn = ctx.query_->getOption(D6O_CLIENT_FQDN);
1389  qualifyName(ghost->getHostname(), *ctx.getDdnsParams(),
1390  static_cast<bool>(fqdn));
1391  }
1392 
1393  // Ok, let's create a new lease...
1394  CalloutHandle::CalloutNextStep callout_status = CalloutHandle::NEXT_STEP_CONTINUE;
1395  Lease6Ptr lease = createLease6(ctx, addr, prefix_len, callout_status);
1396 
1397  // ... and add it to the existing leases list.
1398  existing_leases.push_back(lease);
1399 
1400  if (ctx.currentIA().type_ == Lease::TYPE_NA) {
1402  .arg(addr.toText())
1403  .arg(ctx.query_->getLabel());
1404  } else {
1406  .arg(addr.toText())
1407  .arg(static_cast<int>(prefix_len))
1408  .arg(ctx.query_->getLabel());
1409  }
1410 
1411  // We found a lease for this client and this IA. Let's return.
1412  // Returning after the first lease was assigned is useful if we
1413  // have multiple reservations for the same client. If the client
1414  // sends 2 IAs, the first time we call allocateReservedLeases6 will
1415  // use the first reservation and return. The second time, we'll
1416  // go over the first reservation, but will discover that there's
1417  // a lease corresponding to it and will skip it and then pick
1418  // the second reservation and turn it into the lease. This approach
1419  // would work for any number of reservations.
1420  return;
1421  }
1422  }
1423 }
1424 
1425 void
1426 AllocEngine::removeNonmatchingReservedLeases6(ClientContext6& ctx,
1427  Lease6Collection& existing_leases) {
1428  // If there are no leases (so nothing to remove) just return.
1429  if (existing_leases.empty() || !ctx.subnet_) {
1430  return;
1431  }
1432  // If host reservation is disabled (so there are no reserved leases)
1433  // use the simplified version.
1434  if (!ctx.subnet_->getReservationsInSubnet() &&
1435  !ctx.subnet_->getReservationsGlobal()) {
1436  removeNonmatchingReservedNoHostLeases6(ctx, existing_leases);
1437  return;
1438  }
1439 
1440  // We need a copy, so we won't be iterating over a container and
1441  // removing from it at the same time. It's only a copy of pointers,
1442  // so the operation shouldn't be that expensive.
1443  Lease6Collection copy = existing_leases;
1444 
1445  BOOST_FOREACH(const Lease6Ptr& candidate, copy) {
1446  // If we have reservation we should check if the reservation is for
1447  // the candidate lease. If so, we simply accept the lease.
1448  IPv6Resrv resv = makeIPv6Resrv(*candidate);
1449  if ((ctx.hasGlobalReservation(resv)) ||
1450  ((ctx.hosts_.count(candidate->subnet_id_) > 0) &&
1451  (ctx.hosts_[candidate->subnet_id_]->hasReservation(resv)))) {
1452  // We have a subnet reservation
1453  continue;
1454  }
1455 
1456  // The candidate address doesn't appear to be reserved for us.
1457  // We have to make a bit more expensive operation here to retrieve
1458  // the reservation for the candidate lease and see if it is
1459  // reserved for someone else.
1460  auto hosts = getIPv6Resrv(ctx.subnet_->getID(), candidate->addr_);
1461  // If lease is not reserved to someone else, it means that it can
1462  // be allocated to us from a dynamic pool, but we must check if
1463  // this lease belongs to any pool. If it does, we can proceed to
1464  // checking the next lease.
1465  if (hosts.empty() && inAllowedPool(ctx, candidate->type_,
1466  candidate->addr_, false)) {
1467  continue;
1468  }
1469 
1470  if (!hosts.empty()) {
1471  // Ok, we have a problem. This host has a lease that is reserved
1472  // for someone else. We need to recover from this.
1473  if (hosts.size() == 1) {
1474  if (ctx.currentIA().type_ == Lease::TYPE_NA) {
1476  .arg(candidate->addr_.toText())
1477  .arg(ctx.duid_->toText())
1478  .arg(hosts.front()->getIdentifierAsText());
1479  } else {
1481  .arg(candidate->addr_.toText())
1482  .arg(static_cast<int>(candidate->prefixlen_))
1483  .arg(ctx.duid_->toText())
1484  .arg(hosts.front()->getIdentifierAsText());
1485  }
1486  } else {
1487  if (ctx.currentIA().type_ == Lease::TYPE_NA) {
1489  .arg(candidate->addr_.toText())
1490  .arg(ctx.duid_->toText())
1491  .arg(hosts.size());
1492  } else {
1494  .arg(candidate->addr_.toText())
1495  .arg(static_cast<int>(candidate->prefixlen_))
1496  .arg(ctx.duid_->toText())
1497  .arg(hosts.size());
1498  }
1499  }
1500  }
1501 
1502  // Remove this lease from LeaseMgr as it is reserved to someone
1503  // else or doesn't belong to a pool.
1504  if (!LeaseMgrFactory::instance().deleteLease(candidate)) {
1505  // Concurrent delete performed by other instance which should
1506  // properly handle dns and stats updates.
1507  continue;
1508  }
1509 
1510  // Update DNS if needed.
1511  queueNCR(CHG_REMOVE, candidate);
1512 
1513  // Need to decrease statistic for assigned addresses.
1514  StatsMgr::instance().addValue(
1515  StatsMgr::generateName("subnet", candidate->subnet_id_,
1516  ctx.currentIA().type_ == Lease::TYPE_NA ?
1517  "assigned-nas" : "assigned-pds"),
1518  static_cast<int64_t>(-1));
1519 
1520  // In principle, we could trigger a hook here, but we will do this
1521  // only if we get serious complaints from actual users. We want the
1522  // conflict resolution procedure to really work and user libraries
1523  // should not interfere with it.
1524 
1525  // Add this to the list of removed leases.
1526  ctx.currentIA().old_leases_.push_back(candidate);
1527 
1528  // Let's remove this candidate from existing leases
1529  removeLeases(existing_leases, candidate->addr_);
1530  }
1531 }
1532 
1533 void
1534 AllocEngine::removeNonmatchingReservedNoHostLeases6(ClientContext6& ctx,
1535  Lease6Collection& existing_leases) {
1536  // We need a copy, so we won't be iterating over a container and
1537  // removing from it at the same time. It's only a copy of pointers,
1538  // so the operation shouldn't be that expensive.
1539  Lease6Collection copy = existing_leases;
1540 
1541  BOOST_FOREACH(const Lease6Ptr& candidate, copy) {
1542  // Lease can be allocated to us from a dynamic pool, but we must
1543  // check if this lease belongs to any allowed pool. If it does,
1544  // we can proceed to checking the next lease.
1545  if (inAllowedPool(ctx, candidate->type_,
1546  candidate->addr_, false)) {
1547  continue;
1548  }
1549 
1550  // Remove this lease from LeaseMgr as it doesn't belong to a pool.
1551  if (!LeaseMgrFactory::instance().deleteLease(candidate)) {
1552  // Concurrent delete performed by other instance which should
1553  // properly handle dns and stats updates.
1554  continue;
1555  }
1556 
1557  // Update DNS if needed.
1558  queueNCR(CHG_REMOVE, candidate);
1559 
1560  // Need to decrease statistic for assigned addresses.
1561  StatsMgr::instance().addValue(
1562  StatsMgr::generateName("subnet", candidate->subnet_id_,
1563  ctx.currentIA().type_ == Lease::TYPE_NA ?
1564  "assigned-nas" : "assigned-pds"),
1565  static_cast<int64_t>(-1));
1566 
1567  // Add this to the list of removed leases.
1568  ctx.currentIA().old_leases_.push_back(candidate);
1569 
1570  // Let's remove this candidate from existing leases
1571  removeLeases(existing_leases, candidate->addr_);
1572  }
1573 }
1574 
1575 bool
1576 AllocEngine::removeLeases(Lease6Collection& container, const asiolink::IOAddress& addr) {
1577 
1578  bool removed = false;
1579  for (Lease6Collection::iterator lease = container.begin();
1580  lease != container.end(); ++lease) {
1581  if ((*lease)->addr_ == addr) {
1582  lease->reset();
1583  removed = true;
1584  }
1585  }
1586 
1587  // Remove all elements that have NULL value
1588  container.erase(std::remove(container.begin(), container.end(), Lease6Ptr()),
1589  container.end());
1590 
1591  return (removed);
1592 }
1593 
1594 void
1595 AllocEngine::removeNonreservedLeases6(ClientContext6& ctx,
1596  Lease6Collection& existing_leases) {
1597  // This method removes leases that are not reserved for this host.
1598  // It will keep at least one lease, though, as a fallback.
1599  int total = existing_leases.size();
1600  if (total <= 1) {
1601  return;
1602  }
1603 
1604  // This is officially not scary code anymore. iterates and marks specified
1605  // leases for deletion, by setting appropriate pointers to NULL.
1606  for (Lease6Collection::iterator lease = existing_leases.begin();
1607  lease != existing_leases.end(); ++lease) {
1608 
1609  // If there is reservation for this keep it.
1610  IPv6Resrv resv = makeIPv6Resrv(*(*lease));
1611  if (ctx.hasGlobalReservation(resv) ||
1612  ((ctx.hosts_.count((*lease)->subnet_id_) > 0) &&
1613  (ctx.hosts_[(*lease)->subnet_id_]->hasReservation(resv)))) {
1614  continue;
1615  }
1616 
1617  // @todo - If this is for a fake_allocation, we should probably
1618  // not be deleting the lease or removing DNS entries. We should
1619  // simply remove it from the list.
1620  // We have reservations, but not for this lease. Release it.
1621  // Remove this lease from LeaseMgr
1622  if (!LeaseMgrFactory::instance().deleteLease(*lease)) {
1623  // Concurrent delete performed by other instance which should
1624  // properly handle dns and stats updates.
1625  continue;
1626  }
1627 
1628  // Update DNS if required.
1629  queueNCR(CHG_REMOVE, *lease);
1630 
1631  // Need to decrease statistic for assigned addresses.
1632  StatsMgr::instance().addValue(
1633  StatsMgr::generateName("subnet", (*lease)->subnet_id_,
1634  ctx.currentIA().type_ == Lease::TYPE_NA ?
1635  "assigned-nas" : "assigned-pds"),
1636  static_cast<int64_t>(-1));
1637 
1639 
1640  // Add this to the list of removed leases.
1641  ctx.currentIA().old_leases_.push_back(*lease);
1642 
1643  // Set this pointer to NULL. The pointer is still valid. We're just
1644  // setting the Lease6Ptr to NULL value. We'll remove all NULL
1645  // pointers once the loop is finished.
1646  lease->reset();
1647 
1648  if (--total == 1) {
1649  // If there's only one lease left, break the loop.
1650  break;
1651  }
1652  }
1653 
1654  // Remove all elements that we previously marked for deletion (those that
1655  // have NULL value).
1656  existing_leases.erase(std::remove(existing_leases.begin(),
1657  existing_leases.end(), Lease6Ptr()), existing_leases.end());
1658 }
1659 
1660 Lease6Ptr
1661 AllocEngine::reuseExpiredLease(Lease6Ptr& expired, ClientContext6& ctx,
1662  uint8_t prefix_len,
1663  CalloutHandle::CalloutNextStep& callout_status) {
1664 
1665  if (!expired->expired()) {
1666  isc_throw(BadValue, "Attempt to recycle lease that is still valid");
1667  }
1668 
1669  if (expired->type_ != Lease::TYPE_PD) {
1670  prefix_len = 128; // non-PD lease types must be always /128
1671  }
1672 
1673  if (!ctx.fake_allocation_) {
1674  // The expired lease needs to be reclaimed before it can be reused.
1675  // This includes declined leases for which probation period has
1676  // elapsed.
1677  reclaimExpiredLease(expired, ctx.callout_handle_);
1678  }
1679 
1680  // address, lease type and prefixlen (0) stay the same
1681  expired->iaid_ = ctx.currentIA().iaid_;
1682  expired->duid_ = ctx.duid_;
1683 
1684  // Calculate life times.
1685  getLifetimes6(ctx, expired->preferred_lft_, expired->valid_lft_);
1686  expired->reuseable_valid_lft_ = 0;
1687 
1688  expired->cltt_ = time(NULL);
1689  expired->subnet_id_ = ctx.subnet_->getID();
1690  expired->hostname_ = ctx.hostname_;
1691  expired->fqdn_fwd_ = ctx.fwd_dns_update_;
1692  expired->fqdn_rev_ = ctx.rev_dns_update_;
1693  expired->prefixlen_ = prefix_len;
1694  expired->state_ = Lease::STATE_DEFAULT;
1695 
1698  .arg(ctx.query_->getLabel())
1699  .arg(expired->toText());
1700 
1701  // Let's execute all callouts registered for lease6_select
1702  if (ctx.callout_handle_ &&
1703  HooksManager::calloutsPresent(hook_index_lease6_select_)) {
1704 
1705  // Use the RAII wrapper to make sure that the callout handle state is
1706  // reset when this object goes out of scope. All hook points must do
1707  // it to prevent possible circular dependency between the callout
1708  // handle and its arguments.
1709  ScopedCalloutHandleState callout_handle_state(ctx.callout_handle_);
1710 
1711  // Enable copying options from the packet within hook library.
1712  ScopedEnableOptionsCopy<Pkt6> query6_options_copy(ctx.query_);
1713 
1714  // Pass necessary arguments
1715 
1716  // Pass the original packet
1717  ctx.callout_handle_->setArgument("query6", ctx.query_);
1718 
1719  // Subnet from which we do the allocation
1720  ctx.callout_handle_->setArgument("subnet6", ctx.subnet_);
1721 
1722  // Is this solicit (fake = true) or request (fake = false)
1723  ctx.callout_handle_->setArgument("fake_allocation", ctx.fake_allocation_);
1724 
1725  // The lease that will be assigned to a client
1726  ctx.callout_handle_->setArgument("lease6", expired);
1727 
1728  // Call the callouts
1729  HooksManager::callCallouts(hook_index_lease6_select_, *ctx.callout_handle_);
1730 
1731  callout_status = ctx.callout_handle_->getStatus();
1732 
1733  // Callouts decided to skip the action. This means that the lease is not
1734  // assigned, so the client will get NoAddrAvail as a result. The lease
1735  // won't be inserted into the database.
1736  if (callout_status == CalloutHandle::NEXT_STEP_SKIP) {
1738  return (Lease6Ptr());
1739  }
1740 
1745 
1746  // Let's use whatever callout returned. Hopefully it is the same lease
1747  // we handed to it.
1748  ctx.callout_handle_->getArgument("lease6", expired);
1749  }
1750 
1751  if (!ctx.fake_allocation_) {
1752  // Add(update) the extended information on the lease.
1753  updateLease6ExtendedInfo(expired, ctx);
1754 
1755  // for REQUEST we do update the lease
1757 
1758  // If the lease is in the current subnet we need to account
1759  // for the re-assignment of The lease.
1760  if (ctx.subnet_->inPool(ctx.currentIA().type_, expired->addr_)) {
1761  StatsMgr::instance().addValue(
1762  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
1763  ctx.currentIA().type_ == Lease::TYPE_NA ?
1764  "assigned-nas" : "assigned-pds"),
1765  static_cast<int64_t>(1));
1766  StatsMgr::instance().addValue(
1767  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
1768  ctx.currentIA().type_ == Lease::TYPE_NA ?
1769  "cumulative-assigned-nas" :
1770  "cumulative-assigned-pds"),
1771  static_cast<int64_t>(1));
1772  StatsMgr::instance().addValue(ctx.currentIA().type_ == Lease::TYPE_NA ?
1773  "cumulative-assigned-nas" :
1774  "cumulative-assigned-pds",
1775  static_cast<int64_t>(1));
1776  }
1777  }
1778 
1779  // We do nothing for SOLICIT. We'll just update database when
1780  // the client gets back to us with REQUEST message.
1781 
1782  // it's not really expired at this stage anymore - let's return it as
1783  // an updated lease
1784  return (expired);
1785 }
1786 
1787 void
1788 AllocEngine::getLifetimes6(ClientContext6& ctx, uint32_t& preferred, uint32_t& valid) {
1789  // If the triplets are specified in one of our classes use it.
1790  // We use the first one we find for each lifetime.
1791  Triplet<uint32_t> candidate_preferred;
1792  Triplet<uint32_t> candidate_valid;
1793  const ClientClasses classes = ctx.query_->getClasses();
1794  if (!classes.empty()) {
1795  // Let's get class definitions
1796  const ClientClassDictionaryPtr& dict =
1797  CfgMgr::instance().getCurrentCfg()->getClientClassDictionary();
1798 
1799  // Iterate over the assigned class definitions.
1800  int have_both = 0;
1801  for (auto name = classes.cbegin();
1802  name != classes.cend() && have_both < 2; ++name) {
1803  ClientClassDefPtr cl = dict->findClass(*name);
1804  if (candidate_preferred.unspecified() &&
1805  (cl && (!cl->getPreferred().unspecified()))) {
1806  candidate_preferred = cl->getPreferred();
1807  ++have_both;
1808  }
1809 
1810  if (candidate_valid.unspecified() &&
1811  (cl && (!cl->getValid().unspecified()))) {
1812  candidate_valid = cl->getValid();
1813  ++have_both;
1814  }
1815  }
1816  }
1817 
1818  // If no classes specified preferred lifetime, get it from the subnet.
1819  if (!candidate_preferred) {
1820  candidate_preferred = ctx.subnet_->getPreferred();
1821  }
1822 
1823  // If no classes specified valid lifetime, get it from the subnet.
1824  if (!candidate_valid) {
1825  candidate_valid = ctx.subnet_->getValid();
1826  }
1827 
1828  // Set the outbound parameters to the values we have so far.
1829  preferred = candidate_preferred;
1830  valid = candidate_valid;
1831 
1832  // If client requested either value, use the requested value(s) bounded by
1833  // the candidate triplet(s).
1834  if (!ctx.currentIA().hints_.empty()) {
1835  if (ctx.currentIA().hints_[0].getPreferred()) {
1836  preferred = candidate_preferred.get(ctx.currentIA().hints_[0].getPreferred());
1837  }
1838 
1839  if (ctx.currentIA().hints_[0].getValid()) {
1840  valid = candidate_valid.get(ctx.currentIA().hints_[0].getValid());
1841  }
1842  }
1843 }
1844 
1845 Lease6Ptr AllocEngine::createLease6(ClientContext6& ctx,
1846  const IOAddress& addr,
1847  uint8_t prefix_len,
1848  CalloutHandle::CalloutNextStep& callout_status) {
1849 
1850  if (ctx.currentIA().type_ != Lease::TYPE_PD) {
1851  prefix_len = 128; // non-PD lease types must be always /128
1852  }
1853 
1854  uint32_t preferred = 0;
1855  uint32_t valid = 0;
1856  getLifetimes6(ctx, preferred, valid);
1857 
1858  Lease6Ptr lease(new Lease6(ctx.currentIA().type_, addr, ctx.duid_,
1859  ctx.currentIA().iaid_, preferred,
1860  valid, ctx.subnet_->getID(),
1861  ctx.hwaddr_, prefix_len));
1862 
1863  lease->fqdn_fwd_ = ctx.fwd_dns_update_;
1864  lease->fqdn_rev_ = ctx.rev_dns_update_;
1865  lease->hostname_ = ctx.hostname_;
1866 
1867  // Let's execute all callouts registered for lease6_select
1868  if (ctx.callout_handle_ &&
1869  HooksManager::calloutsPresent(hook_index_lease6_select_)) {
1870 
1871  // Use the RAII wrapper to make sure that the callout handle state is
1872  // reset when this object goes out of scope. All hook points must do
1873  // it to prevent possible circular dependency between the callout
1874  // handle and its arguments.
1875  ScopedCalloutHandleState callout_handle_state(ctx.callout_handle_);
1876 
1877  // Enable copying options from the packet within hook library.
1878  ScopedEnableOptionsCopy<Pkt6> query6_options_copy(ctx.query_);
1879 
1880  // Pass necessary arguments
1881 
1882  // Pass the original packet
1883  ctx.callout_handle_->setArgument("query6", ctx.query_);
1884 
1885  // Subnet from which we do the allocation
1886  ctx.callout_handle_->setArgument("subnet6", ctx.subnet_);
1887 
1888  // Is this solicit (fake = true) or request (fake = false)
1889  ctx.callout_handle_->setArgument("fake_allocation", ctx.fake_allocation_);
1890 
1891  // The lease that will be assigned to a client
1892  ctx.callout_handle_->setArgument("lease6", lease);
1893 
1894  // This is the first callout, so no need to clear any arguments
1895  HooksManager::callCallouts(hook_index_lease6_select_, *ctx.callout_handle_);
1896 
1897  callout_status = ctx.callout_handle_->getStatus();
1898 
1899  // Callouts decided to skip the action. This means that the lease is not
1900  // assigned, so the client will get NoAddrAvail as a result. The lease
1901  // won't be inserted into the database.
1902  if (callout_status == CalloutHandle::NEXT_STEP_SKIP) {
1904  return (Lease6Ptr());
1905  }
1906 
1907  // Let's use whatever callout returned. Hopefully it is the same lease
1908  // we handed to it.
1909  ctx.callout_handle_->getArgument("lease6", lease);
1910  }
1911 
1912  if (!ctx.fake_allocation_) {
1913  // Add(update) the extended information on the lease.
1914  updateLease6ExtendedInfo(lease, ctx);
1915 
1916  // That is a real (REQUEST) allocation
1917  bool status = LeaseMgrFactory::instance().addLease(lease);
1918 
1919  if (status) {
1920  // The lease insertion succeeded - if the lease is in the
1921  // current subnet lets bump up the statistic.
1922  if (ctx.subnet_->inPool(ctx.currentIA().type_, addr)) {
1923  StatsMgr::instance().addValue(
1924  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
1925  ctx.currentIA().type_ == Lease::TYPE_NA ?
1926  "assigned-nas" : "assigned-pds"),
1927  static_cast<int64_t>(1));
1928  StatsMgr::instance().addValue(
1929  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
1930  ctx.currentIA().type_ == Lease::TYPE_NA ?
1931  "cumulative-assigned-nas" :
1932  "cumulative-assigned-pds"),
1933  static_cast<int64_t>(1));
1934  StatsMgr::instance().addValue(ctx.currentIA().type_ == Lease::TYPE_NA ?
1935  "cumulative-assigned-nas" :
1936  "cumulative-assigned-pds",
1937  static_cast<int64_t>(1));
1938  }
1939 
1940  // Record it so it won't be updated twice.
1941  ctx.currentIA().addNewResource(addr, prefix_len);
1942 
1943  return (lease);
1944  } else {
1945  // One of many failures with LeaseMgr (e.g. lost connection to the
1946  // database, database failed etc.). One notable case for that
1947  // is that we are working in multi-process mode and we lost a race
1948  // (some other process got that address first)
1949  return (Lease6Ptr());
1950  }
1951  } else {
1952  // That is only fake (SOLICIT without rapid-commit) allocation
1953 
1954  // It is for advertise only. We should not insert the lease and callers
1955  // have already verified the lease does not exist in the database.
1956  return (lease);
1957  }
1958 }
1959 
1962  try {
1963  if (!ctx.subnet_) {
1964  isc_throw(InvalidOperation, "Subnet is required for allocation");
1965  }
1966 
1967  if (!ctx.duid_) {
1968  isc_throw(InvalidOperation, "DUID is mandatory for allocation");
1969  }
1970 
1971  // Check if there are any leases for this client.
1972  Subnet6Ptr subnet = ctx.subnet_;
1973  Lease6Collection leases;
1974  while (subnet) {
1975  Lease6Collection leases_subnet =
1977  *ctx.duid_,
1978  ctx.currentIA().iaid_,
1979  subnet->getID());
1980  leases.insert(leases.end(), leases_subnet.begin(), leases_subnet.end());
1981 
1982  subnet = subnet->getNextSubnet(ctx.subnet_);
1983  }
1984 
1985  if (!leases.empty()) {
1988  .arg(ctx.query_->getLabel());
1989 
1990  // Check if the existing leases are reserved for someone else.
1991  // If they're not, we're ok to keep using them.
1992  removeNonmatchingReservedLeases6(ctx, leases);
1993  }
1994 
1995  if (!ctx.hosts_.empty()) {
1996 
1999  .arg(ctx.query_->getLabel());
2000 
2001  // If we have host reservation, allocate those leases.
2002  allocateReservedLeases6(ctx, leases);
2003 
2004  // There's one more check to do. Let's remove leases that are not
2005  // matching reservations, i.e. if client X has address A, but there's
2006  // a reservation for address B, we should release A and reassign B.
2007  // Caveat: do this only if we have at least one reserved address.
2008  removeNonreservedLeases6(ctx, leases);
2009  }
2010 
2011  // If we happen to removed all leases, get something new for this guy.
2012  // Depending on the configuration, we may enable or disable granting
2013  // new leases during renewals. This is controlled with the
2014  // allow_new_leases_in_renewals_ field.
2015  if (leases.empty()) {
2016 
2019  .arg(ctx.query_->getLabel());
2020 
2021  leases = allocateUnreservedLeases6(ctx);
2022  }
2023 
2024  // Extend all existing leases that passed all checks.
2025  for (Lease6Collection::iterator l = leases.begin(); l != leases.end(); ++l) {
2026  if (ctx.currentIA().isNewResource((*l)->addr_,
2027  (*l)->prefixlen_)) {
2028  // This lease was just created so is already extended.
2029  continue;
2030  }
2033  .arg(ctx.query_->getLabel())
2034  .arg((*l)->typeToText((*l)->type_))
2035  .arg((*l)->addr_);
2036  extendLease6(ctx, *l);
2037  }
2038 
2039  if (!leases.empty()) {
2040  // If there are any leases allocated, let's store in them in the
2041  // IA context so as they are available when we process subsequent
2042  // IAs.
2043  BOOST_FOREACH(Lease6Ptr lease, leases) {
2044  ctx.addAllocatedResource(lease->addr_, lease->prefixlen_);
2045  ctx.new_leases_.push_back(lease);
2046  }
2047  }
2048 
2049  return (leases);
2050 
2051  } catch (const isc::Exception& e) {
2052 
2053  // Some other error, return an empty lease.
2055  .arg(ctx.query_->getLabel())
2056  .arg(e.what());
2057  }
2058 
2059  return (Lease6Collection());
2060 }
2061 
2062 void
2063 AllocEngine::extendLease6(ClientContext6& ctx, Lease6Ptr lease) {
2064 
2065  if (!lease || !ctx.subnet_) {
2066  return;
2067  }
2068 
2069  // It is likely that the lease for which we're extending the lifetime doesn't
2070  // belong to the current but a sibling subnet.
2071  if (ctx.subnet_->getID() != lease->subnet_id_) {
2072  SharedNetwork6Ptr network;
2073  ctx.subnet_->getSharedNetwork(network);
2074  if (network) {
2075  Subnet6Ptr subnet = network->getSubnet(SubnetID(lease->subnet_id_));
2076  // Found the actual subnet this lease belongs to. Stick to this
2077  // subnet.
2078  if (subnet) {
2079  ctx.subnet_ = subnet;
2080  }
2081  }
2082  }
2083 
2084  // If the lease is not global and it is either out of range (NAs only) or it
2085  // is not permitted by subnet client classification, delete it.
2086  if (!(ctx.hasGlobalReservation(makeIPv6Resrv(*lease))) &&
2087  (((lease->type_ != Lease::TYPE_PD) && !ctx.subnet_->inRange(lease->addr_)) ||
2088  !ctx.subnet_->clientSupported(ctx.query_->getClasses()))) {
2089  // Oh dear, the lease is no longer valid. We need to get rid of it.
2090 
2091  // Remove this lease from LeaseMgr
2092  if (!LeaseMgrFactory::instance().deleteLease(lease)) {
2093  // Concurrent delete performed by other instance which should
2094  // properly handle dns and stats updates.
2095  return;
2096  }
2097 
2098  // Updated DNS if required.
2099  queueNCR(CHG_REMOVE, lease);
2100 
2101  // Need to decrease statistic for assigned addresses.
2102  StatsMgr::instance().addValue(
2103  StatsMgr::generateName("subnet", ctx.subnet_->getID(), "assigned-nas"),
2104  static_cast<int64_t>(-1));
2105 
2106  // Add it to the removed leases list.
2107  ctx.currentIA().old_leases_.push_back(lease);
2108 
2109  return;
2110  }
2111 
2114  .arg(ctx.query_->getLabel())
2115  .arg(lease->toText());
2116 
2117  // Keep the old data in case the callout tells us to skip update.
2118  Lease6Ptr old_data(new Lease6(*lease));
2119 
2120  bool changed = false;
2121 
2122  // Calculate life times.
2123  uint32_t current_preferred_lft = lease->preferred_lft_;
2124  getLifetimes6(ctx, lease->preferred_lft_, lease->valid_lft_);
2125 
2126  // If either has changed set the changed flag.
2127  if ((lease->preferred_lft_ != current_preferred_lft) ||
2128  (lease->valid_lft_ != lease->current_valid_lft_)) {
2129  changed = true;
2130  }
2131 
2132  lease->cltt_ = time(NULL);
2133  if ((lease->fqdn_fwd_ != ctx.fwd_dns_update_) ||
2134  (lease->fqdn_rev_ != ctx.rev_dns_update_) ||
2135  (lease->hostname_ != ctx.hostname_)) {
2136  changed = true;
2137  lease->hostname_ = ctx.hostname_;
2138  lease->fqdn_fwd_ = ctx.fwd_dns_update_;
2139  lease->fqdn_rev_ = ctx.rev_dns_update_;
2140  }
2141  if ((!ctx.hwaddr_ && lease->hwaddr_) ||
2142  (ctx.hwaddr_ &&
2143  (!lease->hwaddr_ || (*ctx.hwaddr_ != *lease->hwaddr_)))) {
2144  changed = true;
2145  lease->hwaddr_ = ctx.hwaddr_;
2146  }
2147  if (lease->state_ != Lease::STATE_DEFAULT) {
2148  changed = true;
2149  lease->state_ = Lease::STATE_DEFAULT;
2150  }
2153  .arg(ctx.query_->getLabel())
2154  .arg(lease->toText());
2155 
2156  bool skip = false;
2157  // Get the callouts specific for the processed message and execute them.
2158  int hook_point = ctx.query_->getType() == DHCPV6_RENEW ?
2159  Hooks.hook_index_lease6_renew_ : Hooks.hook_index_lease6_rebind_;
2160  if (HooksManager::calloutsPresent(hook_point)) {
2161  CalloutHandlePtr callout_handle = ctx.callout_handle_;
2162 
2163  // Use the RAII wrapper to make sure that the callout handle state is
2164  // reset when this object goes out of scope. All hook points must do
2165  // it to prevent possible circular dependency between the callout
2166  // handle and its arguments.
2167  ScopedCalloutHandleState callout_handle_state(callout_handle);
2168 
2169  // Enable copying options from the packet within hook library.
2170  ScopedEnableOptionsCopy<Pkt6> query6_options_copy(ctx.query_);
2171 
2172  // Pass the original packet
2173  callout_handle->setArgument("query6", ctx.query_);
2174 
2175  // Pass the lease to be updated
2176  callout_handle->setArgument("lease6", lease);
2177 
2178  // Pass the IA option to be sent in response
2179  if (lease->type_ == Lease::TYPE_NA) {
2180  callout_handle->setArgument("ia_na", ctx.currentIA().ia_rsp_);
2181  } else {
2182  callout_handle->setArgument("ia_pd", ctx.currentIA().ia_rsp_);
2183  }
2184 
2185  // Call all installed callouts
2186  HooksManager::callCallouts(hook_point, *callout_handle);
2187 
2188  // Callouts decided to skip the next processing step. The next
2189  // processing step would actually renew the lease, so skip at this
2190  // stage means "keep the old lease as it is".
2191  if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
2192  skip = true;
2195  .arg(ctx.query_->getName());
2196  }
2197 
2199  }
2200 
2201  if (!skip) {
2202  bool update_stats = false;
2203 
2204  // If the lease we're renewing has expired, we need to reclaim this
2205  // lease before we can renew it.
2206  if (old_data->expired()) {
2207  reclaimExpiredLease(old_data, ctx.callout_handle_);
2208 
2209  // If the lease is in the current subnet we need to account
2210  // for the re-assignment of the lease.
2211  if (ctx.subnet_->inPool(ctx.currentIA().type_, old_data->addr_)) {
2212  update_stats = true;
2213  }
2214  changed = true;
2215  }
2216 
2217  // @todo should we call storeLease6ExtendedInfo() here ?
2218  updateLease6ExtendedInfo(lease, ctx);
2219  if (lease->extended_info_action_ == Lease6::ACTION_UPDATE) {
2220  changed = true;
2221  }
2222 
2223  // Try to reuse the lease.
2224  if (!changed) {
2225  setLeaseReusable(lease, current_preferred_lft, ctx);
2226  }
2227 
2228  // Now that the lease has been reclaimed, we can go ahead and update it
2229  // in the lease database.
2230  if (lease->reuseable_valid_lft_ == 0) {
2232  }
2233 
2234  if (update_stats) {
2235  StatsMgr::instance().addValue(
2236  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
2237  ctx.currentIA().type_ == Lease::TYPE_NA ?
2238  "assigned-nas" : "assigned-pds"),
2239  static_cast<int64_t>(1));
2240  StatsMgr::instance().addValue(
2241  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
2242  ctx.currentIA().type_ == Lease::TYPE_NA ?
2243  "cumulative-assigned-nas" :
2244  "cumulative-assigned-pds"),
2245  static_cast<int64_t>(1));
2246  StatsMgr::instance().addValue(ctx.currentIA().type_ == Lease::TYPE_NA ?
2247  "cumulative-assigned-nas" :
2248  "cumulative-assigned-pds",
2249  static_cast<int64_t>(1));
2250  }
2251 
2252  } else {
2253  // Copy back the original date to the lease. For MySQL it doesn't make
2254  // much sense, but for memfile, the Lease6Ptr points to the actual lease
2255  // in memfile, so the actual update is performed when we manipulate
2256  // fields of returned Lease6Ptr, the actual updateLease6() is no-op.
2257  *lease = *old_data;
2258  }
2259 
2260  // Add the old lease to the changed lease list. This allows the server
2261  // to make decisions regarding DNS updates.
2262  ctx.currentIA().changed_leases_.push_back(old_data);
2263 }
2264 
2266 AllocEngine::updateLeaseData(ClientContext6& ctx, const Lease6Collection& leases) {
2267  Lease6Collection updated_leases;
2268  for (Lease6Collection::const_iterator lease_it = leases.begin();
2269  lease_it != leases.end(); ++lease_it) {
2270  Lease6Ptr lease(new Lease6(**lease_it));
2271  if (ctx.currentIA().isNewResource(lease->addr_, lease->prefixlen_)) {
2272  // This lease was just created so is already up to date.
2273  updated_leases.push_back(lease);
2274  continue;
2275  }
2276 
2277  lease->reuseable_valid_lft_ = 0;
2278  lease->fqdn_fwd_ = ctx.fwd_dns_update_;
2279  lease->fqdn_rev_ = ctx.rev_dns_update_;
2280  lease->hostname_ = ctx.hostname_;
2281  uint32_t current_preferred_lft = lease->preferred_lft_;
2282  if (lease->valid_lft_ == 0) {
2283  // The lease was expired by a release: reset zero lifetimes.
2284  getLifetimes6(ctx, lease->preferred_lft_, lease->valid_lft_);
2285  }
2286  if (!ctx.fake_allocation_) {
2287  bool update_stats = false;
2288 
2289  if (lease->state_ == Lease::STATE_EXPIRED_RECLAIMED) {
2290  // Transition lease state to default (aka assigned)
2291  lease->state_ = Lease::STATE_DEFAULT;
2292 
2293  // If the lease is in the current subnet we need to account
2294  // for the re-assignment of the lease.
2295  if (inAllowedPool(ctx, ctx.currentIA().type_,
2296  lease->addr_, true)) {
2297  update_stats = true;
2298  }
2299  }
2300 
2301  bool fqdn_changed = ((lease->type_ != Lease::TYPE_PD) &&
2302  !(lease->hasIdenticalFqdn(**lease_it)));
2303 
2304  lease->cltt_ = time(NULL);
2305  if (!fqdn_changed) {
2306  setLeaseReusable(lease, current_preferred_lft, ctx);
2307  }
2308  if (lease->reuseable_valid_lft_ == 0) {
2309  ctx.currentIA().changed_leases_.push_back(*lease_it);
2311  }
2312 
2313  if (update_stats) {
2314  StatsMgr::instance().addValue(
2315  StatsMgr::generateName("subnet", lease->subnet_id_,
2316  ctx.currentIA().type_ == Lease::TYPE_NA ?
2317  "assigned-nas" : "assigned-pds"),
2318  static_cast<int64_t>(1));
2319  StatsMgr::instance().addValue(
2320  StatsMgr::generateName("subnet", lease->subnet_id_,
2321  ctx.currentIA().type_ == Lease::TYPE_NA ?
2322  "cumulative-assigned-nas" :
2323  "cumulative-assigned-pds"),
2324  static_cast<int64_t>(1));
2325  StatsMgr::instance().addValue(ctx.currentIA().type_ == Lease::TYPE_NA ?
2326  "cumulative-assigned-nas" :
2327  "cumulative-assigned-pds",
2328  static_cast<int64_t>(1));
2329  }
2330  }
2331 
2332  updated_leases.push_back(lease);
2333  }
2334 
2335  return (updated_leases);
2336 }
2337 
2338 void
2339 AllocEngine::reclaimExpiredLeases6(const size_t max_leases,
2340  const uint16_t timeout,
2341  const bool remove_lease,
2342  const uint16_t max_unwarned_cycles) {
2343 
2346  .arg(max_leases)
2347  .arg(timeout);
2348 
2349  try {
2350  reclaimExpiredLeases6Internal(max_leases, timeout, remove_lease,
2351  max_unwarned_cycles);
2352  } catch (const std::exception& ex) {
2355  .arg(ex.what());
2356  }
2357 }
2358 
2359 void
2361  const uint16_t timeout,
2362  const bool remove_lease,
2363  const uint16_t max_unwarned_cycles) {
2364 
2365  // Create stopwatch and automatically start it to measure the time
2366  // taken by the routine.
2367  util::Stopwatch stopwatch;
2368 
2369  LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
2370 
2371  // This value indicates if we have been able to deal with all expired
2372  // leases in this pass.
2373  bool incomplete_reclamation = false;
2374  Lease6Collection leases;
2375  // The value of 0 has a special meaning - reclaim all.
2376  if (max_leases > 0) {
2377  // If the value is non-zero, the caller has limited the number of
2378  // leases to reclaim. We obtain one lease more to see if there will
2379  // be still leases left after this pass.
2380  lease_mgr.getExpiredLeases6(leases, max_leases + 1);
2381  // There are more leases expired leases than we will process in this
2382  // pass, so we should mark it as an incomplete reclamation. We also
2383  // remove this extra lease (which we don't want to process anyway)
2384  // from the collection.
2385  if (leases.size() > max_leases) {
2386  leases.pop_back();
2387  incomplete_reclamation = true;
2388  }
2389 
2390  } else {
2391  // If there is no limitation on the number of leases to reclaim,
2392  // we will try to process all. Hence, we don't mark it as incomplete
2393  // reclamation just yet.
2394  lease_mgr.getExpiredLeases6(leases, max_leases);
2395  }
2396 
2397  // Do not initialize the callout handle until we know if there are any
2398  // lease6_expire callouts installed.
2399  CalloutHandlePtr callout_handle;
2400  if (!leases.empty() &&
2401  HooksManager::calloutsPresent(Hooks.hook_index_lease6_expire_)) {
2402  callout_handle = HooksManager::createCalloutHandle();
2403  }
2404 
2405  size_t leases_processed = 0;
2406  BOOST_FOREACH(Lease6Ptr lease, leases) {
2407 
2408  try {
2409  // Reclaim the lease.
2410  if (MultiThreadingMgr::instance().getMode()) {
2411  // The reclamation is exclusive of packet processing.
2412  WriteLockGuard exclusive(rw_mutex_);
2413 
2414  reclaimExpiredLease(lease, remove_lease, callout_handle);
2415  ++leases_processed;
2416  } else {
2417  reclaimExpiredLease(lease, remove_lease, callout_handle);
2418  ++leases_processed;
2419  }
2420 
2421  } catch (const std::exception& ex) {
2423  .arg(lease->addr_.toText())
2424  .arg(ex.what());
2425  }
2426 
2427  // Check if we have hit the timeout for running reclamation routine and
2428  // return if we have. We're checking it here, because we always want to
2429  // allow reclaiming at least one lease.
2430  if ((timeout > 0) && (stopwatch.getTotalMilliseconds() >= timeout)) {
2431  // Timeout. This will likely mean that we haven't been able to process
2432  // all leases we wanted to process. The reclamation pass will be
2433  // probably marked as incomplete.
2434  if (!incomplete_reclamation) {
2435  if (leases_processed < leases.size()) {
2436  incomplete_reclamation = true;
2437  }
2438  }
2439 
2442  .arg(timeout);
2443  break;
2444  }
2445  }
2446 
2447  // Stop measuring the time.
2448  stopwatch.stop();
2449 
2450  // Mark completion of the lease reclamation routine and present some stats.
2453  .arg(leases_processed)
2454  .arg(stopwatch.logFormatTotalDuration());
2455 
2456  // Check if this was an incomplete reclamation and increase the number of
2457  // consecutive incomplete reclamations.
2458  if (incomplete_reclamation) {
2459  ++incomplete_v6_reclamations_;
2460  // If the number of incomplete reclamations is beyond the threshold, we
2461  // need to issue a warning.
2462  if ((max_unwarned_cycles > 0) &&
2463  (incomplete_v6_reclamations_ > max_unwarned_cycles)) {
2465  .arg(max_unwarned_cycles);
2466  // We issued a warning, so let's now reset the counter.
2467  incomplete_v6_reclamations_ = 0;
2468  }
2469 
2470  } else {
2471  // This was a complete reclamation, so let's reset the counter.
2472  incomplete_v6_reclamations_ = 0;
2473 
2476  }
2477 }
2478 
2479 void
2483  .arg(secs);
2484 
2485  uint64_t deleted_leases = 0;
2486  try {
2487  // Try to delete leases from the lease database.
2488  LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
2489  deleted_leases = lease_mgr.deleteExpiredReclaimedLeases6(secs);
2490 
2491  } catch (const std::exception& ex) {
2493  .arg(ex.what());
2494  }
2495 
2498  .arg(deleted_leases);
2499 }
2500 
2501 void
2502 AllocEngine::reclaimExpiredLeases4(const size_t max_leases,
2503  const uint16_t timeout,
2504  const bool remove_lease,
2505  const uint16_t max_unwarned_cycles) {
2506 
2509  .arg(max_leases)
2510  .arg(timeout);
2511 
2512  try {
2513  reclaimExpiredLeases4Internal(max_leases, timeout, remove_lease,
2514  max_unwarned_cycles);
2515  } catch (const std::exception& ex) {
2518  .arg(ex.what());
2519  }
2520 }
2521 
2522 void
2524  const uint16_t timeout,
2525  const bool remove_lease,
2526  const uint16_t max_unwarned_cycles) {
2527 
2528  // Create stopwatch and automatically start it to measure the time
2529  // taken by the routine.
2530  util::Stopwatch stopwatch;
2531 
2532  LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
2533 
2534  // This value indicates if we have been able to deal with all expired
2535  // leases in this pass.
2536  bool incomplete_reclamation = false;
2537  Lease4Collection leases;
2538  // The value of 0 has a special meaning - reclaim all.
2539  if (max_leases > 0) {
2540  // If the value is non-zero, the caller has limited the number of
2541  // leases to reclaim. We obtain one lease more to see if there will
2542  // be still leases left after this pass.
2543  lease_mgr.getExpiredLeases4(leases, max_leases + 1);
2544  // There are more leases expired leases than we will process in this
2545  // pass, so we should mark it as an incomplete reclamation. We also
2546  // remove this extra lease (which we don't want to process anyway)
2547  // from the collection.
2548  if (leases.size() > max_leases) {
2549  leases.pop_back();
2550  incomplete_reclamation = true;
2551  }
2552 
2553  } else {
2554  // If there is no limitation on the number of leases to reclaim,
2555  // we will try to process all. Hence, we don't mark it as incomplete
2556  // reclamation just yet.
2557  lease_mgr.getExpiredLeases4(leases, max_leases);
2558  }
2559 
2560  // Do not initialize the callout handle until we know if there are any
2561  // lease4_expire callouts installed.
2562  CalloutHandlePtr callout_handle;
2563  if (!leases.empty() &&
2564  HooksManager::calloutsPresent(Hooks.hook_index_lease4_expire_)) {
2565  callout_handle = HooksManager::createCalloutHandle();
2566  }
2567 
2568  size_t leases_processed = 0;
2569  BOOST_FOREACH(Lease4Ptr lease, leases) {
2570 
2571  try {
2572  // Reclaim the lease.
2573  if (MultiThreadingMgr::instance().getMode()) {
2574  // The reclamation is exclusive of packet processing.
2575  WriteLockGuard exclusive(rw_mutex_);
2576 
2577  reclaimExpiredLease(lease, remove_lease, callout_handle);
2578  ++leases_processed;
2579  } else {
2580  reclaimExpiredLease(lease, remove_lease, callout_handle);
2581  ++leases_processed;
2582  }
2583 
2584  } catch (const std::exception& ex) {
2586  .arg(lease->addr_.toText())
2587  .arg(ex.what());
2588  }
2589 
2590  // Check if we have hit the timeout for running reclamation routine and
2591  // return if we have. We're checking it here, because we always want to
2592  // allow reclaiming at least one lease.
2593  if ((timeout > 0) && (stopwatch.getTotalMilliseconds() >= timeout)) {
2594  // Timeout. This will likely mean that we haven't been able to process
2595  // all leases we wanted to process. The reclamation pass will be
2596  // probably marked as incomplete.
2597  if (!incomplete_reclamation) {
2598  if (leases_processed < leases.size()) {
2599  incomplete_reclamation = true;
2600  }
2601  }
2602 
2605  .arg(timeout);
2606  break;
2607  }
2608  }
2609 
2610  // Stop measuring the time.
2611  stopwatch.stop();
2612 
2613  // Mark completion of the lease reclamation routine and present some stats.
2616  .arg(leases_processed)
2617  .arg(stopwatch.logFormatTotalDuration());
2618 
2619  // Check if this was an incomplete reclamation and increase the number of
2620  // consecutive incomplete reclamations.
2621  if (incomplete_reclamation) {
2622  ++incomplete_v4_reclamations_;
2623  // If the number of incomplete reclamations is beyond the threshold, we
2624  // need to issue a warning.
2625  if ((max_unwarned_cycles > 0) &&
2626  (incomplete_v4_reclamations_ > max_unwarned_cycles)) {
2628  .arg(max_unwarned_cycles);
2629  // We issued a warning, so let's now reset the counter.
2630  incomplete_v4_reclamations_ = 0;
2631  }
2632 
2633  } else {
2634  // This was a complete reclamation, so let's reset the counter.
2635  incomplete_v4_reclamations_ = 0;
2636 
2639  }
2640 }
2641 
2642 template<typename LeasePtrType>
2643 void
2644 AllocEngine::reclaimExpiredLease(const LeasePtrType& lease, const bool remove_lease,
2645  const CalloutHandlePtr& callout_handle) {
2646  reclaimExpiredLease(lease, remove_lease ? DB_RECLAIM_REMOVE : DB_RECLAIM_UPDATE,
2647  callout_handle);
2648 }
2649 
2650 template<typename LeasePtrType>
2651 void
2652 AllocEngine::reclaimExpiredLease(const LeasePtrType& lease,
2653  const CalloutHandlePtr& callout_handle) {
2654  // This variant of the method is used by the code which allocates or
2655  // renews leases. It may be the case that the lease has already been
2656  // reclaimed, so there is nothing to do.
2657  if (!lease->stateExpiredReclaimed()) {
2658  reclaimExpiredLease(lease, DB_RECLAIM_LEAVE_UNCHANGED, callout_handle);
2659  }
2660 }
2661 
2662 void
2663 AllocEngine::reclaimExpiredLease(const Lease6Ptr& lease,
2664  const DbReclaimMode& reclaim_mode,
2665  const CalloutHandlePtr& callout_handle) {
2666 
2669  .arg(Pkt6::makeLabel(lease->duid_, lease->hwaddr_))
2670  .arg(lease->addr_.toText())
2671  .arg(static_cast<int>(lease->prefixlen_));
2672 
2673  // The skip flag indicates if the callouts have taken responsibility
2674  // for reclaiming the lease. The callout will set this to true if
2675  // it reclaims the lease itself. In this case the reclamation routine
2676  // will not update DNS nor update the database.
2677  bool skipped = false;
2678  if (callout_handle) {
2679 
2680  // Use the RAII wrapper to make sure that the callout handle state is
2681  // reset when this object goes out of scope. All hook points must do
2682  // it to prevent possible circular dependency between the callout
2683  // handle and its arguments.
2684  ScopedCalloutHandleState callout_handle_state(callout_handle);
2685 
2686  callout_handle->deleteAllArguments();
2687  callout_handle->setArgument("lease6", lease);
2688  callout_handle->setArgument("remove_lease", reclaim_mode == DB_RECLAIM_REMOVE);
2689 
2690  HooksManager::callCallouts(Hooks.hook_index_lease6_expire_,
2691  *callout_handle);
2692 
2693  skipped = callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP;
2694  }
2695 
2698 
2699  if (!skipped) {
2700 
2701  // Generate removal name change request for D2, if required.
2702  // This will return immediately if the DNS wasn't updated
2703  // when the lease was created.
2704  queueNCR(CHG_REMOVE, lease);
2705 
2706  // Let's check if the lease that just expired is in DECLINED state.
2707  // If it is, we need to perform a couple extra steps.
2708  bool remove_lease = (reclaim_mode == DB_RECLAIM_REMOVE);
2709  if (lease->state_ == Lease::STATE_DECLINED) {
2710  // Do extra steps required for declined lease reclamation:
2711  // - call the recover hook
2712  // - bump decline-related stats
2713  // - log separate message
2714  // There's no point in keeping a declined lease after its
2715  // reclamation. A declined lease doesn't have any client
2716  // identifying information anymore. So we'll flag it for
2717  // removal unless the hook has set the skip flag.
2718  remove_lease = reclaimDeclined(lease);
2719  }
2720 
2721  if (reclaim_mode != DB_RECLAIM_LEAVE_UNCHANGED) {
2722  // Reclaim the lease - depending on the configuration, set the
2723  // expired-reclaimed state or simply remove it.
2724  LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
2725  reclaimLeaseInDatabase<Lease6Ptr>(lease, remove_lease,
2726  std::bind(&LeaseMgr::updateLease6,
2727  &lease_mgr, ph::_1));
2728  }
2729  }
2730 
2731  // Update statistics.
2732 
2733  // Decrease number of assigned leases.
2734  if (lease->type_ == Lease::TYPE_NA) {
2735  // IA_NA
2736  StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
2737  lease->subnet_id_,
2738  "assigned-nas"),
2739  int64_t(-1));
2740 
2741  } else if (lease->type_ == Lease::TYPE_PD) {
2742  // IA_PD
2743  StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
2744  lease->subnet_id_,
2745  "assigned-pds"),
2746  int64_t(-1));
2747 
2748  }
2749 
2750  // Increase total number of reclaimed leases.
2751  StatsMgr::instance().addValue("reclaimed-leases", int64_t(1));
2752 
2753  // Increase number of reclaimed leases for a subnet.
2754  StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
2755  lease->subnet_id_,
2756  "reclaimed-leases"),
2757  int64_t(1));
2758 }
2759 
2760 void
2761 AllocEngine::reclaimExpiredLease(const Lease4Ptr& lease,
2762  const DbReclaimMode& reclaim_mode,
2763  const CalloutHandlePtr& callout_handle) {
2764 
2767  .arg(Pkt4::makeLabel(lease->hwaddr_, lease->client_id_))
2768  .arg(lease->addr_.toText());
2769 
2770  // The skip flag indicates if the callouts have taken responsibility
2771  // for reclaiming the lease. The callout will set this to true if
2772  // it reclaims the lease itself. In this case the reclamation routine
2773  // will not update DNS nor update the database.
2774  bool skipped = false;
2775  if (callout_handle) {
2776 
2777  // Use the RAII wrapper to make sure that the callout handle state is
2778  // reset when this object goes out of scope. All hook points must do
2779  // it to prevent possible circular dependency between the callout
2780  // handle and its arguments.
2781  ScopedCalloutHandleState callout_handle_state(callout_handle);
2782 
2783  callout_handle->setArgument("lease4", lease);
2784  callout_handle->setArgument("remove_lease", reclaim_mode == DB_RECLAIM_REMOVE);
2785 
2786  HooksManager::callCallouts(Hooks.hook_index_lease4_expire_,
2787  *callout_handle);
2788 
2789  skipped = callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP;
2790  }
2791 
2794 
2795  if (!skipped) {
2796 
2797  // Generate removal name change request for D2, if required.
2798  // This will return immediately if the DNS wasn't updated
2799  // when the lease was created.
2800  queueNCR(CHG_REMOVE, lease);
2801  // Clear DNS fields so we avoid redundant removes.
2802  lease->hostname_.clear();
2803  lease->fqdn_fwd_ = false;
2804  lease->fqdn_rev_ = false;
2805 
2806  // Let's check if the lease that just expired is in DECLINED state.
2807  // If it is, we need to perform a couple extra steps.
2808  bool remove_lease = (reclaim_mode == DB_RECLAIM_REMOVE);
2809  if (lease->state_ == Lease::STATE_DECLINED) {
2810  // Do extra steps required for declined lease reclamation:
2811  // - call the recover hook
2812  // - bump decline-related stats
2813  // - log separate message
2814  // There's no point in keeping a declined lease after its
2815  // reclamation. A declined lease doesn't have any client
2816  // identifying information anymore. So we'll flag it for
2817  // removal unless the hook has set the skip flag.
2818  remove_lease = reclaimDeclined(lease);
2819  }
2820 
2821  if (reclaim_mode != DB_RECLAIM_LEAVE_UNCHANGED) {
2822  // Reclaim the lease - depending on the configuration, set the
2823  // expired-reclaimed state or simply remove it.
2824  LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
2825  reclaimLeaseInDatabase<Lease4Ptr>(lease, remove_lease,
2826  std::bind(&LeaseMgr::updateLease4,
2827  &lease_mgr, ph::_1));
2828  }
2829  }
2830 
2831  // Update statistics.
2832 
2833  // Decrease number of assigned addresses.
2834  StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
2835  lease->subnet_id_,
2836  "assigned-addresses"),
2837  int64_t(-1));
2838 
2839  // Increase total number of reclaimed leases.
2840  StatsMgr::instance().addValue("reclaimed-leases", int64_t(1));
2841 
2842  // Increase number of reclaimed leases for a subnet.
2843  StatsMgr::instance().addValue(StatsMgr::generateName("subnet",
2844  lease->subnet_id_,
2845  "reclaimed-leases"),
2846  int64_t(1));
2847 }
2848 
2849 void
2853  .arg(secs);
2854 
2855  uint64_t deleted_leases = 0;
2856  try {
2857  // Try to delete leases from the lease database.
2858  LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
2859  deleted_leases = lease_mgr.deleteExpiredReclaimedLeases4(secs);
2860 
2861  } catch (const std::exception& ex) {
2863  .arg(ex.what());
2864  }
2865 
2868  .arg(deleted_leases);
2869 }
2870 
2871 bool
2872 AllocEngine::reclaimDeclined(const Lease4Ptr& lease) {
2873  if (!lease || (lease->state_ != Lease::STATE_DECLINED) ) {
2874  return (true);
2875  }
2876 
2877  if (HooksManager::calloutsPresent(Hooks.hook_index_lease4_recover_)) {
2878  CalloutHandlePtr callout_handle = HooksManager::createCalloutHandle();
2879 
2880  // Use the RAII wrapper to make sure that the callout handle state is
2881  // reset when this object goes out of scope. All hook points must do
2882  // it to prevent possible circular dependency between the callout
2883  // handle and its arguments.
2884  ScopedCalloutHandleState callout_handle_state(callout_handle);
2885 
2886  // Pass necessary arguments
2887  callout_handle->setArgument("lease4", lease);
2888 
2889  // Call the callouts
2890  HooksManager::callCallouts(Hooks.hook_index_lease4_recover_, *callout_handle);
2891 
2892  // Callouts decided to skip the action. This means that the lease is not
2893  // assigned, so the client will get NoAddrAvail as a result. The lease
2894  // won't be inserted into the database.
2895  if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
2897  .arg(lease->addr_.toText());
2898  return (false);
2899  }
2900  }
2901 
2903  .arg(lease->addr_.toText())
2904  .arg(lease->valid_lft_);
2905 
2906  StatsMgr& stats_mgr = StatsMgr::instance();
2907 
2908  // Decrease subnet specific counter for currently declined addresses
2909  stats_mgr.addValue(StatsMgr::generateName("subnet", lease->subnet_id_,
2910  "declined-addresses"), static_cast<int64_t>(-1));
2911 
2912  // Decrease global counter for declined addresses
2913  stats_mgr.addValue("declined-addresses", static_cast<int64_t>(-1));
2914 
2915  stats_mgr.addValue("reclaimed-declined-addresses", static_cast<int64_t>(1));
2916 
2917  stats_mgr.addValue(StatsMgr::generateName("subnet", lease->subnet_id_,
2918  "reclaimed-declined-addresses"), static_cast<int64_t>(1));
2919 
2920  // Note that we do not touch assigned-addresses counters. Those are
2921  // modified in whatever code calls this method.
2922  return (true);
2923 }
2924 
2925 bool
2926 AllocEngine::reclaimDeclined(const Lease6Ptr& lease) {
2927  if (!lease || (lease->state_ != Lease::STATE_DECLINED) ) {
2928  return (true);
2929  }
2930 
2931  if (HooksManager::calloutsPresent(Hooks.hook_index_lease6_recover_)) {
2932  CalloutHandlePtr callout_handle = HooksManager::createCalloutHandle();
2933 
2934  // Use the RAII wrapper to make sure that the callout handle state is
2935  // reset when this object goes out of scope. All hook points must do
2936  // it to prevent possible circular dependency between the callout
2937  // handle and its arguments.
2938  ScopedCalloutHandleState callout_handle_state(callout_handle);
2939 
2940  // Pass necessary arguments
2941  callout_handle->setArgument("lease6", lease);
2942 
2943  // Call the callouts
2944  HooksManager::callCallouts(Hooks.hook_index_lease6_recover_, *callout_handle);
2945 
2946  // Callouts decided to skip the action. This means that the lease is not
2947  // assigned, so the client will get NoAddrAvail as a result. The lease
2948  // won't be inserted into the database.
2949  if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
2951  .arg(lease->addr_.toText());
2952  return (false);
2953  }
2954  }
2955 
2957  .arg(lease->addr_.toText())
2958  .arg(lease->valid_lft_);
2959 
2960  StatsMgr& stats_mgr = StatsMgr::instance();
2961 
2962  // Decrease subnet specific counter for currently declined addresses
2963  stats_mgr.addValue(StatsMgr::generateName("subnet", lease->subnet_id_,
2964  "declined-addresses"), static_cast<int64_t>(-1));
2965 
2966  // Decrease global counter for declined addresses
2967  stats_mgr.addValue("declined-addresses", static_cast<int64_t>(-1));
2968 
2969  stats_mgr.addValue("reclaimed-declined-addresses", static_cast<int64_t>(1));
2970 
2971  stats_mgr.addValue(StatsMgr::generateName("subnet", lease->subnet_id_,
2972  "reclaimed-declined-addresses"), static_cast<int64_t>(1));
2973 
2974  // Note that we do not touch assigned-nas counters. Those are
2975  // modified in whatever code calls this method.
2976 
2977  return (true);
2978 }
2979 
2980 void
2982  lease->relay_id_.clear();
2983  lease->remote_id_.clear();
2984  if (lease->getContext()) {
2985  lease->setContext(ElementPtr());
2986  }
2987 }
2988 
2989 void
2991  if (lease->getContext()) {
2992  lease->extended_info_action_ = Lease6::ACTION_DELETE;
2993  lease->setContext(ElementPtr());
2994  }
2995 }
2996 
2997 template<typename LeasePtrType>
2998 void AllocEngine::reclaimLeaseInDatabase(const LeasePtrType& lease,
2999  const bool remove_lease,
3000  const std::function<void (const LeasePtrType&)>&
3001  lease_update_fun) const {
3002 
3003  LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
3004 
3005  // Reclaim the lease - depending on the configuration, set the
3006  // expired-reclaimed state or simply remove it.
3007  if (remove_lease) {
3008  lease_mgr.deleteLease(lease);
3009  } else if (lease_update_fun) {
3010  // Clear FQDN information as we have already sent the
3011  // name change request to remove the DNS record.
3012  lease->reuseable_valid_lft_ = 0;
3013  lease->hostname_.clear();
3014  lease->fqdn_fwd_ = false;
3015  lease->fqdn_rev_ = false;
3016  lease->state_ = Lease::STATE_EXPIRED_RECLAIMED;
3018  lease_update_fun(lease);
3019 
3020  } else {
3021  return;
3022  }
3023 
3024  // Lease has been reclaimed.
3027  .arg(lease->addr_.toText());
3028 }
3029 
3030 std::string
3032  if (!subnet) {
3033  return("<empty subnet>");
3034  }
3035 
3036  SharedNetwork4Ptr network;
3037  subnet->getSharedNetwork(network);
3038  std::ostringstream ss;
3039  if (network) {
3040  ss << "shared-network: " << network->getName();
3041  } else {
3042  ss << "subnet id: " << subnet->getID();
3043  }
3044 
3045  return(ss.str());
3046 }
3047 
3048 
3049 } // namespace dhcp
3050 } // namespace isc
3051 
3052 // ##########################################################################
3053 // # DHCPv4 lease allocation code starts here.
3054 // ##########################################################################
3055 
3056 namespace {
3057 
3075 bool
3076 addressReserved(const IOAddress& address, const AllocEngine::ClientContext4& ctx) {
3077  // When out-of-pool flag is true the server may assume that all host
3078  // reservations are for addresses that do not belong to the dynamic pool.
3079  // Therefore, it can skip the reservation checks when dealing with in-pool
3080  // addresses.
3081  if (ctx.subnet_ && ctx.subnet_->getReservationsInSubnet() &&
3082  (!ctx.subnet_->getReservationsOutOfPool() ||
3083  !ctx.subnet_->inPool(Lease::TYPE_V4, address))) {
3084  // The global parameter ip-reservations-unique controls whether it is allowed
3085  // to specify multiple reservations for the same IP address or delegated prefix
3086  // or IP reservations must be unique. Some host backends do not support the
3087  // former, thus we can't always use getAll4 calls to get the reservations
3088  // for the given IP. When we're in the default mode, when IP reservations
3089  // are unique, we should call get4 (supported by all backends). If we're in
3090  // the mode in which non-unique reservations are allowed the backends which
3091  // don't support it are not used and we can safely call getAll4.
3092  ConstHostCollection hosts;
3093  if (CfgMgr::instance().getCurrentCfg()->getCfgDbAccess()->getIPReservationsUnique()) {
3094  // Reservations are unique. It is safe to call get4 to get the unique host.
3095  ConstHostPtr host = HostMgr::instance().get4(ctx.subnet_->getID(), address);
3096  if (host) {
3097  hosts.push_back(host);
3098  }
3099  } else {
3100  // Reservations can be non-unique. Need to get all reservations for that address.
3101  hosts = HostMgr::instance().getAll4(ctx.subnet_->getID(), address);
3102  }
3103 
3104  for (auto host : hosts) {
3105  for (const AllocEngine::IdentifierPair& id_pair : ctx.host_identifiers_) {
3106  // If we find the matching host we know that this address is reserved
3107  // for us and we can return immediately.
3108  if (id_pair.first == host->getIdentifierType() &&
3109  id_pair.second == host->getIdentifier()) {
3110  return (false);
3111  }
3112  }
3113  }
3114  // We didn't find a matching host. If there are any reservations it means that
3115  // address is reserved for another client or multiple clients. If there are
3116  // no reservations address is not reserved for another client.
3117  return (!hosts.empty());
3118  }
3119  return (false);
3120 }
3121 
3137 bool
3138 hasAddressReservation(AllocEngine::ClientContext4& ctx) {
3139  if (ctx.hosts_.empty()) {
3140  return (false);
3141  }
3142 
3143  // Fetch the globally reserved address if there is one.
3144  auto global_host = ctx.hosts_.find(SUBNET_ID_GLOBAL);
3145  auto global_host_address = ((global_host != ctx.hosts_.end() && global_host->second) ?
3146  global_host->second->getIPv4Reservation() :
3148 
3149  // Start with currently selected subnet.
3150  Subnet4Ptr subnet = ctx.subnet_;
3151  while (subnet) {
3152  // If global reservations are enabled for this subnet and there is
3153  // globally reserved address and that address is feasible for this
3154  // subnet, update the selected subnet and return true.
3155  if (subnet->getReservationsGlobal() &&
3156  (global_host_address != IOAddress::IPV4_ZERO_ADDRESS()) &&
3157  (subnet->inRange(global_host_address))) {
3158  ctx.subnet_ = subnet;
3159  return (true);
3160  }
3161 
3162  if (subnet->getReservationsInSubnet()) {
3163  auto host = ctx.hosts_.find(subnet->getID());
3164  // The out-of-pool flag indicates that no client should be assigned
3165  // reserved addresses from within the dynamic pool, and for that
3166  // reason look only for reservations that are outside the pools,
3167  // hence the inPool check.
3168  if (host != ctx.hosts_.end() && host->second) {
3169  auto reservation = host->second->getIPv4Reservation();
3170  if (!reservation.isV4Zero() &&
3171  (!subnet->getReservationsOutOfPool() ||
3172  !subnet->inPool(Lease::TYPE_V4, reservation))) {
3173  ctx.subnet_ = subnet;
3174  return (true);
3175  }
3176  }
3177  }
3178 
3179  // No address reservation found here, so let's try another subnet
3180  // within the same shared network.
3181  subnet = subnet->getNextSubnet(ctx.subnet_, ctx.query_->getClasses());
3182  }
3183 
3184  if (global_host_address != IOAddress::IPV4_ZERO_ADDRESS()) {
3187  .arg(ctx.currentHost()->getIPv4Reservation().toText())
3189  }
3190 
3191  return (false);
3192 }
3193 
3209 void findClientLease(AllocEngine::ClientContext4& ctx, Lease4Ptr& client_lease) {
3210  LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
3211 
3212  Subnet4Ptr original_subnet = ctx.subnet_;
3213 
3214  auto const& classes = ctx.query_->getClasses();
3215 
3216  // Client identifier is optional. First check if we can try to lookup
3217  // by client-id.
3218  bool try_clientid_lookup = (ctx.clientid_ &&
3219  SharedNetwork4::subnetsIncludeMatchClientId(original_subnet, classes));
3220 
3221  // If it is possible to use client identifier to try to find client's lease.
3222  if (try_clientid_lookup) {
3223  // Get all leases for this client identifier. When shared networks are
3224  // in use it is more efficient to make a single query rather than
3225  // multiple queries, one for each subnet.
3226  Lease4Collection leases_client_id = lease_mgr.getLease4(*ctx.clientid_);
3227 
3228  // Iterate over the subnets within the shared network to see if any client's
3229  // lease belongs to them.
3230  for (Subnet4Ptr subnet = original_subnet; subnet;
3231  subnet = subnet->getNextSubnet(original_subnet, classes)) {
3232 
3233  // If client identifier has been supplied and the server wasn't
3234  // explicitly configured to ignore client identifiers for this subnet
3235  // check if there is a lease within this subnet.
3236  if (subnet->getMatchClientId()) {
3237  for (auto l = leases_client_id.begin(); l != leases_client_id.end(); ++l) {
3238  if ((*l)->subnet_id_ == subnet->getID()) {
3239  // Lease found, so stick to this lease.
3240  client_lease = (*l);
3241  ctx.subnet_ = subnet;
3242  return;
3243  }
3244  }
3245  }
3246  }
3247  }
3248 
3249  // If no lease found using the client identifier, try the lookup using
3250  // the HW address.
3251  if (!client_lease && ctx.hwaddr_) {
3252 
3253  // Get all leases for this HW address.
3254  Lease4Collection leases_hw_address = lease_mgr.getLease4(*ctx.hwaddr_);
3255 
3256  for (Subnet4Ptr subnet = original_subnet; subnet;
3257  subnet = subnet->getNextSubnet(original_subnet, classes)) {
3258  ClientIdPtr client_id;
3259  if (subnet->getMatchClientId()) {
3260  client_id = ctx.clientid_;
3261  }
3262 
3263  // Try to find the lease that matches current subnet and belongs to
3264  // this client, so both HW address and client identifier match.
3265  for (Lease4Collection::const_iterator client_lease_it = leases_hw_address.begin();
3266  client_lease_it != leases_hw_address.end(); ++client_lease_it) {
3267  Lease4Ptr existing_lease = *client_lease_it;
3268  if ((existing_lease->subnet_id_ == subnet->getID()) &&
3269  existing_lease->belongsToClient(ctx.hwaddr_, client_id)) {
3270  // Found the lease of this client, so return it.
3271  client_lease = existing_lease;
3272  // We got a lease but the subnet it belongs to may differ from
3273  // the original subnet. Let's now stick to this subnet.
3274  ctx.subnet_ = subnet;
3275  return;
3276  }
3277  }
3278  }
3279  }
3280 }
3281 
3294 bool
3295 inAllowedPool(AllocEngine::ClientContext4& ctx, const IOAddress& address) {
3296  // If the subnet belongs to a shared network we will be iterating
3297  // over the subnets that belong to this shared network.
3298  Subnet4Ptr current_subnet = ctx.subnet_;
3299  auto const& classes = ctx.query_->getClasses();
3300 
3301  while (current_subnet) {
3302  if (current_subnet->inPool(Lease::TYPE_V4, address, classes)) {
3303  // We found a subnet that this address belongs to, so it
3304  // seems that this subnet is the good candidate for allocation.
3305  // Let's update the selected subnet.
3306  ctx.subnet_ = current_subnet;
3307  return (true);
3308  }
3309 
3310  current_subnet = current_subnet->getNextSubnet(ctx.subnet_, classes);
3311  }
3312 
3313  return (false);
3314 }
3315 
3316 } // namespace
3317 
3318 namespace isc {
3319 namespace dhcp {
3320 
3323  subnet_(), clientid_(), hwaddr_(),
3324  requested_address_(IOAddress::IPV4_ZERO_ADDRESS()),
3325  fwd_dns_update_(false), rev_dns_update_(false),
3327  old_lease_(), new_lease_(), hosts_(), conflicting_lease_(),
3328  query_(), host_identifiers_(), unknown_requested_addr_(false),
3329  ddns_params_() {
3330 }
3331 
3333  const ClientIdPtr& clientid,
3334  const HWAddrPtr& hwaddr,
3335  const asiolink::IOAddress& requested_addr,
3336  const bool fwd_dns_update,
3337  const bool rev_dns_update,
3338  const std::string& hostname,
3339  const bool fake_allocation)
3341  subnet_(subnet), clientid_(clientid), hwaddr_(hwaddr),
3342  requested_address_(requested_addr),
3343  fwd_dns_update_(fwd_dns_update), rev_dns_update_(rev_dns_update),
3344  hostname_(hostname), callout_handle_(),
3345  fake_allocation_(fake_allocation), old_lease_(), new_lease_(),
3347  ddns_params_(new DdnsParams()) {
3348 
3349  // Initialize host identifiers.
3350  if (hwaddr) {
3351  addHostIdentifier(Host::IDENT_HWADDR, hwaddr->hwaddr_);
3352  }
3353 }
3354 
3357  if (subnet_ && subnet_->getReservationsInSubnet()) {
3358  auto host = hosts_.find(subnet_->getID());
3359  if (host != hosts_.cend()) {
3360  return (host->second);
3361  }
3362  }
3363 
3364  return (globalHost());
3365 }
3366 
3369  if (subnet_ && subnet_->getReservationsGlobal()) {
3370  auto host = hosts_.find(SUBNET_ID_GLOBAL);
3371  if (host != hosts_.cend()) {
3372  return (host->second);
3373  }
3374  }
3375 
3376  return (ConstHostPtr());
3377 }
3378 
3381  // We already have it return it unless the context subnet has changed.
3382  if (ddns_params_ && subnet_ && (subnet_->getID() == ddns_params_->getSubnetId())) {
3383  return (ddns_params_);
3384  }
3385 
3386  // Doesn't exist yet or is stale, (re)create it.
3387  if (subnet_) {
3388  ddns_params_ = CfgMgr::instance().getCurrentCfg()->getDdnsParams(subnet_);
3389  return (ddns_params_);
3390  }
3391 
3392  // Asked for it without a subnet? This case really shouldn't occur but
3393  // for now let's return an instance with default values.
3394  return (DdnsParamsPtr(new DdnsParams()));
3395 }
3396 
3397 Lease4Ptr
3399  // The NULL pointer indicates that the old lease didn't exist. It may
3400  // be later set to non NULL value if existing lease is found in the
3401  // database.
3402  ctx.old_lease_.reset();
3403  ctx.new_lease_.reset();
3404 
3405  // Before we start allocation process, we need to make sure that the
3406  // selected subnet is allowed for this client. If not, we'll try to
3407  // use some other subnet within the shared network. If there are no
3408  // subnets allowed for this client within the shared network, we
3409  // can't allocate a lease.
3410  Subnet4Ptr subnet = ctx.subnet_;
3411  auto const& classes = ctx.query_->getClasses();
3412  if (subnet && !subnet->clientSupported(classes)) {
3413  ctx.subnet_ = subnet->getNextSubnet(subnet, classes);
3414  }
3415 
3416  try {
3417  if (!ctx.subnet_) {
3418  isc_throw(BadValue, "Can't allocate IPv4 address without subnet");
3419  }
3420 
3421  if (!ctx.hwaddr_) {
3422  isc_throw(BadValue, "HWAddr must be defined");
3423  }
3424 
3425  if (ctx.fake_allocation_) {
3426  return (discoverLease4(ctx));
3427 
3428  } else {
3429  ctx.new_lease_ = requestLease4(ctx);
3430  }
3431 
3432  } catch (const isc::Exception& e) {
3433  // Some other error, return an empty lease.
3435  .arg(ctx.query_->getLabel())
3436  .arg(e.what());
3437  }
3438 
3439  return (ctx.new_lease_);
3440 }
3441 
3442 void
3444  // If there is no subnet, there is nothing to do.
3445  if (!ctx.subnet_) {
3446  return;
3447  }
3448 
3449  auto subnet = ctx.subnet_;
3450 
3451  // If already done just return.
3453  !subnet->getReservationsInSubnet()) {
3454  return;
3455  }
3456 
3457  // @todo: This code can be trivially optimized.
3459  subnet->getReservationsGlobal()) {
3460  ConstHostPtr ghost = findGlobalReservation(ctx);
3461  if (ghost) {
3462  ctx.hosts_[SUBNET_ID_GLOBAL] = ghost;
3463 
3464  // If we had only to fetch global reservations it is done.
3465  if (!subnet->getReservationsInSubnet()) {
3466  return;
3467  }
3468  }
3469  }
3470 
3471  std::map<SubnetID, ConstHostPtr> host_map;
3472  SharedNetwork4Ptr network;
3473  subnet->getSharedNetwork(network);
3474 
3475  // If the subnet belongs to a shared network it is usually going to be
3476  // more efficient to make a query for all reservations for a particular
3477  // client rather than a query for each subnet within this shared network.
3478  // The only case when it is going to be less efficient is when there are
3479  // more host identifier types in use than subnets within a shared network.
3480  // As it breaks RADIUS use of host caching this can be disabled by the
3481  // host manager.
3482  const bool use_single_query = network &&
3484  (network->getAllSubnets()->size() > ctx.host_identifiers_.size());
3485 
3486  if (use_single_query) {
3487  for (const IdentifierPair& id_pair : ctx.host_identifiers_) {
3488  ConstHostCollection hosts = HostMgr::instance().getAll(id_pair.first,
3489  &id_pair.second[0],
3490  id_pair.second.size());
3491  // Store the hosts in the temporary map, because some hosts may
3492  // belong to subnets outside of the shared network. We'll need
3493  // to eliminate them.
3494  for (auto host = hosts.begin(); host != hosts.end(); ++host) {
3495  if ((*host)->getIPv4SubnetID() != SUBNET_ID_GLOBAL) {
3496  host_map[(*host)->getIPv4SubnetID()] = *host;
3497  }
3498  }
3499  }
3500  }
3501 
3502  auto const& classes = ctx.query_->getClasses();
3503  // We can only search for the reservation if a subnet has been selected.
3504  while (subnet) {
3505 
3506  // Only makes sense to get reservations if the client has access
3507  // to the class and host reservations are enabled for this subnet.
3508  if (subnet->clientSupported(classes) && subnet->getReservationsInSubnet()) {
3509  // Iterate over configured identifiers in the order of preference
3510  // and try to use each of them to search for the reservations.
3511  if (use_single_query) {
3512  if (host_map.count(subnet->getID()) > 0) {
3513  ctx.hosts_[subnet->getID()] = host_map[subnet->getID()];
3514  }
3515  } else {
3516  for (const IdentifierPair& id_pair : ctx.host_identifiers_) {
3517  // Attempt to find a host using a specified identifier.
3518  ConstHostPtr host = HostMgr::instance().get4(subnet->getID(),
3519  id_pair.first,
3520  &id_pair.second[0],
3521  id_pair.second.size());
3522  // If we found matching host for this subnet.
3523  if (host) {
3524  ctx.hosts_[subnet->getID()] = host;
3525  break;
3526  }
3527  }
3528  }
3529  }
3530 
3531  // We need to get to the next subnet if this is a shared network. If it
3532  // is not (a plain subnet), getNextSubnet will return NULL and we're
3533  // done here.
3534  subnet = subnet->getNextSubnet(ctx.subnet_, classes);
3535  }
3536 }
3537 
3540  ConstHostPtr host;
3541  for (const IdentifierPair& id_pair : ctx.host_identifiers_) {
3542  // Attempt to find a host using a specified identifier.
3543  host = HostMgr::instance().get4(SUBNET_ID_GLOBAL, id_pair.first,
3544  &id_pair.second[0], id_pair.second.size());
3545 
3546  // If we found matching global host we're done.
3547  if (host) {
3548  break;
3549  }
3550  }
3551 
3552  return (host);
3553 }
3554 
3555 Lease4Ptr
3556 AllocEngine::discoverLease4(AllocEngine::ClientContext4& ctx) {
3557  // Find an existing lease for this client. This function will return null
3558  // if there is a conflict with existing lease and the allocation should
3559  // not be continued.
3560  Lease4Ptr client_lease;
3561  findClientLease(ctx, client_lease);
3562 
3563  // new_lease will hold the pointer to the lease that we will offer to the
3564  // caller.
3565  Lease4Ptr new_lease;
3566 
3567  CalloutHandle::CalloutNextStep callout_status = CalloutHandle::NEXT_STEP_CONTINUE;
3568 
3569  // Check if there is a reservation for the client. If there is, we want to
3570  // assign the reserved address, rather than any other one.
3571  if (hasAddressReservation(ctx)) {
3572 
3575  .arg(ctx.query_->getLabel())
3576  .arg(ctx.currentHost()->getIPv4Reservation().toText());
3577 
3578  // If the client doesn't have a lease or the leased address is different
3579  // than the reserved one then let's try to allocate the reserved address.
3580  // Otherwise the address that the client has is the one for which it
3581  // has a reservation, so just renew it.
3582  if (!client_lease || (client_lease->addr_ != ctx.currentHost()->getIPv4Reservation())) {
3583  // The call below will return a pointer to the lease for the address
3584  // reserved to this client, if the lease is available, i.e. is not
3585  // currently assigned to any other client.
3586  // Note that we don't remove the existing client's lease at this point
3587  // because this is not a real allocation, we just offer what we can
3588  // allocate in the DHCPREQUEST time.
3589  new_lease = allocateOrReuseLease4(ctx.currentHost()->getIPv4Reservation(), ctx,
3590  callout_status);
3591  if (!new_lease) {
3593  .arg(ctx.query_->getLabel())
3594  .arg(ctx.currentHost()->getIPv4Reservation().toText())
3595  .arg(ctx.conflicting_lease_ ? ctx.conflicting_lease_->toText() :
3596  "(no lease info)");
3597  StatsMgr::instance().addValue(StatsMgr::generateName(
3598  "subnet",
3599  ctx.conflicting_lease_->subnet_id_,
3600  "v4-reservation-conflicts"),
3601  static_cast<int64_t>(1));
3602  StatsMgr::instance().addValue("v4-reservation-conflicts",
3603  static_cast<int64_t>(1));
3604  }
3605 
3606  } else {
3607  new_lease = renewLease4(client_lease, ctx);
3608  }
3609  }
3610 
3611  // Client does not have a reservation or the allocation of the reserved
3612  // address has failed, probably because the reserved address is in use
3613  // by another client. If the client has a lease, we will check if we can
3614  // offer this lease to the client. The lease can't be offered in the
3615  // situation when it is reserved for another client or when the address
3616  // is not in the dynamic pool. The former may be the result of adding the
3617  // new reservation for the address used by this client. The latter may
3618  // be due to the client using the reserved out-of-the pool address, for
3619  // which the reservation has just been removed.
3620  if (!new_lease && client_lease && inAllowedPool(ctx, client_lease->addr_) &&
3621  !addressReserved(client_lease->addr_, ctx)) {
3622 
3625  .arg(ctx.query_->getLabel());
3626 
3627  new_lease = renewLease4(client_lease, ctx);
3628  }
3629 
3630  // The client doesn't have any lease or the lease can't be offered
3631  // because it is either reserved for some other client or the
3632  // address is not in the dynamic pool.
3633  // Let's use the client's hint (requested IP address), if the client
3634  // has provided it, and try to offer it. This address must not be
3635  // reserved for another client, and must be in the range of the
3636  // dynamic pool.
3637  if (!new_lease && !ctx.requested_address_.isV4Zero() &&
3638  inAllowedPool(ctx, ctx.requested_address_) &&
3639  !addressReserved(ctx.requested_address_, ctx)) {
3640 
3643  .arg(ctx.requested_address_.toText())
3644  .arg(ctx.query_->getLabel());
3645 
3646  new_lease = allocateOrReuseLease4(ctx.requested_address_, ctx,
3647  callout_status);
3648  }
3649 
3650  // The allocation engine failed to allocate all of the candidate
3651  // addresses. We will now use the allocator to pick the address
3652  // from the dynamic pool.
3653  if (!new_lease) {
3654 
3657  .arg(ctx.query_->getLabel());
3658 
3659  new_lease = allocateUnreservedLease4(ctx);
3660  }
3661 
3662  // Some of the methods like reuseExpiredLease4 may set the old lease to point
3663  // to the lease which they remove/override. If it is not set, but we have
3664  // found that the client has the lease the client's lease is the one
3665  // to return as an old lease.
3666  if (!ctx.old_lease_ && client_lease) {
3667  ctx.old_lease_ = client_lease;
3668  }
3669 
3670  return (new_lease);
3671 }
3672 
3673 Lease4Ptr
3674 AllocEngine::requestLease4(AllocEngine::ClientContext4& ctx) {
3675  // Find an existing lease for this client. This function will return null
3676  // if there is a conflict with existing lease and the allocation should
3677  // not be continued.
3678  Lease4Ptr client_lease;
3679  findClientLease(ctx, client_lease);
3680 
3681  // When the client sends the DHCPREQUEST, it should always specify the
3682  // address which it is requesting or renewing. That is, the client should
3683  // either use the requested IP address option or set the ciaddr. However,
3684  // we try to be liberal and allow the clients to not specify an address
3685  // in which case the allocation engine will pick a suitable address
3686  // for the client.
3687  if (!ctx.requested_address_.isV4Zero()) {
3688  // If the client has specified an address, make sure this address
3689  // is not reserved for another client. If it is, stop here because
3690  // we can't allocate this address.
3691  if (addressReserved(ctx.requested_address_, ctx)) {
3692 
3695  .arg(ctx.query_->getLabel())
3696  .arg(ctx.requested_address_.toText());
3697 
3698  return (Lease4Ptr());
3699  }
3700 
3701  } else if (hasAddressReservation(ctx)) {
3702  // The client hasn't specified an address to allocate, so the
3703  // allocation engine needs to find an appropriate address.
3704  // If there is a reservation for the client, let's try to
3705  // allocate the reserved address.
3706  ctx.requested_address_ = ctx.currentHost()->getIPv4Reservation();
3707 
3710  .arg(ctx.query_->getLabel())
3711  .arg(ctx.requested_address_.toText());
3712  }
3713 
3714  if (!ctx.requested_address_.isV4Zero()) {
3715  // There is a specific address to be allocated. Let's find out if
3716  // the address is in use.
3718  // If the address is in use (allocated and not expired), we check
3719  // if the address is in use by our client or another client.
3720  // If it is in use by another client, the address can't be
3721  // allocated.
3722  if (existing && !existing->expired() &&
3723  !existing->belongsToClient(ctx.hwaddr_, ctx.subnet_->getMatchClientId() ?
3724  ctx.clientid_ : ClientIdPtr())) {
3725 
3728  .arg(ctx.query_->getLabel())
3729  .arg(ctx.requested_address_.toText());
3730 
3731  return (Lease4Ptr());
3732  }
3733 
3734  // If the client has a reservation but it is requesting a different
3735  // address it is possible that the client was offered this different
3736  // address because the reserved address is in use. We will have to
3737  // check if the address is in use.
3738  if (hasAddressReservation(ctx) &&
3739  (ctx.currentHost()->getIPv4Reservation() != ctx.requested_address_)) {
3740  existing =
3741  LeaseMgrFactory::instance().getLease4(ctx.currentHost()->getIPv4Reservation());
3742  // If the reserved address is not in use, i.e. the lease doesn't
3743  // exist or is expired, and the client is requesting a different
3744  // address, return NULL. The client should go back to the
3745  // DHCPDISCOVER and the reserved address will be offered.
3746  if (!existing || existing->expired()) {
3747 
3750  .arg(ctx.query_->getLabel())
3751  .arg(ctx.currentHost()->getIPv4Reservation().toText())
3752  .arg(ctx.requested_address_.toText());
3753 
3754  return (Lease4Ptr());
3755  }
3756  }
3757 
3758  // The use of the out-of-pool addresses is only allowed when the requested
3759  // address is reserved for the client. If the address is not reserved one
3760  // and it doesn't belong to the dynamic pool, do not allocate it.
3761  if ((!hasAddressReservation(ctx) ||
3762  (ctx.currentHost()->getIPv4Reservation() != ctx.requested_address_)) &&
3763  !inAllowedPool(ctx, ctx.requested_address_)) {
3764 
3767  .arg(ctx.query_->getLabel())
3768  .arg(ctx.requested_address_);
3769 
3770  ctx.unknown_requested_addr_ = true;
3771  return (Lease4Ptr());
3772  }
3773  }
3774 
3775  // We have gone through all the checks, so we can now allocate the address
3776  // for the client.
3777 
3778  // If the client is requesting an address which is assigned to the client
3779  // let's just renew this address. Also, renew this address if the client
3780  // doesn't request any specific address.
3781  // Added extra checks: the address is reserved for this client or belongs
3782  // to the dynamic pool for the case the pool class has changed before the
3783  // request.
3784  if (client_lease) {
3785  if (((client_lease->addr_ == ctx.requested_address_) ||
3786  ctx.requested_address_.isV4Zero()) &&
3787  ((hasAddressReservation(ctx) &&
3788  (ctx.currentHost()->getIPv4Reservation() == ctx.requested_address_)) ||
3789  inAllowedPool(ctx, client_lease->addr_))) {
3790 
3793  .arg(ctx.query_->getLabel())
3794  .arg(ctx.requested_address_);
3795 
3796  return (renewLease4(client_lease, ctx));
3797  }
3798  }
3799 
3800  // new_lease will hold the pointer to the allocated lease if we allocate
3801  // successfully.
3802  Lease4Ptr new_lease;
3803 
3804  // The client doesn't have the lease or it is requesting an address
3805  // which it doesn't have. Let's try to allocate the requested address.
3806  if (!ctx.requested_address_.isV4Zero()) {
3807 
3810  .arg(ctx.query_->getLabel())
3811  .arg(ctx.requested_address_.toText());
3812 
3813  // The call below will return a pointer to the lease allocated
3814  // for the client if there is no lease for the requested address,
3815  // or the existing lease has expired. If the allocation fails,
3816  // e.g. because the lease is in use, we will return NULL to
3817  // indicate that we were unable to allocate the lease.
3818  CalloutHandle::CalloutNextStep callout_status = CalloutHandle::NEXT_STEP_CONTINUE;
3819  new_lease = allocateOrReuseLease4(ctx.requested_address_, ctx,
3820  callout_status);
3821 
3822  } else {
3823 
3826  .arg(ctx.query_->getLabel());
3827 
3828  // We will only get here if the client didn't specify which
3829  // address it wanted to be allocated. The allocation engine will
3830  // to pick the address from the dynamic pool.
3831  new_lease = allocateUnreservedLease4(ctx);
3832  }
3833 
3834  // If we allocated the lease for the client, but the client already had a
3835  // lease, we will need to return the pointer to the previous lease and
3836  // the previous lease needs to be removed from the lease database.
3837  if (new_lease && client_lease) {
3838  ctx.old_lease_ = Lease4Ptr(new Lease4(*client_lease));
3839 
3842  .arg(ctx.query_->getLabel())
3843  .arg(client_lease->addr_.toText());
3844 
3845  if (LeaseMgrFactory::instance().deleteLease(client_lease)) {
3846  // Need to decrease statistic for assigned addresses.
3847  StatsMgr::instance().addValue(
3848  StatsMgr::generateName("subnet", client_lease->subnet_id_,
3849  "assigned-addresses"),
3850  static_cast<int64_t>(-1));
3851  }
3852  }
3853 
3854  // Return the allocated lease or NULL pointer if allocation was
3855  // unsuccessful.
3856  return (new_lease);
3857 }
3858 
3859 uint32_t
3861 
3862  // If it's BOOTP, use infinite valid lifetime.
3863  if (ctx.query_->inClass("BOOTP")) {
3864  return (Lease::INFINITY_LFT);
3865  }
3866 
3867  // Use the dhcp-lease-time content from the client if it's there.
3868  uint32_t requested_lft = 0;
3869  OptionPtr opt = ctx.query_->getOption(DHO_DHCP_LEASE_TIME);
3870  if (opt) {
3871  OptionUint32Ptr opt_lft = boost::dynamic_pointer_cast<OptionInt<uint32_t> >(opt);
3872  if (opt_lft) {
3873  requested_lft = opt_lft->getValue();
3874  }
3875  }
3876 
3877  // If the triplet is specified in one of our classes use it.
3878  // We use the first one we find.
3879  Triplet<uint32_t> candidate_lft;
3880  const ClientClasses classes = ctx.query_->getClasses();
3881  if (!classes.empty()) {
3882  // Let's get class definitions
3883  const ClientClassDictionaryPtr& dict =
3884  CfgMgr::instance().getCurrentCfg()->getClientClassDictionary();
3885 
3886  // Iterate over the assigned class definitions.
3887  for (ClientClasses::const_iterator name = classes.cbegin();
3888  name != classes.cend(); ++name) {
3889  ClientClassDefPtr cl = dict->findClass(*name);
3890  if (cl && (!cl->getValid().unspecified())) {
3891  candidate_lft = cl->getValid();
3892  break;
3893  }
3894  }
3895  }
3896 
3897  // If no classes specified it, get it from the subnet.
3898  if (!candidate_lft) {
3899  candidate_lft = ctx.subnet_->getValid();
3900  }
3901 
3902  // If client requested a value, use the value bounded by
3903  // the candidate triplet.
3904  if (requested_lft > 0) {
3905  return (candidate_lft.get(requested_lft));
3906  }
3907 
3908  // Use the candidate's default value.
3909  return (candidate_lft.get());
3910 }
3911 
3912 Lease4Ptr
3913 AllocEngine::createLease4(const ClientContext4& ctx, const IOAddress& addr,
3914  CalloutHandle::CalloutNextStep& callout_status) {
3915  if (!ctx.hwaddr_) {
3916  isc_throw(BadValue, "Can't create a lease with NULL HW address");
3917  }
3918  if (!ctx.subnet_) {
3919  isc_throw(BadValue, "Can't create a lease without a subnet");
3920  }
3921 
3922  // Get the context appropriate valid lifetime.
3923  uint32_t valid_lft = getValidLft(ctx);
3924 
3925  time_t now = time(NULL);
3926 
3927  ClientIdPtr client_id;
3928  if (ctx.subnet_->getMatchClientId()) {
3929  client_id = ctx.clientid_;
3930  }
3931 
3932  Lease4Ptr lease(new Lease4(addr, ctx.hwaddr_, client_id,
3933  valid_lft, now, ctx.subnet_->getID()));
3934 
3935  // Set FQDN specific lease parameters.
3936  lease->fqdn_fwd_ = ctx.fwd_dns_update_;
3937  lease->fqdn_rev_ = ctx.rev_dns_update_;
3938  lease->hostname_ = ctx.hostname_;
3939 
3940  // Add(update) the extended information on the lease.
3941  static_cast<void>(updateLease4ExtendedInfo(lease, ctx));
3942 
3943  // Let's execute all callouts registered for lease4_select
3944  if (ctx.callout_handle_ &&
3945  HooksManager::calloutsPresent(hook_index_lease4_select_)) {
3946 
3947  // Use the RAII wrapper to make sure that the callout handle state is
3948  // reset when this object goes out of scope. All hook points must do
3949  // it to prevent possible circular dependency between the callout
3950  // handle and its arguments.
3951  ScopedCalloutHandleState callout_handle_state(ctx.callout_handle_);
3952 
3953  // Enable copying options from the packet within hook library.
3954  ScopedEnableOptionsCopy<Pkt4> query4_options_copy(ctx.query_);
3955 
3956  // Pass necessary arguments
3957  // Pass the original client query
3958  ctx.callout_handle_->setArgument("query4", ctx.query_);
3959 
3960  // Subnet from which we do the allocation (That's as far as we can go
3961  // with using SubnetPtr to point to Subnet4 object. Users should not
3962  // be confused with dynamic_pointer_casts. They should get a concrete
3963  // pointer (Subnet4Ptr) pointing to a Subnet4 object.
3964  Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(ctx.subnet_);
3965  ctx.callout_handle_->setArgument("subnet4", subnet4);
3966 
3967  // Is this solicit (fake = true) or request (fake = false)
3968  ctx.callout_handle_->setArgument("fake_allocation", ctx.fake_allocation_);
3969 
3970  // Pass the intended lease as well
3971  ctx.callout_handle_->setArgument("lease4", lease);
3972 
3973  // This is the first callout, so no need to clear any arguments
3974  HooksManager::callCallouts(hook_index_lease4_select_, *ctx.callout_handle_);
3975 
3976  callout_status = ctx.callout_handle_->getStatus();
3977 
3978  // Callouts decided to skip the action. This means that the lease is not
3979  // assigned, so the client will get NoAddrAvail as a result. The lease
3980  // won't be inserted into the database.
3981  if (callout_status == CalloutHandle::NEXT_STEP_SKIP) {
3983  return (Lease4Ptr());
3984  }
3985 
3986  // Let's use whatever callout returned. Hopefully it is the same lease
3987  // we handled to it.
3988  ctx.callout_handle_->getArgument("lease4", lease);
3989  }
3990 
3991  if (!ctx.fake_allocation_) {
3992  // That is a real (REQUEST) allocation
3993  bool status = LeaseMgrFactory::instance().addLease(lease);
3994  if (status) {
3995 
3996  // The lease insertion succeeded, let's bump up the statistic.
3997  StatsMgr::instance().addValue(
3998  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
3999  "assigned-addresses"),
4000  static_cast<int64_t>(1));
4001  StatsMgr::instance().addValue(
4002  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4003  "cumulative-assigned-addresses"),
4004  static_cast<int64_t>(1));
4005  StatsMgr::instance().addValue("cumulative-assigned-addresses",
4006  static_cast<int64_t>(1));
4007 
4008  return (lease);
4009  } else {
4010  // One of many failures with LeaseMgr (e.g. lost connection to the
4011  // database, database failed etc.). One notable case for that
4012  // is that we are working in multi-process mode and we lost a race
4013  // (some other process got that address first)
4014  return (Lease4Ptr());
4015  }
4016  } else {
4017  // That is only fake (DISCOVER) allocation
4018 
4019  // It is for OFFER only. We should not insert the lease and callers
4020  // have already verified the lease does not exist in the database.
4021  return (lease);
4022  }
4023 }
4024 
4025 Lease4Ptr
4026 AllocEngine::renewLease4(const Lease4Ptr& lease,
4028  if (!lease) {
4029  isc_throw(BadValue, "null lease specified for renewLease4");
4030  }
4031 
4032  // Let's keep the old data. This is essential if we are using memfile
4033  // (the lease returned points directly to the lease4 object in the database)
4034  // We'll need it if we want to skip update (i.e. roll back renewal)
4036  Lease4Ptr old_values = boost::make_shared<Lease4>(*lease);
4037  ctx.old_lease_.reset(new Lease4(*old_values));
4038 
4039  // Update the lease with the information from the context.
4040  // If there was no significant changes, try reuse.
4041  lease->reuseable_valid_lft_ = 0;
4042  if (!updateLease4Information(lease, ctx)) {
4043  setLeaseReusable(lease, ctx);
4044  }
4045 
4046  if (!ctx.fake_allocation_) {
4047  // If the lease is expired we have to reclaim it before
4048  // re-assigning it to the client. The lease reclamation
4049  // involves execution of hooks and DNS update.
4050  if (ctx.old_lease_->expired()) {
4051  reclaimExpiredLease(ctx.old_lease_, ctx.callout_handle_);
4052  }
4053 
4054  lease->state_ = Lease::STATE_DEFAULT;
4055  }
4056 
4057  bool skip = false;
4058  // Execute all callouts registered for lease4_renew.
4059  if (HooksManager::calloutsPresent(Hooks.hook_index_lease4_renew_)) {
4060 
4061  // Use the RAII wrapper to make sure that the callout handle state is
4062  // reset when this object goes out of scope. All hook points must do
4063  // it to prevent possible circular dependency between the callout
4064  // handle and its arguments.
4065  ScopedCalloutHandleState callout_handle_state(ctx.callout_handle_);
4066 
4067  // Enable copying options from the packet within hook library.
4068  ScopedEnableOptionsCopy<Pkt4> query4_options_copy(ctx.query_);
4069 
4070  // Subnet from which we do the allocation. Convert the general subnet
4071  // pointer to a pointer to a Subnet4. Note that because we are using
4072  // boost smart pointers here, we need to do the cast using the boost
4073  // version of dynamic_pointer_cast.
4074  Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(ctx.subnet_);
4075 
4076  // Pass the parameters. Note the clientid is passed only if match-client-id
4077  // is set. This is done that way, because the lease4-renew hook point is
4078  // about renewing a lease and the configuration parameter says the
4079  // client-id should be ignored. Hence no clientid value if match-client-id
4080  // is false.
4081  ctx.callout_handle_->setArgument("query4", ctx.query_);
4082  ctx.callout_handle_->setArgument("subnet4", subnet4);
4083  ctx.callout_handle_->setArgument("clientid", subnet4->getMatchClientId() ?
4084  ctx.clientid_ : ClientIdPtr());
4085  ctx.callout_handle_->setArgument("hwaddr", ctx.hwaddr_);
4086 
4087  // Pass the lease to be updated
4088  ctx.callout_handle_->setArgument("lease4", lease);
4089 
4090  // Call all installed callouts
4091  HooksManager::callCallouts(Hooks.hook_index_lease4_renew_,
4092  *ctx.callout_handle_);
4093 
4094  // Callouts decided to skip the next processing step. The next
4095  // processing step would actually renew the lease, so skip at this
4096  // stage means "keep the old lease as it is".
4097  if (ctx.callout_handle_->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
4098  skip = true;
4101  }
4102 
4104  }
4105 
4106  if (!ctx.fake_allocation_ && !skip && (lease->reuseable_valid_lft_ == 0)) {
4107  // for REQUEST we do update the lease
4109 
4110  // We need to account for the re-assignment of The lease.
4111  if (ctx.old_lease_->expired() || ctx.old_lease_->state_ == Lease::STATE_EXPIRED_RECLAIMED) {
4112  StatsMgr::instance().addValue(
4113  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4114  "assigned-addresses"),
4115  static_cast<int64_t>(1));
4116  StatsMgr::instance().addValue(
4117  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4118  "cumulative-assigned-addresses"),
4119  static_cast<int64_t>(1));
4120  StatsMgr::instance().addValue("cumulative-assigned-addresses",
4121  static_cast<int64_t>(1));
4122  }
4123  }
4124  if (skip) {
4125  // Rollback changes (really useful only for memfile)
4127  *lease = *old_values;
4128  }
4129 
4130  return (lease);
4131 }
4132 
4133 Lease4Ptr
4134 AllocEngine::reuseExpiredLease4(Lease4Ptr& expired,
4136  CalloutHandle::CalloutNextStep& callout_status) {
4137  if (!expired) {
4138  isc_throw(BadValue, "null lease specified for reuseExpiredLease");
4139  }
4140 
4141  if (!ctx.subnet_) {
4142  isc_throw(BadValue, "null subnet specified for the reuseExpiredLease");
4143  }
4144 
4145  if (!ctx.fake_allocation_) {
4146  // The expired lease needs to be reclaimed before it can be reused.
4147  // This includes declined leases for which probation period has
4148  // elapsed.
4149  reclaimExpiredLease(expired, ctx.callout_handle_);
4150  expired->state_ = Lease::STATE_DEFAULT;
4151  }
4152 
4153  expired->reuseable_valid_lft_ = 0;
4154  static_cast<void>(updateLease4Information(expired, ctx));
4155 
4158  .arg(ctx.query_->getLabel())
4159  .arg(expired->toText());
4160 
4161  // Let's execute all callouts registered for lease4_select
4162  if (ctx.callout_handle_ &&
4163  HooksManager::calloutsPresent(hook_index_lease4_select_)) {
4164 
4165  // Enable copying options from the packet within hook library.
4166  ScopedEnableOptionsCopy<Pkt4> query4_options_copy(ctx.query_);
4167 
4168  // Use the RAII wrapper to make sure that the callout handle state is
4169  // reset when this object goes out of scope. All hook points must do
4170  // it to prevent possible circular dependency between the callout
4171  // handle and its arguments.
4172  ScopedCalloutHandleState callout_handle_state(ctx.callout_handle_);
4173 
4174  // Pass necessary arguments
4175  // Pass the original client query
4176  ctx.callout_handle_->setArgument("query4", ctx.query_);
4177 
4178  // Subnet from which we do the allocation. Convert the general subnet
4179  // pointer to a pointer to a Subnet4. Note that because we are using
4180  // boost smart pointers here, we need to do the cast using the boost
4181  // version of dynamic_pointer_cast.
4182  Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(ctx.subnet_);
4183  ctx.callout_handle_->setArgument("subnet4", subnet4);
4184 
4185  // Is this solicit (fake = true) or request (fake = false)
4186  ctx.callout_handle_->setArgument("fake_allocation", ctx.fake_allocation_);
4187 
4188  // The lease that will be assigned to a client
4189  ctx.callout_handle_->setArgument("lease4", expired);
4190 
4191  // Call the callouts
4192  HooksManager::callCallouts(hook_index_lease4_select_, *ctx.callout_handle_);
4193 
4194  callout_status = ctx.callout_handle_->getStatus();
4195 
4196  // Callouts decided to skip the action. This means that the lease is not
4197  // assigned, so the client will get NoAddrAvail as a result. The lease
4198  // won't be inserted into the database.
4199  if (callout_status == CalloutHandle::NEXT_STEP_SKIP) {
4202  return (Lease4Ptr());
4203  }
4204 
4206 
4207  // Let's use whatever callout returned. Hopefully it is the same lease
4208  // we handed to it.
4209  ctx.callout_handle_->getArgument("lease4", expired);
4210  }
4211 
4212  if (!ctx.fake_allocation_) {
4213  // for REQUEST we do update the lease
4215 
4216  // We need to account for the re-assignment of The lease.
4217  StatsMgr::instance().addValue(
4218  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4219  "assigned-addresses"),
4220  static_cast<int64_t>(1));
4221  StatsMgr::instance().addValue(
4222  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4223  "cumulative-assigned-addresses"),
4224  static_cast<int64_t>(1));
4225  StatsMgr::instance().addValue("cumulative-assigned-addresses",
4226  static_cast<int64_t>(1));
4227  }
4228 
4229  // We do nothing for SOLICIT. We'll just update database when
4230  // the client gets back to us with REQUEST message.
4231 
4232  // it's not really expired at this stage anymore - let's return it as
4233  // an updated lease
4234  return (expired);
4235 }
4236 
4237 Lease4Ptr
4238 AllocEngine::allocateOrReuseLease4(const IOAddress& candidate, ClientContext4& ctx,
4239  CalloutHandle::CalloutNextStep& callout_status) {
4240  ctx.conflicting_lease_.reset();
4241 
4242  Lease4Ptr exist_lease = LeaseMgrFactory::instance().getLease4(candidate);
4243  if (exist_lease) {
4244  if (exist_lease->expired()) {
4245  ctx.old_lease_ = Lease4Ptr(new Lease4(*exist_lease));
4246  // reuseExpiredLease4() will reclaim the use which will
4247  // queue an NCR remove it needed. Clear the DNS fields in
4248  // the old lease to avoid a redundant remove in server logic.
4249  ctx.old_lease_->hostname_.clear();
4250  ctx.old_lease_->fqdn_fwd_ = false;
4251  ctx.old_lease_->fqdn_rev_ = false;
4252  return (reuseExpiredLease4(exist_lease, ctx, callout_status));
4253 
4254  } else {
4255  // If there is a lease and it is not expired, pass this lease back
4256  // to the caller in the context. The caller may need to know
4257  // which lease we're conflicting with.
4258  ctx.conflicting_lease_ = exist_lease;
4259  }
4260 
4261  } else {
4262  return (createLease4(ctx, candidate, callout_status));
4263  }
4264  return (Lease4Ptr());
4265 }
4266 
4267 Lease4Ptr
4268 AllocEngine::allocateUnreservedLease4(ClientContext4& ctx) {
4269  Lease4Ptr new_lease;
4270  Subnet4Ptr subnet = ctx.subnet_;
4271 
4272  // Need to check if the subnet belongs to a shared network. If so,
4273  // we might be able to find a better subnet for lease allocation,
4274  // for which it is more likely that there are some leases available.
4275  // If we stick to the selected subnet, we may end up walking over
4276  // the entire subnet (or more subnets) to discover that the address
4277  // pools have been exhausted. Using a subnet from which an address
4278  // was assigned most recently is an optimization which increases
4279  // the likelihood of starting from the subnet which address pools
4280  // are not exhausted.
4281  SharedNetwork4Ptr network;
4282  ctx.subnet_->getSharedNetwork(network);
4283  if (network) {
4284  // This would try to find a subnet with the same set of classes
4285  // as the current subnet, but with the more recent "usage timestamp".
4286  // This timestamp is only updated for the allocations made with an
4287  // allocator (unreserved lease allocations), not the static
4288  // allocations or requested addresses.
4289  ctx.subnet_ = subnet = network->getPreferredSubnet(ctx.subnet_);
4290  }
4291 
4292  // We have the choice in the order checking the lease and
4293  // the reservation. The default is to begin by the lease
4294  // if the multi-threading is disabled.
4295  bool check_reservation_first = MultiThreadingMgr::instance().getMode();
4296 
4297  Subnet4Ptr original_subnet = subnet;
4298 
4299  uint64_t total_attempts = 0;
4300 
4301  // The following counter tracks the number of subnets with matching client
4302  // classes from which the allocation engine attempted to assign leases.
4303  uint64_t subnets_with_unavail_leases = 0;
4304  // The following counter tracks the number of subnets in which there were
4305  // no matching pools for the client.
4306  uint64_t subnets_with_unavail_pools = 0;
4307 
4308  auto const& classes = ctx.query_->getClasses();
4309 
4310  while (subnet) {
4311  ClientIdPtr client_id;
4312  if (subnet->getMatchClientId()) {
4313  client_id = ctx.clientid_;
4314  }
4315 
4316  uint64_t possible_attempts =
4317  subnet->getPoolCapacity(Lease::TYPE_V4, classes);
4318 
4319  // If the number of tries specified in the allocation engine constructor
4320  // is set to 0 (unlimited) or the pools capacity is lower than that number,
4321  // let's use the pools capacity as the maximum number of tries. Trying
4322  // more than the actual pools capacity is a waste of time. If the specified
4323  // number of tries is lower than the pools capacity, use that number.
4324  uint64_t max_attempts = ((attempts_ == 0 || possible_attempts < attempts_) ? possible_attempts : attempts_);
4325 
4326  if (max_attempts > 0) {
4327  // If max_attempts is greater than 0, there are some pools in this subnet
4328  // from which we can potentially get a lease.
4329  ++subnets_with_unavail_leases;
4330  } else {
4331  // If max_attempts is 0, it is an indication that there are no pools
4332  // in the subnet from which we can get a lease.
4333  ++subnets_with_unavail_pools;
4334  }
4335 
4336  bool exclude_first_last_24 = ((subnet->get().second <= 24) &&
4337  CfgMgr::instance().getCurrentCfg()->getExcludeFirstLast24());
4338 
4339  CalloutHandle::CalloutNextStep callout_status = CalloutHandle::NEXT_STEP_CONTINUE;
4340 
4341  for (uint64_t i = 0; i < max_attempts; ++i) {
4342 
4343  ++total_attempts;
4344 
4345  auto allocator = subnet->getAllocator(Lease::TYPE_V4);
4346  IOAddress candidate = allocator->pickAddress(classes,
4347  client_id,
4348  ctx.requested_address_);
4349 
4350  if (exclude_first_last_24) {
4351  // Exclude .0 and .255 addresses.
4352  auto const& bytes = candidate.toBytes();
4353  if ((bytes.size() != 4) ||
4354  (bytes[3] == 0) || (bytes[3] == 255U)) {
4355  // Don't allocate.
4356  continue;
4357  }
4358  }
4359 
4360  // First check for reservation when it is the choice.
4361  if (check_reservation_first && addressReserved(candidate, ctx)) {
4362  // Don't allocate.
4363  continue;
4364  }
4365 
4366  // Check if the resource is busy i.e. can be being allocated
4367  // by another thread to another client.
4368  ResourceHandler4 resource_handler;
4369  if (MultiThreadingMgr::instance().getMode() &&
4370  !resource_handler.tryLock4(candidate)) {
4371  // Don't allocate.
4372  continue;
4373  }
4374 
4375  // Check for an existing lease for the candidate address.
4376  Lease4Ptr exist_lease = LeaseMgrFactory::instance().getLease4(candidate);
4377  if (!exist_lease) {
4378  // No existing lease, is it reserved?
4379  if (check_reservation_first || !addressReserved(candidate, ctx)) {
4380  // Not reserved use it.
4381  new_lease = createLease4(ctx, candidate, callout_status);
4382  }
4383  } else {
4384  // An lease exists, is expired, and not reserved use it.
4385  if (exist_lease->expired() &&
4386  (check_reservation_first || !addressReserved(candidate, ctx))) {
4387  ctx.old_lease_ = Lease4Ptr(new Lease4(*exist_lease));
4388  new_lease = reuseExpiredLease4(exist_lease, ctx, callout_status);
4389  }
4390  }
4391 
4392  // We found a lease we can use, return it.
4393  if (new_lease) {
4394  return (new_lease);
4395  }
4396 
4397  if (ctx.callout_handle_ && (callout_status != CalloutHandle::NEXT_STEP_CONTINUE)) {
4398  // Don't retry when the callout status is not continue.
4399  subnet.reset();
4400  break;
4401  }
4402  }
4403 
4404  // This pointer may be set to NULL if hooks set SKIP status.
4405  if (subnet) {
4406  subnet = subnet->getNextSubnet(original_subnet, classes);
4407 
4408  if (subnet) {
4409  ctx.subnet_ = subnet;
4410  }
4411  }
4412  }
4413 
4414  if (network) {
4415  // The client is in the shared network. Let's log the high level message
4416  // indicating which shared network the client belongs to.
4418  .arg(ctx.query_->getLabel())
4419  .arg(network->getName())
4420  .arg(subnets_with_unavail_leases)
4421  .arg(subnets_with_unavail_pools);
4422  StatsMgr::instance().addValue("v4-allocation-fail-shared-network",
4423  static_cast<int64_t>(1));
4424  StatsMgr::instance().addValue(
4425  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4426  "v4-allocation-fail-shared-network"),
4427  static_cast<int64_t>(1));
4428  } else {
4429  // The client is not connected to a shared network. It is connected
4430  // to a subnet. Let's log some details about the subnet.
4431  std::string shared_network = ctx.subnet_->getSharedNetworkName();
4432  if (shared_network.empty()) {
4433  shared_network = "(none)";
4434  }
4436  .arg(ctx.query_->getLabel())
4437  .arg(ctx.subnet_->toText())
4438  .arg(ctx.subnet_->getID())
4439  .arg(shared_network);
4440  StatsMgr::instance().addValue("v4-allocation-fail-subnet",
4441  static_cast<int64_t>(1));
4442  StatsMgr::instance().addValue(
4443  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4444  "v4-allocation-fail-subnet"),
4445  static_cast<int64_t>(1));
4446  }
4447  if (total_attempts == 0) {
4448  // In this case, it seems that none of the pools in the subnets could
4449  // be used for that client, both in case the client is connected to
4450  // a shared network or to a single subnet. Apparently, the client was
4451  // rejected to use the pools because of the client classes' mismatch.
4453  .arg(ctx.query_->getLabel());
4454  StatsMgr::instance().addValue("v4-allocation-fail-no-pools",
4455  static_cast<int64_t>(1));
4456  StatsMgr::instance().addValue(
4457  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4458  "v4-allocation-fail-no-pools"),
4459  static_cast<int64_t>(1));
4460  } else {
4461  // This is an old log message which provides a number of attempts
4462  // made by the allocation engine to allocate a lease. The only case
4463  // when we don't want to log this message is when the number of
4464  // attempts is zero (condition above), because it would look silly.
4466  .arg(ctx.query_->getLabel())
4467  .arg(total_attempts);
4468  StatsMgr::instance().addValue("v4-allocation-fail",
4469  static_cast<int64_t>(1));
4470  StatsMgr::instance().addValue(
4471  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4472  "v4-allocation-fail"),
4473  static_cast<int64_t>(1));
4474  }
4475 
4476  if (!classes.empty()) {
4478  .arg(ctx.query_->getLabel())
4479  .arg(classes.toText());
4480  StatsMgr::instance().addValue("v4-allocation-fail-classes",
4481  static_cast<int64_t>(1));
4482  StatsMgr::instance().addValue(
4483  StatsMgr::generateName("subnet", ctx.subnet_->getID(),
4484  "v4-allocation-fail-classes"),
4485  static_cast<int64_t>(1));
4486  }
4487 
4488  return (new_lease);
4489 }
4490 
4491 bool
4492 AllocEngine::updateLease4Information(const Lease4Ptr& lease,
4493  AllocEngine::ClientContext4& ctx) const {
4494  bool changed = false;
4495  if (lease->subnet_id_ != ctx.subnet_->getID()) {
4496  changed = true;
4497  lease->subnet_id_ = ctx.subnet_->getID();
4498  }
4499  if ((!ctx.hwaddr_ && lease->hwaddr_) ||
4500  (ctx.hwaddr_ &&
4501  (!lease->hwaddr_ || (*ctx.hwaddr_ != *lease->hwaddr_)))) {
4502  changed = true;
4503  lease->hwaddr_ = ctx.hwaddr_;
4504  }
4505  if (ctx.subnet_->getMatchClientId() && ctx.clientid_) {
4506  if (!lease->client_id_ || (*ctx.clientid_ != *lease->client_id_)) {
4507  changed = true;
4508  lease->client_id_ = ctx.clientid_;
4509  }
4510  } else if (lease->client_id_) {
4511  changed = true;
4512  lease->client_id_ = ClientIdPtr();
4513  }
4514  lease->cltt_ = time(NULL);
4515 
4516  // Get the context appropriate valid lifetime.
4517  lease->valid_lft_ = getValidLft(ctx);
4518 
4519  // Reduced valid lifetime is a significant change.
4520  if (lease->valid_lft_ < lease->current_valid_lft_) {
4521  changed = true;
4522  }
4523 
4524  if ((lease->fqdn_fwd_ != ctx.fwd_dns_update_) ||
4525  (lease->fqdn_rev_ != ctx.rev_dns_update_) ||
4526  (lease->hostname_ != ctx.hostname_)) {
4527  changed = true;
4528  lease->fqdn_fwd_ = ctx.fwd_dns_update_;
4529  lease->fqdn_rev_ = ctx.rev_dns_update_;
4530  lease->hostname_ = ctx.hostname_;
4531  }
4532 
4533  // Add(update) the extended information on the lease.
4534  if (updateLease4ExtendedInfo(lease, ctx)) {
4535  changed = true;
4536  }
4537 
4538  return (changed);
4539 }
4540 
4541 bool
4543  const AllocEngine::ClientContext4& ctx) const {
4544  bool changed = false;
4545 
4546  // If storage is not enabled then punt.
4547  if (!ctx.subnet_->getStoreExtendedInfo()) {
4548  return (changed);
4549  }
4550 
4551  // Look for relay agent information option (option 82)
4552  OptionPtr rai = ctx.query_->getOption(DHO_DHCP_AGENT_OPTIONS);
4553  if (!rai) {
4554  // Pkt4 doesn't have it, so nothing to store (or update).
4555  return (changed);
4556  }
4557 
4558  // Create a StringElement with the hex string for relay-agent-info.
4559  ElementPtr relay_agent(new StringElement(rai->toHexString()));
4560 
4561  // Now we wrap the agent info in a map. This allows for future expansion.
4562  ElementPtr extended_info = Element::createMap();
4563  extended_info->set("sub-options", relay_agent);
4564 
4565  OptionPtr remote_id = rai->getOption(RAI_OPTION_REMOTE_ID);
4566  if (remote_id) {
4567  std::vector<uint8_t> bytes = remote_id->toBinary(false);
4568  lease->remote_id_ = bytes;
4569  if (bytes.size() > 0) {
4570  extended_info->set("remote-id",
4572  }
4573  }
4574 
4575  OptionPtr relay_id = rai->getOption(RAI_OPTION_RELAY_ID);
4576  if (relay_id) {
4577  std::vector<uint8_t> bytes = relay_id->toBinary(false);
4578  lease->relay_id_ = bytes;
4579  if (bytes.size() > 0) {
4580  extended_info->set("relay-id",
4582  }
4583  }
4584 
4585  // Get a mutable copy of the lease's current user context.
4586  ConstElementPtr user_context = lease->getContext();
4587  ElementPtr mutable_user_context;
4588  if (user_context && (user_context->getType() == Element::map)) {
4589  mutable_user_context = copy(user_context, 0);
4590  } else {
4591  mutable_user_context = Element::createMap();
4592  }
4593 
4594  // Get a mutable copy of the ISC entry.
4595  ConstElementPtr isc = mutable_user_context->get("ISC");
4596  ElementPtr mutable_isc;
4597  if (isc && (isc->getType() == Element::map)) {
4598  mutable_isc = copy(isc, 0);
4599  } else {
4600  mutable_isc = Element::createMap();
4601  }
4602 
4603  // Add/replace the extended info entry.
4604  ConstElementPtr old_extended_info = mutable_isc->get("relay-agent-info");
4605  if (!old_extended_info || (*old_extended_info != *extended_info)) {
4606  changed = true;
4607  mutable_isc->set("relay-agent-info", extended_info);
4608  mutable_user_context->set("ISC", mutable_isc);
4609  }
4610 
4611  // Update the lease's user_context.
4612  lease->setContext(mutable_user_context);
4613 
4614  return (changed);
4615 }
4616 
4617 void
4619  const AllocEngine::ClientContext6& ctx) const {
4620  // The extended info action is a transient value but be safe so reset it.
4621  lease->extended_info_action_ = Lease6::ACTION_IGNORE;
4622 
4623  // If storage is not enabled then punt.
4624  if (!ctx.subnet_->getStoreExtendedInfo()) {
4625  return;
4626  }
4627 
4628  // If we do not have relay information, then punt.
4629  if (ctx.query_->relay_info_.empty()) {
4630  return;
4631  }
4632 
4633  // We need to convert the vector of RelayInfo instances in
4634  // into an Element hierarchy like this:
4635  // "relay-info": [
4636  // {
4637  // "hop": 123,
4638  // "link": "2001:db8::1",
4639  // "peer": "2001:db8::2",
4640  // "options": "0x..."
4641  // },..]
4642  //
4643  ElementPtr extended_info = Element::createList();
4644  for (auto relay : ctx.query_->relay_info_) {
4645  ElementPtr relay_elem = Element::createMap();
4646  relay_elem->set("hop", ElementPtr(new IntElement(relay.hop_count_)));
4647  relay_elem->set("link", ElementPtr(new StringElement(relay.linkaddr_.toText())));
4648  relay_elem->set("peer", ElementPtr(new StringElement(relay.peeraddr_.toText())));
4649 
4650  // If there are relay options, we'll pack them into a buffer and then
4651  // convert that into a hex string. If there are no options, we omit
4652  // then entry.
4653  if (!relay.options_.empty()) {
4654  OutputBuffer buf(128);
4655  LibDHCP::packOptions6(buf, relay.options_);
4656 
4657  if (buf.getLength() > 0) {
4658  const uint8_t* cp = static_cast<const uint8_t*>(buf.getData());
4659  std::vector<uint8_t> bytes;
4660  std::stringstream ss;
4661 
4662  bytes.assign(cp, cp + buf.getLength());
4663  ss << "0x" << encode::encodeHex(bytes);
4664  relay_elem->set("options", ElementPtr(new StringElement(ss.str())));
4665  }
4666 
4667  auto remote_id_it = relay.options_.find(D6O_REMOTE_ID);
4668  if (remote_id_it != relay.options_.end()) {
4669  OptionPtr remote_id = remote_id_it->second;
4670  if (remote_id) {
4671  std::vector<uint8_t> bytes = remote_id->toBinary(false);
4672  if (bytes.size() > 0) {
4673  relay_elem->set("remote-id",
4675  }
4676  }
4677  }
4678 
4679  auto relay_id_it = relay.options_.find(D6O_RELAY_ID);
4680  if (relay_id_it != relay.options_.end()) {
4681  OptionPtr relay_id = relay_id_it->second;
4682  if (relay_id) {
4683  std::vector<uint8_t> bytes = relay_id->toBinary(false);
4684  if (bytes.size() > 0) {
4685  relay_elem->set("relay-id",
4687  }
4688  }
4689  }
4690  }
4691 
4692  extended_info->add(relay_elem);
4693  }
4694 
4695  // Get a mutable copy of the lease's current user context.
4696  ConstElementPtr user_context = lease->getContext();
4697  ElementPtr mutable_user_context;
4698  if (user_context && (user_context->getType() == Element::map)) {
4699  mutable_user_context = copy(user_context, 0);
4700  } else {
4701  mutable_user_context = Element::createMap();
4702  }
4703 
4704  // Get a mutable copy of the ISC entry.
4705  ConstElementPtr isc = mutable_user_context->get("ISC");
4706  ElementPtr mutable_isc;
4707  if (isc && (isc->getType() == Element::map)) {
4708  mutable_isc = copy(isc, 0);
4709  } else {
4710  mutable_isc = Element::createMap();
4711  }
4712 
4713  // Add/replace the extended info entry.
4714  ConstElementPtr old_extended_info = mutable_isc->get("relay-info");
4715  if (!old_extended_info || (*old_extended_info != *extended_info)) {
4716  lease->extended_info_action_ = Lease6::ACTION_UPDATE;
4717  mutable_isc->set("relay-info", extended_info);
4718  mutable_user_context->set("ISC", mutable_isc);
4719  }
4720 
4721  // Update the lease's user context.
4722  lease->setContext(mutable_user_context);
4723 }
4724 
4725 void
4726 AllocEngine::setLeaseReusable(const Lease4Ptr& lease,
4727  const ClientContext4& ctx) const {
4728  // Sanity.
4729  lease->reuseable_valid_lft_ = 0;
4730  const Subnet4Ptr& subnet = ctx.subnet_;
4731  if (!subnet) {
4732  return;
4733  }
4734  if (lease->state_ != Lease::STATE_DEFAULT) {
4735  return;
4736  }
4737 
4738  // Always reuse infinite lifetime leases.
4739  if (lease->valid_lft_ == Lease::INFINITY_LFT) {
4740  lease->reuseable_valid_lft_ = Lease::INFINITY_LFT;
4741  return;
4742  }
4743 
4744  // Refuse time not going forward.
4745  if (lease->cltt_ < lease->current_cltt_) {
4746  return;
4747  }
4748 
4749  uint32_t age = lease->cltt_ - lease->current_cltt_;
4750  // Already expired.
4751  if (age >= lease->current_valid_lft_) {
4752  return;
4753  }
4754 
4755  // Try cache max age.
4756  uint32_t max_age = 0;
4757  if (!subnet->getCacheMaxAge().unspecified()) {
4758  max_age = subnet->getCacheMaxAge().get();
4759  if ((max_age == 0) || (age > max_age)) {
4760  return;
4761  }
4762  }
4763 
4764  // Try cache threshold.
4765  if (!subnet->getCacheThreshold().unspecified()) {
4766  double threshold = subnet->getCacheThreshold().get();
4767  if ((threshold <= 0.) || (threshold > 1.)) {
4768  return;
4769  }
4770  max_age = lease->valid_lft_ * threshold;
4771  if (age > max_age) {
4772  return;
4773  }
4774  }
4775 
4776  // No cache.
4777  if (max_age == 0) {
4778  return;
4779  }
4780 
4781  // Seems to be reusable.
4782  lease->reuseable_valid_lft_ = lease->current_valid_lft_ - age;
4783 }
4784 
4785 void
4786 AllocEngine::setLeaseReusable(const Lease6Ptr& lease,
4787  uint32_t current_preferred_lft,
4788  const ClientContext6& ctx) const {
4789  // Sanity.
4790  lease->reuseable_valid_lft_ = 0;
4791  lease->reuseable_preferred_lft_ = 0;
4792  const Subnet6Ptr& subnet = ctx.subnet_;
4793  if (!subnet) {
4794  return;
4795  }
4796  if (lease->state_ != Lease::STATE_DEFAULT) {
4797  return;
4798  }
4799 
4800  // Refuse time not going forward.
4801  if (lease->cltt_ < lease->current_cltt_) {
4802  return;
4803  }
4804 
4805  uint32_t age = lease->cltt_ - lease->current_cltt_;
4806  // Already expired.
4807  if (age >= lease->current_valid_lft_) {
4808  return;
4809  }
4810 
4811  // Try cache max age.
4812  uint32_t max_age = 0;
4813  if (!subnet->getCacheMaxAge().unspecified()) {
4814  max_age = subnet->getCacheMaxAge().get();
4815  if ((max_age == 0) || (age > max_age)) {
4816  return;
4817  }
4818  }
4819 
4820  // Try cache threshold.
4821  if (!subnet->getCacheThreshold().unspecified()) {
4822  double threshold = subnet->getCacheThreshold().get();
4823  if ((threshold <= 0.) || (threshold > 1.)) {
4824  return;
4825  }
4826  max_age = lease->valid_lft_ * threshold;
4827  if (age > max_age) {
4828  return;
4829  }
4830  }
4831 
4832  // No cache.
4833  if (max_age == 0) {
4834  return;
4835  }
4836 
4837  // Seems to be reusable.
4838  if ((current_preferred_lft == Lease::INFINITY_LFT) ||
4839  (current_preferred_lft == 0)) {
4840  // Keep these values.
4841  lease->reuseable_preferred_lft_ = current_preferred_lft;
4842  } else if (current_preferred_lft > age) {
4843  lease->reuseable_preferred_lft_ = current_preferred_lft - age;
4844  } else {
4845  // Can be a misconfiguration so stay safe...
4846  return;
4847  }
4848  if (lease->current_valid_lft_ == Lease::INFINITY_LFT) {
4849  lease->reuseable_valid_lft_ = Lease::INFINITY_LFT;
4850  } else {
4851  lease->reuseable_valid_lft_ = lease->current_valid_lft_ - age;
4852  }
4853 }
4854 
4855 } // namespace dhcp
4856 } // namespace isc
void clearReclaimedExtendedInfo(const Lease4Ptr &lease) const
Clear extended info from a reclaimed V4 lease.
static bool isValidPrefixPool(Allocator::PrefixLenMatchType prefix_length_match, PoolPtr pool, uint8_t hint_prefix_length)
Check if the pool matches the selection criteria relative to the provided hint prefix length...
Definition: allocator.cc:37
#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:401
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:295
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
static void packOptions6(isc::util::OutputBuffer &buf, const isc::dhcp::OptionCollection &options)
Stores DHCPv6 options in a buffer.
Definition: libdhcp++.cc:1190
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
delete reference to the lease
Definition: lease.h:559
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:788
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:504
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:486
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:493
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
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.
PrefixLenMatchType
Type of preferred PD-pool prefix length selection criteria.
Definition: allocator.h:61
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.
static std::string labelNetworkOrSubnet(SubnetPtr subnet)
Generates a label for subnet or shared-network from subnet.
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:284
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
bool updateLease4ExtendedInfo(const Lease4Ptr &lease, const ClientContext4 &ctx) const
Stores additional client query parameters on a V4 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
void reclaimExpiredLeases4Internal(const size_t max_leases, const uint16_t timeout, const bool remove_lease, const uint16_t max_unwarned_cycles=0)
Body of reclaimExpiredLeases4.
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...
const isc::log::MessageID ALLOC_ENGINE_V4_LEASES_RECLAMATION_FAILED
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:520
update extended info tables.
Definition: lease.h:560
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:677
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
const isc::log::MessageID ALLOC_ENGINE_V6_LEASES_RECLAMATION_FAILED
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:695
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
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
ignore extended info,
Definition: lease.h:558
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
static TrackingLeaseMgr & instance()
Return current lease manager.
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:644
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
const isc::log::MessageID ALLOC_ENGINE_IGNORING_UNSUITABLE_GLOBAL_ADDRESS6
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.
const isc::log::MessageID ALLOC_ENGINE_IGNORING_UNSUITABLE_GLOBAL_ADDRESS
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:509
virtual uint64_t deleteExpiredReclaimedLeases6(const uint32_t secs)=0
Deletes all expired and reclaimed DHCPv6 leases.
std::string logFormatTotalDuration() const
Returns the total measured duration in the format directly usable in the log messages.
Definition: stopwatch.cc:80
This file provides the classes needed to embody, compose, and decompose DNS update requests that are ...
ConstHostPtr currentHost() const
Returns host from the most preferred subnet.
std::pair< Host::IdentifierType, std::vector< uint8_t > > IdentifierPair
A tuple holding host identifier type and value.
Definition: alloc_engine.h:191
const isc::log::MessageID ALLOC_ENGINE_V4_REQUEST_ALLOC_REQUESTED
Container for storing client class names.
Definition: classify.h:108
void reclaimExpiredLeases6Internal(const size_t max_leases, const uint16_t timeout, const bool remove_lease, const uint16_t max_unwarned_cycles=0)
Body of reclaimExpiredLeases6.
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.
boost::shared_ptr< Subnet > SubnetPtr
A generic pointer to either Subnet4 or Subnet6 object.
Definition: subnet.h:477
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