alloc_engine.cc 73 KB

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