alloc_engine.cc 90 KB

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