alloc_engine.cc 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519
  1. // Copyright (C) 2012-2014 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <dhcpsrv/alloc_engine.h>
  15. #include <dhcpsrv/dhcpsrv_log.h>
  16. #include <dhcpsrv/host_mgr.h>
  17. #include <dhcpsrv/host.h>
  18. #include <dhcpsrv/lease_mgr_factory.h>
  19. #include <hooks/server_hooks.h>
  20. #include <hooks/hooks_manager.h>
  21. #include <cstring>
  22. #include <vector>
  23. #include <string.h>
  24. using namespace isc::asiolink;
  25. using namespace isc::hooks;
  26. namespace {
  27. /// Structure that holds registered hook indexes
  28. struct AllocEngineHooks {
  29. int hook_index_lease4_select_; ///< index for "lease4_receive" hook point
  30. int hook_index_lease4_renew_; ///< index for "lease4_renew" hook point
  31. int hook_index_lease6_select_; ///< index for "lease6_receive" hook point
  32. /// Constructor that registers hook points for AllocationEngine
  33. AllocEngineHooks() {
  34. hook_index_lease4_select_ = HooksManager::registerHook("lease4_select");
  35. hook_index_lease4_renew_ = HooksManager::registerHook("lease4_renew");
  36. hook_index_lease6_select_ = HooksManager::registerHook("lease6_select");
  37. }
  38. };
  39. // Declare a Hooks object. As this is outside any function or method, it
  40. // will be instantiated (and the constructor run) when the module is loaded.
  41. // As a result, the hook indexes will be defined before any method in this
  42. // module is called.
  43. AllocEngineHooks Hooks;
  44. }; // anonymous namespace
  45. namespace isc {
  46. namespace dhcp {
  47. AllocEngine::IterativeAllocator::IterativeAllocator(Lease::Type lease_type)
  48. :Allocator(lease_type) {
  49. }
  50. isc::asiolink::IOAddress
  51. AllocEngine::IterativeAllocator::increaseAddress(const isc::asiolink::IOAddress& addr) {
  52. // Get a buffer holding an address.
  53. const std::vector<uint8_t>& vec = addr.toBytes();
  54. // Get the address length.
  55. const int len = vec.size();
  56. // Since the same array will be used to hold the IPv4 and IPv6
  57. // address we have to make sure that the size of the array
  58. // we allocate will work for both types of address.
  59. BOOST_STATIC_ASSERT(V4ADDRESS_LEN <= V6ADDRESS_LEN);
  60. uint8_t packed[V6ADDRESS_LEN];
  61. // Copy the address. It can be either V4 or V6.
  62. std::memcpy(packed, &vec[0], len);
  63. // Start increasing the least significant byte
  64. for (int i = len - 1; i >= 0; --i) {
  65. ++packed[i];
  66. // if we haven't overflowed (0xff -> 0x0), than we are done
  67. if (packed[i] != 0) {
  68. break;
  69. }
  70. }
  71. return (IOAddress::fromBytes(addr.getFamily(), packed));
  72. }
  73. isc::asiolink::IOAddress
  74. AllocEngine::IterativeAllocator::increasePrefix(const isc::asiolink::IOAddress& prefix,
  75. const uint8_t prefix_len) {
  76. if (!prefix.isV6()) {
  77. isc_throw(BadValue, "Prefix operations are for IPv6 only (attempted to "
  78. "increase prefix " << prefix << ")");
  79. }
  80. // Get a buffer holding an address.
  81. const std::vector<uint8_t>& vec = prefix.toBytes();
  82. if (prefix_len < 1 || prefix_len > 128) {
  83. isc_throw(BadValue, "Cannot increase prefix: invalid prefix length: "
  84. << prefix_len);
  85. }
  86. // Brief explanation what happens here:
  87. // http://www.youtube.com/watch?v=NFQCYpIHLNQ
  88. uint8_t n_bytes = (prefix_len - 1)/8;
  89. uint8_t n_bits = 8 - (prefix_len - n_bytes*8);
  90. uint8_t mask = 1 << n_bits;
  91. // Longer explanation: n_bytes specifies number of full bytes that are
  92. // in-prefix. They can also be used as an offset for the first byte that
  93. // is not in prefix. n_bits specifies number of bits on the last byte that
  94. // is (often partially) in prefix. For example for a /125 prefix, the values
  95. // are 15 and 3, respectively. Mask is a bitmask that has the least
  96. // significant bit from the prefix set.
  97. uint8_t packed[V6ADDRESS_LEN];
  98. // Copy the address. It must be V6, but we already checked that.
  99. std::memcpy(packed, &vec[0], V6ADDRESS_LEN);
  100. // Can we safely increase only the last byte in prefix without overflow?
  101. if (packed[n_bytes] + uint16_t(mask) < 256u) {
  102. packed[n_bytes] += mask;
  103. return (IOAddress::fromBytes(AF_INET6, packed));
  104. }
  105. // Overflow (done on uint8_t, but the sum is greater than 255)
  106. packed[n_bytes] += mask;
  107. // Deal with the overflow. Start increasing the least significant byte
  108. for (int i = n_bytes - 1; i >= 0; --i) {
  109. ++packed[i];
  110. // If we haven't overflowed (0xff->0x0) the next byte, then we are done
  111. if (packed[i] != 0) {
  112. break;
  113. }
  114. }
  115. return (IOAddress::fromBytes(AF_INET6, packed));
  116. }
  117. isc::asiolink::IOAddress
  118. AllocEngine::IterativeAllocator::pickAddress(const SubnetPtr& subnet,
  119. const DuidPtr&,
  120. const IOAddress&) {
  121. // Is this prefix allocation?
  122. bool prefix = pool_type_ == Lease::TYPE_PD;
  123. // Let's get the last allocated address. It is usually set correctly,
  124. // but there are times when it won't be (like after removing a pool or
  125. // perhaps restarting the server).
  126. IOAddress last = subnet->getLastAllocated(pool_type_);
  127. const PoolCollection& pools = subnet->getPools(pool_type_);
  128. if (pools.empty()) {
  129. isc_throw(AllocFailed, "No pools defined in selected subnet");
  130. }
  131. // first we need to find a pool the last address belongs to.
  132. PoolCollection::const_iterator it;
  133. for (it = pools.begin(); it != pools.end(); ++it) {
  134. if ((*it)->inRange(last)) {
  135. break;
  136. }
  137. }
  138. // last one was bogus for one of several reasons:
  139. // - we just booted up and that's the first address we're allocating
  140. // - a subnet was removed or other reconfiguration just completed
  141. // - perhaps allocation algorithm was changed
  142. if (it == pools.end()) {
  143. // ok to access first element directly. We checked that pools is non-empty
  144. IOAddress next = pools[0]->getFirstAddress();
  145. subnet->setLastAllocated(pool_type_, next);
  146. return (next);
  147. }
  148. // Ok, we have a pool that the last address belonged to, let's use it.
  149. IOAddress next("::");
  150. if (!prefix) {
  151. next = increaseAddress(last); // basically addr++
  152. } else {
  153. Pool6Ptr pool6 = boost::dynamic_pointer_cast<Pool6>(*it);
  154. if (!pool6) {
  155. // Something is gravely wrong here
  156. isc_throw(Unexpected, "Wrong type of pool: " << (*it)->toText()
  157. << " is not Pool6");
  158. }
  159. // Get the next prefix
  160. next = increasePrefix(last, pool6->getLength());
  161. }
  162. if ((*it)->inRange(next)) {
  163. // the next one is in the pool as well, so we haven't hit pool boundary yet
  164. subnet->setLastAllocated(pool_type_, next);
  165. return (next);
  166. }
  167. // We hit pool boundary, let's try to jump to the next pool and try again
  168. ++it;
  169. if (it == pools.end()) {
  170. // Really out of luck today. That was the last pool. Let's rewind
  171. // to the beginning.
  172. next = pools[0]->getFirstAddress();
  173. subnet->setLastAllocated(pool_type_, next);
  174. return (next);
  175. }
  176. // there is a next pool, let's try first address from it
  177. next = (*it)->getFirstAddress();
  178. subnet->setLastAllocated(pool_type_, next);
  179. return (next);
  180. }
  181. AllocEngine::HashedAllocator::HashedAllocator(Lease::Type lease_type)
  182. :Allocator(lease_type) {
  183. isc_throw(NotImplemented, "Hashed allocator is not implemented");
  184. }
  185. isc::asiolink::IOAddress
  186. AllocEngine::HashedAllocator::pickAddress(const SubnetPtr&,
  187. const DuidPtr&,
  188. const IOAddress&) {
  189. isc_throw(NotImplemented, "Hashed allocator is not implemented");
  190. }
  191. AllocEngine::RandomAllocator::RandomAllocator(Lease::Type lease_type)
  192. :Allocator(lease_type) {
  193. isc_throw(NotImplemented, "Random allocator is not implemented");
  194. }
  195. isc::asiolink::IOAddress
  196. AllocEngine::RandomAllocator::pickAddress(const SubnetPtr&,
  197. const DuidPtr&,
  198. const IOAddress&) {
  199. isc_throw(NotImplemented, "Random allocator is not implemented");
  200. }
  201. AllocEngine::AllocEngine(AllocType engine_type, unsigned int attempts,
  202. bool ipv6)
  203. :attempts_(attempts) {
  204. // Choose the basic (normal address) lease type
  205. Lease::Type basic_type = ipv6 ? Lease::TYPE_NA : Lease::TYPE_V4;
  206. // Initalize normal address allocators
  207. switch (engine_type) {
  208. case ALLOC_ITERATIVE:
  209. allocators_[basic_type] = AllocatorPtr(new IterativeAllocator(basic_type));
  210. break;
  211. case ALLOC_HASHED:
  212. allocators_[basic_type] = AllocatorPtr(new HashedAllocator(basic_type));
  213. break;
  214. case ALLOC_RANDOM:
  215. allocators_[basic_type] = AllocatorPtr(new RandomAllocator(basic_type));
  216. break;
  217. default:
  218. isc_throw(BadValue, "Invalid/unsupported allocation algorithm");
  219. }
  220. // If this is IPv6 allocation engine, initalize also temporary addrs
  221. // and prefixes
  222. if (ipv6) {
  223. switch (engine_type) {
  224. case ALLOC_ITERATIVE:
  225. allocators_[Lease::TYPE_TA] = AllocatorPtr(new IterativeAllocator(Lease::TYPE_TA));
  226. allocators_[Lease::TYPE_PD] = AllocatorPtr(new IterativeAllocator(Lease::TYPE_PD));
  227. break;
  228. case ALLOC_HASHED:
  229. allocators_[Lease::TYPE_TA] = AllocatorPtr(new HashedAllocator(Lease::TYPE_TA));
  230. allocators_[Lease::TYPE_PD] = AllocatorPtr(new HashedAllocator(Lease::TYPE_PD));
  231. break;
  232. case ALLOC_RANDOM:
  233. allocators_[Lease::TYPE_TA] = AllocatorPtr(new RandomAllocator(Lease::TYPE_TA));
  234. allocators_[Lease::TYPE_PD] = AllocatorPtr(new RandomAllocator(Lease::TYPE_PD));
  235. break;
  236. default:
  237. isc_throw(BadValue, "Invalid/unsupported allocation algorithm");
  238. }
  239. }
  240. // Register hook points
  241. hook_index_lease4_select_ = Hooks.hook_index_lease4_select_;
  242. hook_index_lease6_select_ = Hooks.hook_index_lease6_select_;
  243. }
  244. Lease6Collection
  245. AllocEngine::allocateLeases6(ClientContext6& ctx) {
  246. try {
  247. if (!ctx.subnet_) {
  248. isc_throw(InvalidOperation, "Subnet is required for allocation");
  249. }
  250. if (!ctx.duid_) {
  251. isc_throw(InvalidOperation, "DUID is mandatory for allocation");
  252. }
  253. // Check which host reservation mode is supported in this subnet.
  254. Subnet::HRMode hr_mode = ctx.subnet_->getHostReservationMode();
  255. // Check if there's a host reservation for this client. Attempt to get
  256. // host info only if reservations are not disabled.
  257. if (hr_mode != Subnet::HR_DISABLED) {
  258. ctx.host_ = HostMgr::instance().get6(ctx.subnet_->getID(), ctx.duid_,
  259. ctx.hwaddr_);
  260. }
  261. // Check if there are existing leases for that subnet/duid/iaid
  262. // combination.
  263. Lease6Collection leases =
  264. LeaseMgrFactory::instance().getLeases6(ctx.type_, *ctx.duid_, ctx.iaid_,
  265. ctx.subnet_->getID());
  266. // Now do the checks:
  267. // Case 1. if there are no leases, and there are reservations...
  268. // 1.1. are the reserved addresses are used by someone else?
  269. // yes: we have a problem
  270. // no: assign them => done
  271. // Case 2. if there are leases and there are no reservations...
  272. // 2.1 are the leases reserved for someone else?
  273. // yes: release them, assign something else
  274. // no: renew them => done
  275. // Case 3. if there are leases and there are reservations...
  276. // 3.1 are the leases matching reservations?
  277. // yes: renew them => done
  278. // no: release existing leases, assign new ones based on reservations
  279. // Case 4. if there are no leases and no reservations...
  280. // assign new leases
  281. //
  282. // We could implement those checks as nested ifs, but the performance
  283. // gain would be minimal and the code readibility loss would be substantial.
  284. // Hence independent checks.
  285. // Case 1: There are no leases and there's a reservation for this host.
  286. if ((hr_mode != Subnet::HR_DISABLED) && leases.empty() && ctx.host_) {
  287. // Try to allocate leases that match reservations. Typically this will
  288. // succeed, except cases where the reserved addresses are used by
  289. // someone else.
  290. allocateReservedLeases6(ctx, leases);
  291. // If we got at least one lease, we're good to go.
  292. if (!leases.empty()) {
  293. return (leases);
  294. }
  295. // If not, we'll need to continue and will eventually fall into case 4:
  296. // getting a regular lease. That could happen when we're processing
  297. // request from client X, there's a reserved address A for X, but
  298. // A is currently used by client Y. We can't immediately reassign A
  299. // from X to Y, because Y keeps using it, so X would send Decline right
  300. // away. Need to wait till Y renews, then we can release A, so it
  301. // will become available for X.
  302. }
  303. // Case 2: There are existing leases and there are no reservations.
  304. //
  305. // There is at least one lease for this client and there are no reservations.
  306. // We will return these leases for the client, but we may need to update
  307. // FQDN information.
  308. if (!leases.empty() && !ctx.host_) {
  309. // Check if the existing leases are reserved for someone else.
  310. // If they're not, we're ok to keep using them.
  311. removeNonmatchingReservedLeases6(ctx, leases);
  312. if (!leases.empty()) {
  313. // Return old leases so the server can see what has changed.
  314. return (updateFqdnData(leases, ctx.fwd_dns_update_,
  315. ctx.rev_dns_update_,
  316. ctx.hostname_, ctx.fake_allocation_));
  317. }
  318. // If leases is empty at this stage, it means that we used to have
  319. // leases for this client, but we checked and those leases are reserved
  320. // for someone else, so we lost them. We will need to continue and
  321. // will finally end up in case 4 (no leases, no reservations), so we'll
  322. // assign something new.
  323. }
  324. // Case 3: There are leases and there are reservations.
  325. if (!leases.empty() && ctx.host_) {
  326. // First, check if have leases matching reservations, and add new
  327. // leases if we don't have them.
  328. allocateReservedLeases6(ctx, leases);
  329. // leases now contain both existing and new leases that were created
  330. // from reservations.
  331. // Second, let's remove leases that are reserved for someone else.
  332. // This applies to any existing leases.
  333. removeNonmatchingReservedLeases6(ctx, leases);
  334. // leases now contain existing and new leases, but we removed those
  335. // leases that are reserved for someone else (non-matching reserved).
  336. // There's one more check to do. Let's remove leases that are not
  337. // matching reservations, i.e. if client X has address A, but there's
  338. // a reservation for address B, we should release A and reassign B.
  339. // Caveat: do this only if we have at least one reserved address.
  340. removeNonreservedLeases6(ctx, leases);
  341. // All checks are done. Let's hope we do have any leases left.
  342. // If we have any leases left, let's return them and we're done.
  343. if (!leases.empty()) {
  344. return (leases);
  345. }
  346. // If we don't have any leases at this stage, it means that we hit
  347. // one of the following cases:
  348. // - we have a reservation, but it's not for this IAID/ia-type and
  349. // we had to return the address we were using
  350. // - we have a reservation for this iaid/ia-type, but the reserved
  351. // address is currently used by someone else. We can't assign it
  352. // yet.
  353. // - we had an address, but we just discovered that it's reserved for
  354. // someone else, so we released it.
  355. }
  356. // Case 4: One of the following is true:
  357. // - we don't have leases and there are no reservations
  358. // - we used to have leases, but we lost them, because they are now
  359. // reserved for someone else
  360. // - we have a reservation, but it is not usable yet, because the address
  361. // is still used by someone else
  362. //
  363. // In any case, we need to go through normal lease assignment process
  364. // for now.
  365. leases = allocateUnreservedLeases6(ctx);
  366. return (leases);
  367. // Unable to allocate an address, return an empty lease.
  368. LOG_WARN(dhcpsrv_logger, DHCPSRV_ADDRESS6_ALLOC_FAIL).arg(attempts_);
  369. } catch (const isc::Exception& e) {
  370. // Some other error, return an empty lease.
  371. LOG_ERROR(dhcpsrv_logger, DHCPSRV_ADDRESS6_ALLOC_ERROR).arg(e.what());
  372. }
  373. return (Lease6Collection());
  374. }
  375. Lease6Collection
  376. AllocEngine::allocateUnreservedLeases6(ClientContext6& ctx) {
  377. AllocatorPtr allocator = getAllocator(ctx.type_);
  378. if (!allocator) {
  379. isc_throw(InvalidOperation, "No allocator specified for "
  380. << Lease6::typeToText(ctx.type_));
  381. }
  382. // Check which host reservation mode is supported in this subnet.
  383. Subnet::HRMode hr_mode = ctx.subnet_->getHostReservationMode();
  384. Lease6Collection leases;
  385. IOAddress hint("::");
  386. if (!ctx.hints_.empty()) {
  387. /// @todo: We support only one hint for now
  388. hint = ctx.hints_[0];
  389. }
  390. // check if the hint is in pool and is available
  391. // This is equivalent of subnet->inPool(hint), but returns the pool
  392. Pool6Ptr pool = boost::dynamic_pointer_cast<
  393. Pool6>(ctx.subnet_->getPool(ctx.type_, hint, false));
  394. if (pool) {
  395. /// @todo: We support only one hint for now
  396. Lease6Ptr lease = LeaseMgrFactory::instance().getLease6(ctx.type_, hint);
  397. if (!lease) {
  398. // In-pool reservations: Check if this address is reserved for someone
  399. // else. There is no need to check for whom it is reserved, because if
  400. // it has been reserved for us we would have already allocated a lease.
  401. ConstHostPtr host;
  402. if (hr_mode != Subnet::HR_DISABLED) {
  403. host = HostMgr::instance().get6(ctx.subnet_->getID(), hint);
  404. }
  405. if (!host) {
  406. // If the in-pool reservations are disabled, or there is no
  407. // reservation for a given hint, we're good to go.
  408. // The hint is valid and not currently used, let's create a
  409. // lease for it
  410. lease = createLease6(ctx, hint, pool->getLength());
  411. // It can happen that the lease allocation failed (we could
  412. // have lost the race condition. That means that the hint is
  413. // lo longer usable and we need to continue the regular
  414. // allocation path.
  415. if (lease) {
  416. /// @todo: We support only one lease per ia for now
  417. Lease6Collection collection;
  418. collection.push_back(lease);
  419. return (collection);
  420. }
  421. }
  422. } else {
  423. // If the lease is expired, we may likely reuse it, but...
  424. if (lease->expired()) {
  425. ConstHostPtr host;
  426. if (hr_mode != Subnet::HR_DISABLED) {
  427. host = HostMgr::instance().get6(ctx.subnet_->getID(), hint);
  428. }
  429. // Let's check if there is a reservation for this address.
  430. if (!host) {
  431. // Copy an existing, expired lease so as it can be returned
  432. // to the caller.
  433. Lease6Ptr old_lease(new Lease6(*lease));
  434. ctx.old_leases_.push_back(old_lease);
  435. /// We found a lease and it is expired, so we can reuse it
  436. lease = reuseExpiredLease(lease, ctx, pool->getLength());
  437. /// @todo: We support only one lease per ia for now
  438. leases.push_back(lease);
  439. return (leases);
  440. }
  441. }
  442. }
  443. }
  444. // Hint is in the pool but is not available. Search the pool until first of
  445. // the following occurs:
  446. // - we find a free address
  447. // - we find an address for which the lease has expired
  448. // - we exhaust number of tries
  449. //
  450. // @todo: Current code does not handle pool exhaustion well. It will be
  451. // improved. Current problems:
  452. // 1. with attempts set to too large value (e.g. 1000) and a small pool (e.g.
  453. // 10 addresses), we will iterate over it 100 times before giving up
  454. // 2. attempts 0 mean unlimited (this is really UINT_MAX, not infinite)
  455. // 3. the whole concept of infinite attempts is just asking for infinite loop
  456. // We may consider some form or reference counting (this pool has X addresses
  457. // left), but this has one major problem. We exactly control allocation
  458. // moment, but we currently do not control expiration time at all
  459. unsigned int i = attempts_;
  460. do {
  461. IOAddress candidate = allocator->pickAddress(ctx.subnet_, ctx.duid_, hint);
  462. /// In-pool reservations: Check if this address is reserved for someone
  463. /// else. There is no need to check for whom it is reserved, because if
  464. /// it has been reserved for us we would have already allocated a lease.
  465. if (hr_mode == Subnet::HR_IN_POOL &&
  466. HostMgr::instance().get6(ctx.subnet_->getID(), candidate)) {
  467. // Don't allocate.
  468. continue;
  469. }
  470. // The first step is to find out prefix length. It is 128 for
  471. // non-PD leases.
  472. uint8_t prefix_len = 128;
  473. if (ctx.type_ == Lease::TYPE_PD) {
  474. Pool6Ptr pool = boost::dynamic_pointer_cast<Pool6>(
  475. ctx.subnet_->getPool(ctx.type_, candidate, false));
  476. prefix_len = pool->getLength();
  477. }
  478. Lease6Ptr existing = LeaseMgrFactory::instance().getLease6(ctx.type_,
  479. candidate);
  480. if (!existing) {
  481. // there's no existing lease for selected candidate, so it is
  482. // free. Let's allocate it.
  483. Lease6Ptr lease = createLease6(ctx, candidate, prefix_len);
  484. if (lease) {
  485. // We are allocating a new lease (not renewing). So, the
  486. // old lease should be NULL.
  487. ctx.old_leases_.clear();
  488. Lease6Collection collection;
  489. collection.push_back(lease);
  490. return (collection);
  491. }
  492. // Although the address was free just microseconds ago, it may have
  493. // been taken just now. If the lease insertion fails, we continue
  494. // allocation attempts.
  495. } else {
  496. if (existing->expired()) {
  497. // Copy an existing, expired lease so as it can be returned
  498. // to the caller.
  499. Lease6Ptr old_lease(new Lease6(*existing));
  500. ctx.old_leases_.push_back(old_lease);
  501. existing = reuseExpiredLease(existing,
  502. ctx,
  503. prefix_len);
  504. Lease6Collection collection;
  505. collection.push_back(existing);
  506. return (collection);
  507. }
  508. }
  509. // Continue trying allocation until we run out of attempts
  510. // (or attempts are set to 0, which means infinite)
  511. --i;
  512. } while ((i > 0) || !attempts_);
  513. // We failed to allocate anything. Let's return empty collection.
  514. return (Lease6Collection());
  515. }
  516. void
  517. AllocEngine::allocateReservedLeases6(ClientContext6& ctx, Lease6Collection& existing_leases) {
  518. // If there are no reservations or the reservation is v4, there's nothing to do.
  519. if (!ctx.host_ || !ctx.host_->hasIPv6Reservation()) {
  520. return;
  521. }
  522. // Let's convert this from Lease::Type to IPv6Reserv::Type
  523. IPv6Resrv::Type type = ctx.type_ == Lease::TYPE_NA ? IPv6Resrv::TYPE_NA : IPv6Resrv::TYPE_PD;
  524. // Get the IPv6 reservations of specified type.
  525. const IPv6ResrvRange& reservs = ctx.host_->getIPv6Reservations(type);
  526. if (std::distance(reservs.first, reservs.second) == 0) {
  527. // No reservations? We're done here.
  528. return;
  529. }
  530. for (IPv6ResrvIterator resv = reservs.first; resv != reservs.second; ++resv) {
  531. // We do have a reservation for addr.
  532. IOAddress addr = resv->second.getPrefix();
  533. uint8_t prefix_len = resv->second.getPrefixLen();
  534. // If there's a lease for this address, let's not create it.
  535. // It doesn't matter whether it is for this client or for someone else.
  536. if (LeaseMgrFactory::instance().getLease6(ctx.type_, addr)) {
  537. continue;
  538. }
  539. // Ok, let's create a new lease...
  540. Lease6Ptr lease = createLease6(ctx, addr, prefix_len);
  541. // ... and add it to the existing leases list.
  542. existing_leases.push_back(lease);
  543. }
  544. }
  545. void
  546. AllocEngine::removeNonmatchingReservedLeases6(ClientContext6& ctx,
  547. Lease6Collection& existing_leases) {
  548. /// @todo
  549. if (!ctx.host_ || existing_leases.empty()) {
  550. }
  551. }
  552. void
  553. AllocEngine::removeNonreservedLeases6(ClientContext6& ctx,
  554. Lease6Collection& existing_leases) {
  555. /// @todo
  556. if (!ctx.host_ || existing_leases.empty()) {
  557. }
  558. }
  559. Lease4Ptr
  560. AllocEngine::allocateLease4(const SubnetPtr& subnet, const ClientIdPtr& clientid,
  561. const HWAddrPtr& hwaddr, const IOAddress& hint,
  562. const bool fwd_dns_update, const bool rev_dns_update,
  563. const std::string& hostname, bool fake_allocation,
  564. const isc::hooks::CalloutHandlePtr& callout_handle,
  565. Lease4Ptr& old_lease) {
  566. // The NULL pointer indicates that the old lease didn't exist. It may
  567. // be later set to non NULL value if existing lease is found in the
  568. // database.
  569. old_lease.reset();
  570. try {
  571. // Set allocator.
  572. AllocatorPtr allocator = getAllocator(Lease::TYPE_V4);
  573. if (!subnet) {
  574. isc_throw(BadValue, "Can't allocate IPv4 address without subnet");
  575. }
  576. if (!hwaddr) {
  577. isc_throw(BadValue, "HWAddr must be defined");
  578. }
  579. /// @todo The context for lease allocation should really be created
  580. /// by the DHCPv4 server and passed to this function. The reason for
  581. /// this is that the server should retrieve the Host object for the
  582. /// client because the Host object contains the data not only useful
  583. /// for the address allocation but also hostname and DHCP options
  584. /// for the client. The Host object should be passed in the context.
  585. /// Making this change would require a change to the allocateLease4
  586. /// API which would in turn require lots of changes in unit tests.
  587. /// The ticket introducing a context and host reservation in the
  588. /// allocation engine is complex enough by itself to warrant that
  589. /// the API change is done with a separate ticket.
  590. ClientContext4 ctx;
  591. ctx.subnet_ = subnet;
  592. ctx.clientid_ = clientid;
  593. ctx.hwaddr_ = hwaddr;
  594. ctx.requested_address_ = hint;
  595. ctx.fwd_dns_update_ = fwd_dns_update;
  596. ctx.rev_dns_update_ = rev_dns_update;
  597. ctx.hostname_ = hostname;
  598. ctx.fake_allocation_ = fake_allocation;
  599. ctx.callout_handle_ = callout_handle;
  600. ctx.old_lease_ = old_lease;
  601. ctx.host_ = HostMgr::instance().get4(subnet->getID(), hwaddr);
  602. // If there is a reservation for this client we want to allocate the
  603. // reserved address to the client, rather than any other address.
  604. if (ctx.host_) {
  605. // In some cases the client doesn't supply any address, e.g. when
  606. // it sends a DHCPDISCOVER. In such cases, we use the reserved
  607. // address as a hint.
  608. if (ctx.requested_address_ == IOAddress("0.0.0.0")) {
  609. ctx.requested_address_ = ctx.host_->getIPv4Reservation();
  610. // If the client supplied an address we have to check if this
  611. // address is reserved for this client. If not, we will send
  612. // DHCPNAK to inform the client that we were not able to
  613. // assign a requested address. The fake allocation (DHCPDISCOVER
  614. // case) is an exception. In such case we treat the address
  615. // supplied by the client as a hint, but we may offer address
  616. // other than desired by the client. So, we don't return an
  617. // empty lease.
  618. } else if (!ctx.fake_allocation_ &&
  619. (ctx.requested_address_ != ctx.host_->getIPv4Reservation())) {
  620. return (Lease4Ptr());
  621. }
  622. }
  623. // Check if the client has any leases in the lease database, using HW
  624. // address or client identifier.
  625. LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
  626. Lease4Ptr existing = lease_mgr.getLease4(*hwaddr, ctx.subnet_->getID());
  627. if (!existing && clientid) {
  628. existing = lease_mgr.getLease4(*clientid, ctx.subnet_->getID());
  629. }
  630. // If client has a lease there are two choices. The server may need
  631. // to renew (no address change) the lease. Or, the server may need
  632. // to replace the lease with a different one. This is the case when
  633. // the server has a dynamically assigned lease but an administrator
  634. // has made a new reservation for the client for a different address.
  635. if (existing) {
  636. existing = reallocateClientLease(existing, ctx);
  637. // The interrupt_processing_ flag indicates that the lease
  638. // reallocation was not successful and that the allocation
  639. // engine should cease allocation process for this client.
  640. // This may occur when the client is trying to renew the
  641. // lease which is reserved for someone else. The server should
  642. // send DHCPNAK to indicate that the client should try to
  643. // start over the allocation process.
  644. if (ctx.interrupt_processing_) {
  645. old_lease = ctx.old_lease_;
  646. return (Lease4Ptr());
  647. // If we tried to reallocate the reserved lease we return
  648. // at this point regardless if reallocation failed or passed.
  649. // We also return when allocation passed, no matter if this
  650. // was a reserved address or not.
  651. } else if (ctx.host_ || existing) {
  652. old_lease = ctx.old_lease_;
  653. return (existing);
  654. }
  655. }
  656. // There is no lease in the database for this client, so we will
  657. // proceed with a new allocation. We will try to allocate a
  658. // reserved address or an address from a dynamic pool if there is
  659. // no reservation.
  660. if (ctx.host_ || subnet->inPool(Lease::TYPE_V4, ctx.requested_address_)) {
  661. // If a client is requesting specific IP address, but the
  662. // reservation was made for a different address the server returns
  663. // NAK to the client. By returning NULL lease here we indicate to
  664. // the server that we're not able to fulfil client's request for the
  665. // particular IP address. We don't return NULL lease in case of the
  666. // fake allocation (DHCPDISCOVER) because in this case the address
  667. // supplied by the client is only a hint.
  668. if (!ctx.fake_allocation_ && ctx.host_ &&
  669. (ctx.requested_address_ != IOAddress("0.0.0.0")) &&
  670. (ctx.host_->getIPv4Reservation() != ctx.requested_address_)) {
  671. return (Lease4Ptr());
  672. }
  673. // The reserved address always takes precedence over an address
  674. // supplied by the client (renewed address or requested).
  675. const IOAddress& candidate = ctx.host_ ?
  676. ctx.host_->getIPv4Reservation() : ctx.requested_address_;
  677. // Once we picked an address we want to allocate, we have to check
  678. // if this address is available.
  679. existing = LeaseMgrFactory::instance().getLease4(candidate);
  680. if (!existing) {
  681. // The candidate address is currently unused. Let's create a
  682. // lease for it.
  683. Lease4Ptr lease = createLease4(subnet, clientid, hwaddr,
  684. candidate, fwd_dns_update,
  685. rev_dns_update,
  686. hostname, callout_handle,
  687. fake_allocation);
  688. // If we have allocated the lease let's return it. Also,
  689. // always return when tried to allocate reserved address,
  690. // regardless if allocation was successful or not. If it
  691. // was not successful, we will return a NULL pointer which
  692. // indicates to the server that it should send NAK to the
  693. // client.
  694. if (lease || ctx.host_) {
  695. return (lease);
  696. }
  697. // There is a lease for this address in the lease database but
  698. // it is possible that the lease has expired, in which case
  699. // we will be able to reuse it.
  700. } else {
  701. if (existing->expired()) {
  702. // Save the old lease, before reusing it.
  703. old_lease.reset(new Lease4(*existing));
  704. return (reuseExpiredLease(existing, ctx));
  705. // The existing lease is not expired (is in use by some
  706. // other client). If we are trying to get this lease because
  707. // the address has been reserved for the client we have no
  708. // choice but to return a NULL lease to indicate that the
  709. // allocation has failed.
  710. } else if (ctx.host_) {
  711. return (Lease4Ptr());
  712. }
  713. }
  714. }
  715. // No address was requested, requested address was not in pool or the
  716. // allocation was not successful so far. Let's try to find a different
  717. // address for the client. Search the pool until first of the following
  718. // occurs:
  719. // - we find a free address
  720. // - we find an address for which the lease has expired
  721. // - we exhaust the number of tries
  722. //
  723. /// @todo: Current code does not handle pool exhaustion well. It will be
  724. /// improved. Current problems:
  725. /// 1. with attempts set to too large value (e.g. 1000) and a small pool (e.g.
  726. /// 10 addresses), we will iterate over it 100 times before giving up
  727. /// 2. attempts 0 mean unlimited (this is really UINT_MAX, not infinite)
  728. /// 3. the whole concept of infinite attempts is just asking for infinite loop
  729. /// We may consider some form or reference counting (this pool has X addresses
  730. /// left), but this has one major problem. We exactly control allocation
  731. /// moment, but we currently do not control expiration time at all
  732. unsigned int i = attempts_;
  733. do {
  734. IOAddress candidate = allocator->pickAddress(subnet, clientid,
  735. ctx.requested_address_);
  736. // Check if this address is reserved. There is no need to check for
  737. // whom it is reserved, because if it has been reserved for us we would
  738. // have already allocated a lease.
  739. if (HostMgr::instance().get4(subnet->getID(), candidate)) {
  740. // Don't allocate a reserved address.
  741. continue;
  742. }
  743. Lease4Ptr existing = LeaseMgrFactory::instance().getLease4(candidate);
  744. if (!existing) {
  745. // there's no existing lease for selected candidate, so it is
  746. // free. Let's allocate it.
  747. Lease4Ptr lease = createLease4(subnet, clientid, hwaddr,
  748. candidate, fwd_dns_update,
  749. rev_dns_update, hostname,
  750. callout_handle, fake_allocation);
  751. if (lease) {
  752. return (lease);
  753. }
  754. // Although the address was free just microseconds ago, it may have
  755. // been taken just now. If the lease insertion fails, we continue
  756. // allocation attempts.
  757. } else {
  758. if (existing->expired()) {
  759. // Save old lease before reusing it.
  760. old_lease.reset(new Lease4(*existing));
  761. return (reuseExpiredLease(existing, ctx));
  762. }
  763. }
  764. // Continue trying allocation until we run out of attempts
  765. // (or attempts are set to 0, which means infinite)
  766. --i;
  767. } while ((i > 0) || !attempts_);
  768. // Unable to allocate an address, return an empty lease.
  769. LOG_WARN(dhcpsrv_logger, DHCPSRV_ADDRESS4_ALLOC_FAIL).arg(attempts_);
  770. } catch (const isc::Exception& e) {
  771. // Some other error, return an empty lease.
  772. LOG_ERROR(dhcpsrv_logger, DHCPSRV_ADDRESS4_ALLOC_ERROR).arg(e.what());
  773. }
  774. return (Lease4Ptr());
  775. }
  776. Lease4Ptr
  777. AllocEngine::renewLease4(const Lease4Ptr& lease,
  778. AllocEngine::ClientContext4& ctx) {
  779. if (!lease) {
  780. isc_throw(BadValue, "null lease specified for renewLease4");
  781. }
  782. // The ctx.host_ possibly contains a reservation for the client for which
  783. // we are renewing a lease. If this reservation exists, we assume that
  784. // there is no conflict in assigning the address to this client. Note
  785. // that the reallocateClientLease checks if the address reserved for
  786. // the client matches the address in the lease we're renewing here.
  787. if (!ctx.host_) {
  788. ConstHostPtr host = HostMgr::instance().get4(ctx.subnet_->getID(),
  789. lease->addr_);
  790. // Do not renew the lease if:
  791. // - If address is reserved for someone else or ...
  792. // - renewed address doesn't belong to a pool.
  793. if ((host && ctx.hwaddr_ && (*host->getHWAddress() != *ctx.hwaddr_)) ||
  794. (!ctx.subnet_->inPool(Lease::TYPE_V4, lease->addr_))) {
  795. ctx.interrupt_processing_ = !ctx.fake_allocation_;
  796. return (Lease4Ptr());
  797. }
  798. }
  799. // Let's keep the old data. This is essential if we are using memfile
  800. // (the lease returned points directly to the lease4 object in the database)
  801. // We'll need it if we want to skip update (i.e. roll back renewal)
  802. /// @todo: remove this once #3083 is implemented
  803. Lease4 old_values = *lease;
  804. // Update the lease with the information from the context.
  805. updateLease4Information(lease, ctx);
  806. bool skip = false;
  807. // Execute all callouts registered for lease4_renew.
  808. if (HooksManager::getHooksManager().
  809. calloutsPresent(Hooks.hook_index_lease4_renew_)) {
  810. // Delete all previous arguments
  811. ctx.callout_handle_->deleteAllArguments();
  812. // Subnet from which we do the allocation. Convert the general subnet
  813. // pointer to a pointer to a Subnet4. Note that because we are using
  814. // boost smart pointers here, we need to do the cast using the boost
  815. // version of dynamic_pointer_cast.
  816. Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(ctx.subnet_);
  817. // Pass the parameters
  818. ctx.callout_handle_->setArgument("subnet4", subnet4);
  819. ctx.callout_handle_->setArgument("clientid", ctx.clientid_);
  820. ctx.callout_handle_->setArgument("hwaddr", ctx.hwaddr_);
  821. // Pass the lease to be updated
  822. ctx.callout_handle_->setArgument("lease4", lease);
  823. // Call all installed callouts
  824. HooksManager::callCallouts(Hooks.hook_index_lease4_renew_,
  825. *ctx.callout_handle_);
  826. // Callouts decided to skip the next processing step. The next
  827. // processing step would to actually renew the lease, so skip at this
  828. // stage means "keep the old lease as it is".
  829. if (ctx.callout_handle_->getSkip()) {
  830. skip = true;
  831. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS,
  832. DHCPSRV_HOOK_LEASE4_RENEW_SKIP);
  833. }
  834. }
  835. if (!ctx.fake_allocation_ && !skip) {
  836. // for REQUEST we do update the lease
  837. LeaseMgrFactory::instance().updateLease4(lease);
  838. }
  839. if (skip) {
  840. // Rollback changes (really useful only for memfile)
  841. /// @todo: remove this once #3083 is implemented
  842. *lease = old_values;
  843. }
  844. return (lease);
  845. }
  846. Lease6Ptr AllocEngine::reuseExpiredLease(Lease6Ptr& expired,
  847. ClientContext6& ctx,
  848. uint8_t prefix_len) {
  849. if (!expired->expired()) {
  850. isc_throw(BadValue, "Attempt to recycle lease that is still valid");
  851. }
  852. if (expired->type_ != Lease::TYPE_PD) {
  853. prefix_len = 128; // non-PD lease types must be always /128
  854. }
  855. // address, lease type and prefixlen (0) stay the same
  856. expired->iaid_ = ctx.iaid_;
  857. expired->duid_ = ctx.duid_;
  858. expired->preferred_lft_ = ctx.subnet_->getPreferred();
  859. expired->valid_lft_ = ctx.subnet_->getValid();
  860. expired->t1_ = ctx.subnet_->getT1();
  861. expired->t2_ = ctx.subnet_->getT2();
  862. expired->cltt_ = time(NULL);
  863. expired->subnet_id_ = ctx.subnet_->getID();
  864. expired->fixed_ = false;
  865. expired->hostname_ = ctx.hostname_;
  866. expired->fqdn_fwd_ = ctx.fwd_dns_update_;
  867. expired->fqdn_rev_ = ctx.rev_dns_update_;
  868. expired->prefixlen_ = prefix_len;
  869. /// @todo: log here that the lease was reused (there's ticket #2524 for
  870. /// logging in libdhcpsrv)
  871. // Let's execute all callouts registered for lease6_select
  872. if (ctx.callout_handle_ &&
  873. HooksManager::getHooksManager().calloutsPresent(hook_index_lease6_select_)) {
  874. // Delete all previous arguments
  875. ctx.callout_handle_->deleteAllArguments();
  876. // Pass necessary arguments
  877. // Subnet from which we do the allocation
  878. ctx.callout_handle_->setArgument("subnet6", ctx.subnet_);
  879. // Is this solicit (fake = true) or request (fake = false)
  880. ctx.callout_handle_->setArgument("fake_allocation", ctx.fake_allocation_);
  881. // The lease that will be assigned to a client
  882. ctx.callout_handle_->setArgument("lease6", expired);
  883. // Call the callouts
  884. HooksManager::callCallouts(hook_index_lease6_select_, *ctx.callout_handle_);
  885. // Callouts decided to skip the action. This means that the lease is not
  886. // assigned, so the client will get NoAddrAvail as a result. The lease
  887. // won't be inserted into the database.
  888. if (ctx.callout_handle_->getSkip()) {
  889. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE6_SELECT_SKIP);
  890. return (Lease6Ptr());
  891. }
  892. // Let's use whatever callout returned. Hopefully it is the same lease
  893. // we handled to it.
  894. ctx.callout_handle_->getArgument("lease6", expired);
  895. }
  896. if (!ctx.fake_allocation_) {
  897. // for REQUEST we do update the lease
  898. LeaseMgrFactory::instance().updateLease6(expired);
  899. }
  900. // We do nothing for SOLICIT. We'll just update database when
  901. // the client gets back to us with REQUEST message.
  902. // it's not really expired at this stage anymore - let's return it as
  903. // an updated lease
  904. return (expired);
  905. }
  906. Lease4Ptr
  907. AllocEngine::reuseExpiredLease(Lease4Ptr& expired,
  908. AllocEngine::ClientContext4& ctx) {
  909. if (!expired) {
  910. isc_throw(BadValue, "null lease specified for reuseExpiredLease");
  911. }
  912. if (!ctx.subnet_) {
  913. isc_throw(BadValue, "null subnet specified for the reuseExpiredLease");
  914. }
  915. updateLease4Information(expired, ctx);
  916. expired->fixed_ = false;
  917. /// @todo: log here that the lease was reused (there's ticket #2524 for
  918. /// logging in libdhcpsrv)
  919. // Let's execute all callouts registered for lease4_select
  920. if (ctx.callout_handle_ && HooksManager::getHooksManager()
  921. .calloutsPresent(hook_index_lease4_select_)) {
  922. // Delete all previous arguments
  923. ctx.callout_handle_->deleteAllArguments();
  924. // Pass necessary arguments
  925. // Subnet from which we do the allocation. Convert the general subnet
  926. // pointer to a pointer to a Subnet4. Note that because we are using
  927. // boost smart pointers here, we need to do the cast using the boost
  928. // version of dynamic_pointer_cast.
  929. Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(ctx.subnet_);
  930. ctx.callout_handle_->setArgument("subnet4", subnet4);
  931. // Is this solicit (fake = true) or request (fake = false)
  932. ctx.callout_handle_->setArgument("fake_allocation",
  933. ctx.fake_allocation_);
  934. // The lease that will be assigned to a client
  935. ctx.callout_handle_->setArgument("lease4", expired);
  936. // Call the callouts
  937. HooksManager::callCallouts(hook_index_lease4_select_, *ctx.callout_handle_);
  938. // Callouts decided to skip the action. This means that the lease is not
  939. // assigned, so the client will get NoAddrAvail as a result. The lease
  940. // won't be inserted into the database.
  941. if (ctx.callout_handle_->getSkip()) {
  942. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS,
  943. DHCPSRV_HOOK_LEASE4_SELECT_SKIP);
  944. return (Lease4Ptr());
  945. }
  946. // Let's use whatever callout returned. Hopefully it is the same lease
  947. // we handled to it.
  948. ctx.callout_handle_->getArgument("lease4", expired);
  949. }
  950. if (!ctx.fake_allocation_) {
  951. // for REQUEST we do update the lease
  952. LeaseMgrFactory::instance().updateLease4(expired);
  953. }
  954. // We do nothing for SOLICIT. We'll just update database when
  955. // the client gets back to us with REQUEST message.
  956. // it's not really expired at this stage anymore - let's return it as
  957. // an updated lease
  958. return (expired);
  959. }
  960. Lease4Ptr
  961. AllocEngine::replaceClientLease(Lease4Ptr& lease, ClientContext4& ctx) {
  962. if (!lease) {
  963. isc_throw(BadValue, "null lease specified for replaceClientLease");
  964. }
  965. if (!ctx.subnet_) {
  966. isc_throw(BadValue, "null subnet specified for replaceClientLease");
  967. }
  968. if (ctx.requested_address_ == IOAddress("0.0.0.0")) {
  969. isc_throw(BadValue, "zero address specified for the"
  970. " replaceClientLease");
  971. }
  972. // Remember the previous address for this lease.
  973. IOAddress prev_address = lease->addr_;
  974. if (!ctx.host_) {
  975. ConstHostPtr host = HostMgr::instance().get4(ctx.subnet_->getID(),
  976. ctx.requested_address_);
  977. // If there is a reservation for the new address and the reservation
  978. // is made for another client, do not use this address.
  979. if (host && ctx.hwaddr_ && (*host->getHWAddress() != *ctx.hwaddr_)) {
  980. ctx.interrupt_processing_ = true;
  981. return (Lease4Ptr());
  982. }
  983. lease->addr_ = ctx.requested_address_;
  984. } else {
  985. lease->addr_ = ctx.host_->getIPv4Reservation();
  986. }
  987. updateLease4Information(lease, ctx);
  988. bool skip = false;
  989. // Execute callouts registered for lease4_select.
  990. if (ctx.callout_handle_ && HooksManager::getHooksManager()
  991. .calloutsPresent(hook_index_lease4_select_)) {
  992. // Delete all previous arguments.
  993. ctx.callout_handle_->deleteAllArguments();
  994. // Pass arguments.
  995. Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(ctx.subnet_);
  996. ctx.callout_handle_->setArgument("subnet4", subnet4);
  997. ctx.callout_handle_->setArgument("fake_allocation",
  998. ctx.fake_allocation_);
  999. ctx.callout_handle_->setArgument("lease4", lease);
  1000. HooksManager::callCallouts(hook_index_lease4_select_,
  1001. *ctx.callout_handle_);
  1002. if (ctx.callout_handle_->getSkip()) {
  1003. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS,
  1004. DHCPSRV_HOOK_LEASE4_SELECT_SKIP);
  1005. return (Lease4Ptr());
  1006. }
  1007. // Let's use whatever callout returned.
  1008. ctx.callout_handle_->getArgument("lease4", lease);
  1009. // Callouts decided to skip the next processing step. The next
  1010. // processing step would to actually renew the lease, so skip at this
  1011. // stage means "keep the old lease as it is".
  1012. if (ctx.callout_handle_->getSkip()) {
  1013. skip = true;
  1014. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS,
  1015. DHCPSRV_HOOK_LEASE4_SELECT_SKIP);
  1016. }
  1017. }
  1018. /// @todo There should be a callout for a deletion of an old lease.
  1019. /// The lease4_release callout is in appropriate, because by definition
  1020. /// it is invoked when DHCPRELEASE packet is received.
  1021. if (!ctx.fake_allocation_ && !skip) {
  1022. // We can't use LeaseMgr::updateLease because it identifies the
  1023. // lease by an IP address. Instead, we have to delete an old
  1024. // lease and add a new one.
  1025. LeaseMgrFactory::instance().deleteLease(prev_address);
  1026. LeaseMgrFactory::instance().addLease(lease);
  1027. }
  1028. return (lease);
  1029. }
  1030. Lease4Ptr
  1031. AllocEngine::reallocateClientLease(Lease4Ptr& lease,
  1032. AllocEngine::ClientContext4& ctx) {
  1033. // Save the old lease, before renewal.
  1034. ctx.old_lease_.reset(new Lease4(*lease));
  1035. /// The client's address will need to be modified in case if:
  1036. /// - There is a reservation for the client (likely new one) and
  1037. /// the currently used address is different.
  1038. /// - Client requested some IP address and the requested address
  1039. /// is different than the currently used one. Note that if this
  1040. /// is a DHCPDISCOVER the requested IP address is ignored when
  1041. /// it doesn't match the one in use.
  1042. if ((ctx.host_ && (ctx.host_->getIPv4Reservation() != lease->addr_)) ||
  1043. (!ctx.fake_allocation_ &&
  1044. (ctx.requested_address_ != IOAddress("0.0.0.0")) &&
  1045. (lease->addr_ != ctx.requested_address_))) {
  1046. lease = replaceClientLease(lease, ctx);
  1047. return (lease);
  1048. } else {
  1049. lease = renewLease4(lease, ctx);
  1050. if (lease) {
  1051. return (lease);
  1052. }
  1053. }
  1054. return (Lease4Ptr());
  1055. }
  1056. Lease6Ptr AllocEngine::createLease6(ClientContext6& ctx,
  1057. const IOAddress& addr,
  1058. uint8_t prefix_len) {
  1059. if (ctx.type_ != Lease::TYPE_PD) {
  1060. prefix_len = 128; // non-PD lease types must be always /128
  1061. }
  1062. Lease6Ptr lease(new Lease6(ctx.type_, addr, ctx.duid_, ctx.iaid_,
  1063. ctx.subnet_->getPreferred(), ctx.subnet_->getValid(),
  1064. ctx.subnet_->getT1(), ctx.subnet_->getT2(),
  1065. ctx.subnet_->getID(), ctx.hwaddr_, prefix_len));
  1066. lease->fqdn_fwd_ = ctx.fwd_dns_update_;
  1067. lease->fqdn_rev_ = ctx.rev_dns_update_;
  1068. lease->hostname_ = ctx.hostname_;
  1069. // Let's execute all callouts registered for lease6_select
  1070. if (ctx.callout_handle_ &&
  1071. HooksManager::getHooksManager().calloutsPresent(hook_index_lease6_select_)) {
  1072. // Delete all previous arguments
  1073. ctx.callout_handle_->deleteAllArguments();
  1074. // Pass necessary arguments
  1075. // Subnet from which we do the allocation
  1076. ctx.callout_handle_->setArgument("subnet6", ctx.subnet_);
  1077. // Is this solicit (fake = true) or request (fake = false)
  1078. ctx.callout_handle_->setArgument("fake_allocation", ctx.fake_allocation_);
  1079. ctx.callout_handle_->setArgument("lease6", lease);
  1080. // This is the first callout, so no need to clear any arguments
  1081. HooksManager::callCallouts(hook_index_lease6_select_, *ctx.callout_handle_);
  1082. // Callouts decided to skip the action. This means that the lease is not
  1083. // assigned, so the client will get NoAddrAvail as a result. The lease
  1084. // won't be inserted into the database.
  1085. if (ctx.callout_handle_->getSkip()) {
  1086. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE6_SELECT_SKIP);
  1087. return (Lease6Ptr());
  1088. }
  1089. // Let's use whatever callout returned. Hopefully it is the same lease
  1090. // we handled to it.
  1091. ctx.callout_handle_->getArgument("lease6", lease);
  1092. }
  1093. if (!ctx.fake_allocation_) {
  1094. // That is a real (REQUEST) allocation
  1095. bool status = LeaseMgrFactory::instance().addLease(lease);
  1096. if (status) {
  1097. return (lease);
  1098. } else {
  1099. // One of many failures with LeaseMgr (e.g. lost connection to the
  1100. // database, database failed etc.). One notable case for that
  1101. // is that we are working in multi-process mode and we lost a race
  1102. // (some other process got that address first)
  1103. return (Lease6Ptr());
  1104. }
  1105. } else {
  1106. // That is only fake (SOLICIT without rapid-commit) allocation
  1107. // It is for advertise only. We should not insert the lease into LeaseMgr,
  1108. // but rather check that we could have inserted it.
  1109. Lease6Ptr existing = LeaseMgrFactory::instance().getLease6(
  1110. Lease::TYPE_NA, addr);
  1111. if (!existing) {
  1112. return (lease);
  1113. } else {
  1114. return (Lease6Ptr());
  1115. }
  1116. }
  1117. }
  1118. Lease4Ptr AllocEngine::createLease4(const SubnetPtr& subnet,
  1119. const DuidPtr& clientid,
  1120. const HWAddrPtr& hwaddr,
  1121. const IOAddress& addr,
  1122. const bool fwd_dns_update,
  1123. const bool rev_dns_update,
  1124. const std::string& hostname,
  1125. const isc::hooks::CalloutHandlePtr& callout_handle,
  1126. bool fake_allocation /*= false */ ) {
  1127. if (!hwaddr) {
  1128. isc_throw(BadValue, "Can't create a lease with NULL HW address");
  1129. }
  1130. time_t now = time(NULL);
  1131. // @todo: remove this kludge after ticket #2590 is implemented
  1132. std::vector<uint8_t> local_copy;
  1133. if (clientid) {
  1134. local_copy = clientid->getDuid();
  1135. }
  1136. Lease4Ptr lease(new Lease4(addr, hwaddr, &local_copy[0], local_copy.size(),
  1137. subnet->getValid(), subnet->getT1(), subnet->getT2(),
  1138. now, subnet->getID()));
  1139. // Set FQDN specific lease parameters.
  1140. lease->fqdn_fwd_ = fwd_dns_update;
  1141. lease->fqdn_rev_ = rev_dns_update;
  1142. lease->hostname_ = hostname;
  1143. // Let's execute all callouts registered for lease4_select
  1144. if (callout_handle &&
  1145. HooksManager::getHooksManager().calloutsPresent(hook_index_lease4_select_)) {
  1146. // Delete all previous arguments
  1147. callout_handle->deleteAllArguments();
  1148. // Pass necessary arguments
  1149. // Subnet from which we do the allocation (That's as far as we can go
  1150. // with using SubnetPtr to point to Subnet4 object. Users should not
  1151. // be confused with dynamic_pointer_casts. They should get a concrete
  1152. // pointer (Subnet4Ptr) pointing to a Subnet4 object.
  1153. Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(subnet);
  1154. callout_handle->setArgument("subnet4", subnet4);
  1155. // Is this solicit (fake = true) or request (fake = false)
  1156. callout_handle->setArgument("fake_allocation", fake_allocation);
  1157. // Pass the intended lease as well
  1158. callout_handle->setArgument("lease4", lease);
  1159. // This is the first callout, so no need to clear any arguments
  1160. HooksManager::callCallouts(hook_index_lease4_select_, *callout_handle);
  1161. // Callouts decided to skip the action. This means that the lease is not
  1162. // assigned, so the client will get NoAddrAvail as a result. The lease
  1163. // won't be inserted into the database.
  1164. if (callout_handle->getSkip()) {
  1165. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE4_SELECT_SKIP);
  1166. return (Lease4Ptr());
  1167. }
  1168. // Let's use whatever callout returned. Hopefully it is the same lease
  1169. // we handled to it.
  1170. callout_handle->getArgument("lease4", lease);
  1171. }
  1172. if (!fake_allocation) {
  1173. // That is a real (REQUEST) allocation
  1174. bool status = LeaseMgrFactory::instance().addLease(lease);
  1175. if (status) {
  1176. return (lease);
  1177. } else {
  1178. // One of many failures with LeaseMgr (e.g. lost connection to the
  1179. // database, database failed etc.). One notable case for that
  1180. // is that we are working in multi-process mode and we lost a race
  1181. // (some other process got that address first)
  1182. return (Lease4Ptr());
  1183. }
  1184. } else {
  1185. // That is only fake (DISCOVER) allocation
  1186. // It is for OFFER only. We should not insert the lease into LeaseMgr,
  1187. // but rather check that we could have inserted it.
  1188. Lease4Ptr existing = LeaseMgrFactory::instance().getLease4(addr);
  1189. if (!existing) {
  1190. return (lease);
  1191. } else {
  1192. return (Lease4Ptr());
  1193. }
  1194. }
  1195. }
  1196. void
  1197. AllocEngine::updateLease4Information(const Lease4Ptr& lease,
  1198. AllocEngine::ClientContext4& ctx) const {
  1199. // This should not happen in theory.
  1200. if (!lease) {
  1201. isc_throw(BadValue, "null lease specified for updateLease4Information");
  1202. }
  1203. if (!ctx.subnet_) {
  1204. isc_throw(BadValue, "null subnet specified for"
  1205. " updateLease4Information");
  1206. }
  1207. lease->subnet_id_ = ctx.subnet_->getID();
  1208. lease->hwaddr_ = ctx.hwaddr_;
  1209. lease->client_id_ = ctx.clientid_;
  1210. lease->cltt_ = time(NULL);
  1211. lease->t1_ = ctx.subnet_->getT1();
  1212. lease->t2_ = ctx.subnet_->getT2();
  1213. lease->valid_lft_ = ctx.subnet_->getValid();
  1214. lease->fqdn_fwd_ = ctx.fwd_dns_update_;
  1215. lease->fqdn_rev_ = ctx.rev_dns_update_;
  1216. lease->hostname_ = ctx.hostname_;
  1217. }
  1218. Lease6Collection
  1219. AllocEngine::updateFqdnData(const Lease6Collection& leases,
  1220. const bool fwd_dns_update,
  1221. const bool rev_dns_update,
  1222. const std::string& hostname,
  1223. const bool fake_allocation) {
  1224. Lease6Collection updated_leases;
  1225. for (Lease6Collection::const_iterator lease_it = leases.begin();
  1226. lease_it != leases.end(); ++lease_it) {
  1227. Lease6Ptr lease(new Lease6(**lease_it));
  1228. lease->fqdn_fwd_ = fwd_dns_update;
  1229. lease->fqdn_rev_ = rev_dns_update;
  1230. lease->hostname_ = hostname;
  1231. if (!fake_allocation &&
  1232. ((lease->fqdn_fwd_ != (*lease_it)->fqdn_fwd_) ||
  1233. (lease->fqdn_rev_ != (*lease_it)->fqdn_rev_) ||
  1234. (lease->hostname_ != (*lease_it)->hostname_))) {
  1235. LeaseMgrFactory::instance().updateLease6(lease);
  1236. }
  1237. updated_leases.push_back(lease);
  1238. }
  1239. return (updated_leases);
  1240. }
  1241. AllocEngine::AllocatorPtr AllocEngine::getAllocator(Lease::Type type) {
  1242. std::map<Lease::Type, AllocatorPtr>::const_iterator alloc = allocators_.find(type);
  1243. if (alloc == allocators_.end()) {
  1244. isc_throw(BadValue, "No allocator initialized for pool type "
  1245. << Lease::typeToText(type));
  1246. }
  1247. return (alloc->second);
  1248. }
  1249. AllocEngine::~AllocEngine() {
  1250. // no need to delete allocator. smart_ptr will do the trick for us
  1251. }
  1252. }; // end of isc::dhcp namespace
  1253. }; // end of isc namespace