alloc_engine.cc 79 KB

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