alloc_engine.cc 73 KB

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