alloc_engine.cc 83 KB

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