alloc_engine.cc 94 KB

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