alloc_engine.cc 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964
  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_ADDRESS6_ALLOC_FAIL).arg(attempts_);
  416. } catch (const isc::Exception& e) {
  417. // Some other error, return an empty lease.
  418. LOG_ERROR(alloc_engine_logger, ALLOC_ENGINE_ADDRESS6_ALLOC_ERROR).arg(e.what());
  419. }
  420. return (Lease6Collection());
  421. }
  422. Lease6Collection
  423. AllocEngine::allocateUnreservedLeases6(ClientContext6& ctx) {
  424. AllocatorPtr allocator = getAllocator(ctx.type_);
  425. if (!allocator) {
  426. isc_throw(InvalidOperation, "No allocator specified for "
  427. << Lease6::typeToText(ctx.type_));
  428. }
  429. // Check which host reservation mode is supported in this subnet.
  430. Subnet::HRMode hr_mode = ctx.subnet_->getHostReservationMode();
  431. Lease6Collection leases;
  432. IOAddress hint("::");
  433. if (!ctx.hints_.empty()) {
  434. /// @todo: We support only one hint for now
  435. hint = ctx.hints_[0].first;
  436. }
  437. // check if the hint is in pool and is available
  438. // This is equivalent of subnet->inPool(hint), but returns the pool
  439. Pool6Ptr pool = boost::dynamic_pointer_cast<
  440. Pool6>(ctx.subnet_->getPool(ctx.type_, hint, false));
  441. if (pool) {
  442. /// @todo: We support only one hint for now
  443. Lease6Ptr lease = LeaseMgrFactory::instance().getLease6(ctx.type_, hint);
  444. if (!lease) {
  445. // In-pool reservations: Check if this address is reserved for someone
  446. // else. There is no need to check for whom it is reserved, because if
  447. // it has been reserved for us we would have already allocated a lease.
  448. ConstHostPtr host;
  449. if (hr_mode != Subnet::HR_DISABLED) {
  450. host = HostMgr::instance().get6(ctx.subnet_->getID(), hint);
  451. }
  452. if (!host) {
  453. // If the in-pool reservations are disabled, or there is no
  454. // reservation for a given hint, we're good to go.
  455. // The hint is valid and not currently used, let's create a
  456. // lease for it
  457. lease = createLease6(ctx, hint, pool->getLength());
  458. // It can happen that the lease allocation failed (we could
  459. // have lost the race condition. That means that the hint is
  460. // no longer usable and we need to continue the regular
  461. // allocation path.
  462. if (lease) {
  463. /// @todo: We support only one lease per ia for now
  464. Lease6Collection collection;
  465. collection.push_back(lease);
  466. return (collection);
  467. }
  468. }
  469. } else {
  470. // If the lease is expired, we may likely reuse it, but...
  471. if (lease->expired()) {
  472. ConstHostPtr host;
  473. if (hr_mode != Subnet::HR_DISABLED) {
  474. host = HostMgr::instance().get6(ctx.subnet_->getID(), hint);
  475. }
  476. // Let's check if there is a reservation for this address.
  477. if (!host) {
  478. // Copy an existing, expired lease so as it can be returned
  479. // to the caller.
  480. Lease6Ptr old_lease(new Lease6(*lease));
  481. ctx.old_leases_.push_back(old_lease);
  482. /// We found a lease and it is expired, so we can reuse it
  483. lease = reuseExpiredLease(lease, ctx, pool->getLength());
  484. /// @todo: We support only one lease per ia for now
  485. leases.push_back(lease);
  486. return (leases);
  487. }
  488. }
  489. }
  490. }
  491. // The hint was useless (it was not provided at all, was used by someone else,
  492. // was out of pool or reserved for someone else). Search the pool until first
  493. // of the following occurs:
  494. // - we find a free address
  495. // - we find an address for which the lease has expired
  496. // - we exhaust number of tries
  497. //
  498. /// @todo: We used to use hardcoded number of attempts (100). Now we dynamically
  499. /// calculate the number of possible leases in all pools in this subnet and
  500. /// try that number of times at most. It would be useful to that value if
  501. /// attempts_, specified by the user could override that value (and keep
  502. /// dynamic if they're set to 0).
  503. uint32_t max_attempts = ctx.subnet_->getPoolCapacity(ctx.type_);
  504. for (uint32_t i = 0; i < max_attempts; ++i)
  505. {
  506. IOAddress candidate = allocator->pickAddress(ctx.subnet_, ctx.duid_, hint);
  507. /// In-pool reservations: Check if this address is reserved for someone
  508. /// else. There is no need to check for whom it is reserved, because if
  509. /// it has been reserved for us we would have already allocated a lease.
  510. if (hr_mode == Subnet::HR_ALL &&
  511. HostMgr::instance().get6(ctx.subnet_->getID(), candidate)) {
  512. // Don't allocate.
  513. continue;
  514. }
  515. // The first step is to find out prefix length. It is 128 for
  516. // non-PD leases.
  517. uint8_t prefix_len = 128;
  518. if (ctx.type_ == Lease::TYPE_PD) {
  519. Pool6Ptr pool = boost::dynamic_pointer_cast<Pool6>(
  520. ctx.subnet_->getPool(ctx.type_, candidate, false));
  521. /// @todo: verify that the pool is non-null
  522. prefix_len = pool->getLength();
  523. }
  524. Lease6Ptr existing = LeaseMgrFactory::instance().getLease6(ctx.type_,
  525. candidate);
  526. if (!existing) {
  527. // there's no existing lease for selected candidate, so it is
  528. // free. Let's allocate it.
  529. Lease6Ptr lease = createLease6(ctx, candidate, prefix_len);
  530. if (lease) {
  531. // We are allocating a new lease (not renewing). So, the
  532. // old lease should be NULL.
  533. ctx.old_leases_.clear();
  534. leases.push_back(lease);
  535. return (leases);
  536. }
  537. // Although the address was free just microseconds ago, it may have
  538. // been taken just now. If the lease insertion fails, we continue
  539. // allocation attempts.
  540. } else {
  541. if (existing->expired()) {
  542. // Copy an existing, expired lease so as it can be returned
  543. // to the caller.
  544. Lease6Ptr old_lease(new Lease6(*existing));
  545. ctx.old_leases_.push_back(old_lease);
  546. existing = reuseExpiredLease(existing,
  547. ctx,
  548. prefix_len);
  549. leases.push_back(existing);
  550. return (leases);
  551. }
  552. }
  553. }
  554. // We failed to allocate anything. Let's return empty collection.
  555. return (Lease6Collection());
  556. }
  557. void
  558. AllocEngine::allocateReservedLeases6(ClientContext6& ctx, Lease6Collection& existing_leases) {
  559. // If there are no reservations or the reservation is v4, there's nothing to do.
  560. if (!ctx.host_ || !ctx.host_->hasIPv6Reservation()) {
  561. return;
  562. }
  563. // Let's convert this from Lease::Type to IPv6Reserv::Type
  564. IPv6Resrv::Type type = ctx.type_ == Lease::TYPE_NA ? IPv6Resrv::TYPE_NA : IPv6Resrv::TYPE_PD;
  565. // Get the IPv6 reservations of specified type.
  566. const IPv6ResrvRange& reservs = ctx.host_->getIPv6Reservations(type);
  567. if (std::distance(reservs.first, reservs.second) == 0) {
  568. // No reservations? We're done here.
  569. return;
  570. }
  571. for (IPv6ResrvIterator resv = reservs.first; resv != reservs.second; ++resv) {
  572. // We do have a reservation for addr.
  573. IOAddress addr = resv->second.getPrefix();
  574. uint8_t prefix_len = resv->second.getPrefixLen();
  575. // Check if already have this lease on the existing_leases list.
  576. for (Lease6Collection::const_iterator l = existing_leases.begin();
  577. l != existing_leases.end(); ++l) {
  578. // Ok, we already have a lease for this reservation and it's usable
  579. if (((*l)->addr_ == addr) && (*l)->valid_lft_ != 0) {
  580. return;
  581. }
  582. }
  583. // If there's a lease for this address, let's not create it.
  584. // It doesn't matter whether it is for this client or for someone else.
  585. if (!LeaseMgrFactory::instance().getLease6(ctx.type_, addr)) {
  586. // Ok, let's create a new lease...
  587. Lease6Ptr lease = createLease6(ctx, addr, prefix_len);
  588. // ... and add it to the existing leases list.
  589. existing_leases.push_back(lease);
  590. if (ctx.type_ == Lease::TYPE_NA) {
  591. LOG_INFO(alloc_engine_logger, ALLOC_ENGINE_HR_RESERVED_ADDR_GRANTED)
  592. .arg(addr.toText()).arg(ctx.duid_->toText());
  593. } else {
  594. LOG_INFO(alloc_engine_logger, ALLOC_ENGINE_HR_RESERVED_PREFIX_GRANTED)
  595. .arg(addr.toText()).arg(static_cast<int>(prefix_len))
  596. .arg(ctx.duid_->toText());
  597. }
  598. // We found a lease for this client and this IA. Let's return.
  599. // Returning after the first lease was assigned is useful if we
  600. // have multiple reservations for the same client. If the client
  601. // sends 2 IAs, the first time we call allocateReservedLeases6 will
  602. // use the first reservation and return. The second time, we'll
  603. // go over the first reservation, but will discover that there's
  604. // a lease corresponding to it and will skip it and then pick
  605. // the second reservation and turn it into the lease. This approach
  606. // would work for any number of reservations.
  607. return;
  608. }
  609. }
  610. }
  611. void
  612. AllocEngine::removeNonmatchingReservedLeases6(ClientContext6& ctx,
  613. Lease6Collection& existing_leases) {
  614. // If there are no leases (so nothing to remove) or
  615. // host reservation is disabled (so there are no reserved leases),
  616. // just return.
  617. if (existing_leases.empty() || !ctx.subnet_ ||
  618. (ctx.subnet_->getHostReservationMode() == Subnet::HR_DISABLED) ) {
  619. return;
  620. }
  621. // We need a copy, so we won't be iterating over a container and
  622. // removing from it at the same time. It's only a copy of pointers,
  623. // so the operation shouldn't be that expensive.
  624. Lease6Collection copy = existing_leases;
  625. for (Lease6Collection::const_iterator candidate = copy.begin();
  626. candidate != copy.end(); ++candidate) {
  627. ConstHostPtr host = HostMgr::instance().get6(ctx.subnet_->getID(),
  628. (*candidate)->addr_);
  629. if (!host || (host == ctx.host_)) {
  630. // Not reserved or reserved for us. That's ok, let's check
  631. // the next lease.
  632. continue;
  633. }
  634. // Ok, we have a problem. This host has a lease that is reserved
  635. // for someone else. We need to recover from this.
  636. if (ctx.type_ == Lease::TYPE_NA) {
  637. LOG_INFO(alloc_engine_logger, ALLOC_ENGINE_HR_REVOKED_ADDR6_LEASE)
  638. .arg((*candidate)->addr_.toText()).arg(ctx.duid_->toText())
  639. .arg(host->getIdentifierAsText());
  640. } else {
  641. LOG_INFO(alloc_engine_logger, ALLOC_ENGINE_HR_REVOKED_PREFIX6_LEASE)
  642. .arg((*candidate)->addr_.toText())
  643. .arg(static_cast<int>((*candidate)->prefixlen_))
  644. .arg(ctx.duid_->toText())
  645. .arg(host->getIdentifierAsText());
  646. }
  647. // Remove this lease from LeaseMgr
  648. LeaseMgrFactory::instance().deleteLease((*candidate)->addr_);
  649. // In principle, we could trigger a hook here, but we will do this
  650. // only if we get serious complaints from actual users. We want the
  651. // conflict resolution procedure to really work and user libraries
  652. // should not interfere with it.
  653. // Add this to the list of removed leases.
  654. ctx.old_leases_.push_back(*candidate);
  655. // Let's remove this candidate from existing leases
  656. removeLeases(existing_leases, (*candidate)->addr_);
  657. }
  658. }
  659. bool
  660. AllocEngine::removeLeases(Lease6Collection& container, const asiolink::IOAddress& addr) {
  661. bool removed = false;
  662. for (Lease6Collection::iterator lease = container.begin();
  663. lease != container.end(); ++lease) {
  664. if ((*lease)->addr_ == addr) {
  665. lease->reset();
  666. removed = true;
  667. }
  668. }
  669. // Remove all elements that have NULL value
  670. container.erase(std::remove(container.begin(), container.end(), Lease6Ptr()),
  671. container.end());
  672. return (removed);
  673. }
  674. void
  675. AllocEngine::removeNonreservedLeases6(ClientContext6& ctx,
  676. Lease6Collection& existing_leases) {
  677. // This method removes leases that are not reserved for this host.
  678. // It will keep at least one lease, though.
  679. if (existing_leases.empty() || !ctx.host_ || !ctx.host_->hasIPv6Reservation()) {
  680. return;
  681. }
  682. // This is the total number of leases. We should not remove the last one.
  683. int total = existing_leases.size();
  684. // This is officially not scary code anymore. iterates and marks specified
  685. // leases for deletion, by setting appropriate pointers to NULL.
  686. for (Lease6Collection::iterator lease = existing_leases.begin();
  687. lease != existing_leases.end(); ++lease) {
  688. IPv6Resrv resv(ctx.type_ == Lease::TYPE_NA ? IPv6Resrv::TYPE_NA : IPv6Resrv::TYPE_PD,
  689. (*lease)->addr_, (*lease)->prefixlen_);
  690. if (!ctx.host_->hasReservation(resv)) {
  691. // We have reservations, but not for this lease. Release it.
  692. // Remove this lease from LeaseMgr
  693. LeaseMgrFactory::instance().deleteLease((*lease)->addr_);
  694. /// @todo: Probably trigger a hook here
  695. // Add this to the list of removed leases.
  696. ctx.old_leases_.push_back(*lease);
  697. // Set this pointer to NULL. The pointer is still valid. We're just
  698. // setting the Lease6Ptr to NULL value. We'll remove all NULL
  699. // pointers once the loop is finished.
  700. lease->reset();
  701. if (--total == 1) {
  702. // If there's only one lease left, break the loop.
  703. break;
  704. }
  705. }
  706. }
  707. // Remove all elements that we previously marked for deletion (those that
  708. // have NULL value).
  709. existing_leases.erase(std::remove(existing_leases.begin(),
  710. existing_leases.end(), Lease6Ptr()), existing_leases.end());
  711. }
  712. Lease6Ptr
  713. AllocEngine::reuseExpiredLease(Lease6Ptr& expired, ClientContext6& ctx,
  714. uint8_t prefix_len) {
  715. if (!expired->expired()) {
  716. isc_throw(BadValue, "Attempt to recycle lease that is still valid");
  717. }
  718. if (expired->type_ != Lease::TYPE_PD) {
  719. prefix_len = 128; // non-PD lease types must be always /128
  720. }
  721. // address, lease type and prefixlen (0) stay the same
  722. expired->iaid_ = ctx.iaid_;
  723. expired->duid_ = ctx.duid_;
  724. expired->preferred_lft_ = ctx.subnet_->getPreferred();
  725. expired->valid_lft_ = ctx.subnet_->getValid();
  726. expired->t1_ = ctx.subnet_->getT1();
  727. expired->t2_ = ctx.subnet_->getT2();
  728. expired->cltt_ = time(NULL);
  729. expired->subnet_id_ = ctx.subnet_->getID();
  730. expired->fixed_ = false;
  731. expired->hostname_ = ctx.hostname_;
  732. expired->fqdn_fwd_ = ctx.fwd_dns_update_;
  733. expired->fqdn_rev_ = ctx.rev_dns_update_;
  734. expired->prefixlen_ = prefix_len;
  735. /// @todo: log here that the lease was reused (there's ticket #2524 for
  736. /// logging in libdhcpsrv)
  737. // Let's execute all callouts registered for lease6_select
  738. if (ctx.callout_handle_ &&
  739. HooksManager::getHooksManager().calloutsPresent(hook_index_lease6_select_)) {
  740. // Delete all previous arguments
  741. ctx.callout_handle_->deleteAllArguments();
  742. // Pass necessary arguments
  743. // Subnet from which we do the allocation
  744. ctx.callout_handle_->setArgument("subnet6", ctx.subnet_);
  745. // Is this solicit (fake = true) or request (fake = false)
  746. ctx.callout_handle_->setArgument("fake_allocation", ctx.fake_allocation_);
  747. // The lease that will be assigned to a client
  748. ctx.callout_handle_->setArgument("lease6", expired);
  749. // Call the callouts
  750. HooksManager::callCallouts(hook_index_lease6_select_, *ctx.callout_handle_);
  751. // Callouts decided to skip the action. This means that the lease is not
  752. // assigned, so the client will get NoAddrAvail as a result. The lease
  753. // won't be inserted into the database.
  754. if (ctx.callout_handle_->getSkip()) {
  755. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE6_SELECT_SKIP);
  756. return (Lease6Ptr());
  757. }
  758. // Let's use whatever callout returned. Hopefully it is the same lease
  759. // we handed to it.
  760. ctx.callout_handle_->getArgument("lease6", expired);
  761. }
  762. if (!ctx.fake_allocation_) {
  763. // for REQUEST we do update the lease
  764. LeaseMgrFactory::instance().updateLease6(expired);
  765. }
  766. // We do nothing for SOLICIT. We'll just update database when
  767. // the client gets back to us with REQUEST message.
  768. // it's not really expired at this stage anymore - let's return it as
  769. // an updated lease
  770. return (expired);
  771. }
  772. Lease6Ptr AllocEngine::createLease6(ClientContext6& ctx,
  773. const IOAddress& addr,
  774. uint8_t prefix_len) {
  775. if (ctx.type_ != Lease::TYPE_PD) {
  776. prefix_len = 128; // non-PD lease types must be always /128
  777. }
  778. Lease6Ptr lease(new Lease6(ctx.type_, addr, ctx.duid_, ctx.iaid_,
  779. ctx.subnet_->getPreferred(), ctx.subnet_->getValid(),
  780. ctx.subnet_->getT1(), ctx.subnet_->getT2(),
  781. ctx.subnet_->getID(), ctx.hwaddr_, prefix_len));
  782. lease->fqdn_fwd_ = ctx.fwd_dns_update_;
  783. lease->fqdn_rev_ = ctx.rev_dns_update_;
  784. lease->hostname_ = ctx.hostname_;
  785. // Let's execute all callouts registered for lease6_select
  786. if (ctx.callout_handle_ &&
  787. HooksManager::getHooksManager().calloutsPresent(hook_index_lease6_select_)) {
  788. // Delete all previous arguments
  789. ctx.callout_handle_->deleteAllArguments();
  790. // Pass necessary arguments
  791. // Subnet from which we do the allocation
  792. ctx.callout_handle_->setArgument("subnet6", ctx.subnet_);
  793. // Is this solicit (fake = true) or request (fake = false)
  794. ctx.callout_handle_->setArgument("fake_allocation", ctx.fake_allocation_);
  795. ctx.callout_handle_->setArgument("lease6", lease);
  796. // This is the first callout, so no need to clear any arguments
  797. HooksManager::callCallouts(hook_index_lease6_select_, *ctx.callout_handle_);
  798. // Callouts decided to skip the action. This means that the lease is not
  799. // assigned, so the client will get NoAddrAvail as a result. The lease
  800. // won't be inserted into the database.
  801. if (ctx.callout_handle_->getSkip()) {
  802. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE6_SELECT_SKIP);
  803. return (Lease6Ptr());
  804. }
  805. // Let's use whatever callout returned. Hopefully it is the same lease
  806. // we handed to it.
  807. ctx.callout_handle_->getArgument("lease6", lease);
  808. }
  809. if (!ctx.fake_allocation_) {
  810. // That is a real (REQUEST) allocation
  811. bool status = LeaseMgrFactory::instance().addLease(lease);
  812. if (status) {
  813. return (lease);
  814. } else {
  815. // One of many failures with LeaseMgr (e.g. lost connection to the
  816. // database, database failed etc.). One notable case for that
  817. // is that we are working in multi-process mode and we lost a race
  818. // (some other process got that address first)
  819. return (Lease6Ptr());
  820. }
  821. } else {
  822. // That is only fake (SOLICIT without rapid-commit) allocation
  823. // It is for advertise only. We should not insert the lease into LeaseMgr,
  824. // but rather check that we could have inserted it.
  825. Lease6Ptr existing = LeaseMgrFactory::instance().getLease6(
  826. Lease::TYPE_NA, addr);
  827. if (!existing) {
  828. return (lease);
  829. } else {
  830. return (Lease6Ptr());
  831. }
  832. }
  833. }
  834. Lease6Collection
  835. AllocEngine::renewLeases6(ClientContext6& ctx) {
  836. try {
  837. if (!ctx.subnet_) {
  838. isc_throw(InvalidOperation, "Subnet is required for allocation");
  839. }
  840. if (!ctx.duid_) {
  841. isc_throw(InvalidOperation, "DUID is mandatory for allocation");
  842. }
  843. // Check if there are any leases for this client.
  844. Lease6Collection leases = LeaseMgrFactory::instance()
  845. .getLeases6(ctx.type_, *ctx.duid_, ctx.iaid_, ctx.subnet_->getID());
  846. if (!leases.empty()) {
  847. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  848. ALLOC_ENGINE_V6_RENEW_REMOVE_RESERVED)
  849. .arg(ctx.query_->getLabel());
  850. // Check if the existing leases are reserved for someone else.
  851. // If they're not, we're ok to keep using them.
  852. removeNonmatchingReservedLeases6(ctx, leases);
  853. }
  854. if (ctx.host_) {
  855. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  856. ALLOC_ENGINE_V6_RENEW_HR)
  857. .arg(ctx.query_->getLabel());
  858. // If we have host reservation, allocate those leases.
  859. allocateReservedLeases6(ctx, leases);
  860. // There's one more check to do. Let's remove leases that are not
  861. // matching reservations, i.e. if client X has address A, but there's
  862. // a reservation for address B, we should release A and reassign B.
  863. // Caveat: do this only if we have at least one reserved address.
  864. removeNonreservedLeases6(ctx, leases);
  865. }
  866. // If we happen to removed all leases, get something new for this guy.
  867. // Depending on the configuration, we may enable or disable granting
  868. // new leases during renewals. This is controlled with the
  869. // allow_new_leases_in_renewals_ field.
  870. if (leases.empty() && ctx.allow_new_leases_in_renewals_) {
  871. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  872. ALLOC_ENGINE_V6_EXTEND_ALLOC_UNRESERVED)
  873. .arg(ctx.query_->getLabel());
  874. leases = allocateUnreservedLeases6(ctx);
  875. }
  876. // Extend all existing leases that passed all checks.
  877. for (Lease6Collection::iterator l = leases.begin(); l != leases.end(); ++l) {
  878. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE_DETAIL,
  879. ALLOC_ENGINE_V6_EXTEND_LEASE)
  880. .arg(ctx.query_->getLabel())
  881. .arg((*l)->typeToText((*l)->type_))
  882. .arg((*l)->addr_);
  883. extendLease6(ctx, *l);
  884. }
  885. return (leases);
  886. } catch (const isc::Exception& e) {
  887. // Some other error, return an empty lease.
  888. LOG_ERROR(alloc_engine_logger, ALLOC_ENGINE_V6_EXTEND_ERROR)
  889. .arg(ctx.query_->getLabel())
  890. .arg(e.what());
  891. }
  892. return (Lease6Collection());
  893. }
  894. void
  895. AllocEngine::extendLease6(ClientContext6& ctx, Lease6Ptr lease) {
  896. if (!lease || !ctx.subnet_) {
  897. return;
  898. }
  899. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE_DETAIL_DATA,
  900. ALLOC_ENGINE_V6_EXTEND_LEASE_DATA)
  901. .arg(ctx.query_->getLabel())
  902. .arg(lease->toText());
  903. // Check if the lease still belongs to the subnet. If it doesn't,
  904. // we'll need to remove it.
  905. if ((lease->type_ != Lease::TYPE_PD) && !ctx.subnet_->inRange(lease->addr_)) {
  906. // Oh dear, the lease is no longer valid. We need to get rid of it.
  907. // Remove this lease from LeaseMgr
  908. LeaseMgrFactory::instance().deleteLease(lease->addr_);
  909. // Add it to the removed leases list.
  910. ctx.old_leases_.push_back(lease);
  911. return;
  912. }
  913. // Keep the old data in case the callout tells us to skip update.
  914. Lease6 old_data = *lease;
  915. lease->preferred_lft_ = ctx.subnet_->getPreferred();
  916. lease->valid_lft_ = ctx.subnet_->getValid();
  917. lease->t1_ = ctx.subnet_->getT1();
  918. lease->t2_ = ctx.subnet_->getT2();
  919. lease->cltt_ = time(NULL);
  920. lease->hostname_ = ctx.hostname_;
  921. lease->fqdn_fwd_ = ctx.fwd_dns_update_;
  922. lease->fqdn_rev_ = ctx.rev_dns_update_;
  923. lease->hwaddr_ = ctx.hwaddr_;
  924. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE_DETAIL_DATA,
  925. ALLOC_ENGINE_V6_EXTEND_NEW_LEASE_DATA)
  926. .arg(ctx.query_->getLabel())
  927. .arg(lease->toText());
  928. bool skip = false;
  929. // Get the callouts specific for the processed message and execute them.
  930. int hook_point = ctx.query_->getType() == DHCPV6_RENEW ?
  931. Hooks.hook_index_lease6_renew_ : Hooks.hook_index_lease6_rebind_;
  932. if (HooksManager::calloutsPresent(hook_point)) {
  933. CalloutHandlePtr callout_handle = ctx.callout_handle_;
  934. // Delete all previous arguments
  935. callout_handle->deleteAllArguments();
  936. // Pass the original packet
  937. callout_handle->setArgument("query6", ctx.query_);
  938. // Pass the lease to be updated
  939. callout_handle->setArgument("lease6", lease);
  940. // Pass the IA option to be sent in response
  941. if (lease->type_ == Lease::TYPE_NA) {
  942. callout_handle->setArgument("ia_na", ctx.ia_rsp_);
  943. } else {
  944. callout_handle->setArgument("ia_pd", ctx.ia_rsp_);
  945. }
  946. // Call all installed callouts
  947. HooksManager::callCallouts(hook_point, *callout_handle);
  948. // Callouts decided to skip the next processing step. The next
  949. // processing step would actually renew the lease, so skip at this
  950. // stage means "keep the old lease as it is".
  951. if (callout_handle->getSkip()) {
  952. skip = true;
  953. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS,
  954. DHCPSRV_HOOK_LEASE6_EXTEND_SKIP)
  955. .arg(ctx.query_->getName());
  956. }
  957. }
  958. if (!skip) {
  959. LeaseMgrFactory::instance().updateLease6(lease);
  960. } else {
  961. // Copy back the original date to the lease. For MySQL it doesn't make
  962. // much sense, but for memfile, the Lease6Ptr points to the actual lease
  963. // in memfile, so the actual update is performed when we manipulate
  964. // fields of returned Lease6Ptr, the actual updateLease6() is no-op.
  965. *lease = old_data;
  966. }
  967. }
  968. Lease6Collection
  969. AllocEngine::updateFqdnData(ClientContext6& ctx, const Lease6Collection& leases) {
  970. Lease6Collection updated_leases;
  971. for (Lease6Collection::const_iterator lease_it = leases.begin();
  972. lease_it != leases.end(); ++lease_it) {
  973. Lease6Ptr lease(new Lease6(**lease_it));
  974. lease->fqdn_fwd_ = ctx.fwd_dns_update_;
  975. lease->fqdn_rev_ = ctx.rev_dns_update_;
  976. lease->hostname_ = ctx.hostname_;
  977. if (!ctx.fake_allocation_ &&
  978. ((lease->fqdn_fwd_ != (*lease_it)->fqdn_fwd_) ||
  979. (lease->fqdn_rev_ != (*lease_it)->fqdn_rev_) ||
  980. (lease->hostname_ != (*lease_it)->hostname_))) {
  981. ctx.changed_leases_.push_back(*lease_it);
  982. LeaseMgrFactory::instance().updateLease6(lease);
  983. }
  984. updated_leases.push_back(lease);
  985. }
  986. return (updated_leases);
  987. }
  988. } // end of isc::dhcp namespace
  989. } // end of isc namespace
  990. // ##########################################################################
  991. // # DHCPv4 lease allocation code starts here.
  992. // ##########################################################################
  993. namespace {
  994. /// @brief Check if the specific address is reserved for another client.
  995. ///
  996. /// This function uses the HW address from the context to check if the
  997. /// requested address (specified as first parameter) is reserved for
  998. /// another client, i.e. client using a different HW address.
  999. ///
  1000. /// @param address An address for which the function should check if
  1001. /// there is a reservation for the different client.
  1002. /// @param ctx Client context holding the data extracted from the
  1003. /// client's message.
  1004. ///
  1005. /// @return true if the address is reserved for another client.
  1006. bool
  1007. addressReserved(const IOAddress& address, const AllocEngine::ClientContext4& ctx) {
  1008. ConstHostPtr host = HostMgr::instance().get4(ctx.subnet_->getID(), address);
  1009. HWAddrPtr host_hwaddr;
  1010. if (host) {
  1011. host_hwaddr = host->getHWAddress();
  1012. if (ctx.hwaddr_ && host_hwaddr) {
  1013. /// @todo Use the equality operators for HWAddr class.
  1014. /// Currently, this is impossible because the HostMgr uses the
  1015. /// HTYPE_ETHER type, whereas the unit tests may use other types
  1016. /// which HostMgr doesn't support yet.
  1017. return (host_hwaddr->hwaddr_ != ctx.hwaddr_->hwaddr_);
  1018. } else {
  1019. return (false);
  1020. }
  1021. }
  1022. return (false);
  1023. }
  1024. /// @brief Check if the context contains the reservation for the
  1025. /// IPv4 address.
  1026. ///
  1027. /// This convenience function checks if the context contains the reservation
  1028. /// for the IPv4 address. Note that some reservations may not assign a
  1029. /// static IPv4 address to the clients, but may rather reserve a hostname.
  1030. /// Allocation engine should check if the existing reservation is made
  1031. /// for the IPv4 address and if it is not, allocate the address from the
  1032. /// dynamic pool. The allocation engine uses this function to check if
  1033. /// the reservation is made for the IPv4 address.
  1034. ///
  1035. /// @param ctx Client context holding the data extracted from the
  1036. /// client's message.
  1037. ///
  1038. /// @return true if the context contains the reservation for the IPv4 address.
  1039. bool
  1040. hasAddressReservation(const AllocEngine::ClientContext4& ctx) {
  1041. return (ctx.host_ && !ctx.host_->getIPv4Reservation().isV4Zero());
  1042. }
  1043. /// @brief Finds existing lease in the database.
  1044. ///
  1045. /// This function searches for the lease in the database which belongs to the
  1046. /// client requesting allocation. If the client has supplied the client
  1047. /// identifier this identifier is used to look up the lease. If the lease is
  1048. /// not found using the client identifier, an additional lookup is performed
  1049. /// using the HW address, if supplied. If the lease is found using the HW
  1050. /// address, the function also checks if the lease belongs to the client, i.e.
  1051. /// there is no conflict between the client identifiers.
  1052. ///
  1053. /// @param ctx Context holding data extracted from the client's message,
  1054. /// including the HW address and client identifier.
  1055. /// @param [out] client_lease A pointer to the lease returned by this function
  1056. /// or null value if no has been lease found.
  1057. void findClientLease(const AllocEngine::ClientContext4& ctx, Lease4Ptr& client_lease) {
  1058. LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
  1059. // If client identifier has been supplied, use it to lookup the lease. This
  1060. // search will return no lease if the client doesn't have any lease in the
  1061. // database or if the client didn't use client identifier to allocate the
  1062. // existing lease (this include cases when the server was explicitly
  1063. // configured to ignore client identifier).
  1064. if (ctx.clientid_) {
  1065. client_lease = lease_mgr.getLease4(*ctx.clientid_, ctx.subnet_->getID());
  1066. }
  1067. // If no lease found using the client identifier, try the lookup using
  1068. // the HW address.
  1069. if (!client_lease && ctx.hwaddr_) {
  1070. client_lease = lease_mgr.getLease4(*ctx.hwaddr_, ctx.subnet_->getID());
  1071. // This lookup may return the lease which has conflicting client
  1072. // identifier and thus is considered to belong to someone else.
  1073. // If this is the case, we need to toss the result and force the
  1074. // Allocation Engine to allocate another lease.
  1075. if (client_lease && !client_lease->belongsToClient(ctx.hwaddr_, ctx.clientid_)) {
  1076. client_lease.reset();
  1077. }
  1078. }
  1079. }
  1080. } // end of anonymous namespace
  1081. namespace isc {
  1082. namespace dhcp {
  1083. AllocEngine::ClientContext4::ClientContext4()
  1084. : subnet_(), clientid_(), hwaddr_(),
  1085. requested_address_(IOAddress::IPV4_ZERO_ADDRESS()),
  1086. fwd_dns_update_(false), rev_dns_update_(false),
  1087. hostname_(""), callout_handle_(), fake_allocation_(false),
  1088. old_lease_(), host_(), conflicting_lease_(), query_() {
  1089. }
  1090. AllocEngine::ClientContext4::ClientContext4(const Subnet4Ptr& subnet,
  1091. const ClientIdPtr& clientid,
  1092. const HWAddrPtr& hwaddr,
  1093. const asiolink::IOAddress& requested_addr,
  1094. const bool fwd_dns_update,
  1095. const bool rev_dns_update,
  1096. const std::string& hostname,
  1097. const bool fake_allocation)
  1098. : subnet_(subnet), clientid_(clientid), hwaddr_(hwaddr),
  1099. requested_address_(requested_addr),
  1100. fwd_dns_update_(fwd_dns_update), rev_dns_update_(rev_dns_update),
  1101. hostname_(hostname), callout_handle_(),
  1102. fake_allocation_(fake_allocation), old_lease_(), host_() {
  1103. }
  1104. Lease4Ptr
  1105. AllocEngine::allocateLease4(ClientContext4& ctx) {
  1106. // The NULL pointer indicates that the old lease didn't exist. It may
  1107. // be later set to non NULL value if existing lease is found in the
  1108. // database.
  1109. ctx.old_lease_.reset();
  1110. Lease4Ptr new_lease;
  1111. try {
  1112. if (!ctx.subnet_) {
  1113. isc_throw(BadValue, "Can't allocate IPv4 address without subnet");
  1114. }
  1115. if (!ctx.hwaddr_) {
  1116. isc_throw(BadValue, "HWAddr must be defined");
  1117. }
  1118. new_lease = ctx.fake_allocation_ ? discoverLease4(ctx) : requestLease4(ctx);
  1119. if (!new_lease) {
  1120. // Unable to allocate an address, return an empty lease.
  1121. LOG_WARN(alloc_engine_logger, ALLOC_ENGINE_ADDRESS4_ALLOC_FAIL).arg(attempts_);
  1122. }
  1123. } catch (const isc::Exception& e) {
  1124. // Some other error, return an empty lease.
  1125. LOG_ERROR(alloc_engine_logger, ALLOC_ENGINE_ADDRESS4_ALLOC_ERROR).arg(e.what());
  1126. }
  1127. return (new_lease);
  1128. }
  1129. void
  1130. AllocEngine::findReservation(ClientContext4& ctx) {
  1131. ctx.host_.reset();
  1132. // We can only search for the reservation if a subnet has been selected.
  1133. if (ctx.subnet_) {
  1134. // Check which host reservation mode is supported in this subnet.
  1135. Subnet::HRMode hr_mode = ctx.subnet_->getHostReservationMode();
  1136. // Check if there is a host reseravtion for this client. Attempt to
  1137. // get host information
  1138. if (hr_mode != Subnet::HR_DISABLED) {
  1139. // This method should handle the case when there is neither hwaddr
  1140. // nor clientid_ available and simply return NULL.
  1141. ctx.host_ = HostMgr::instance().get4(ctx.subnet_->getID(), ctx.hwaddr_,
  1142. ctx.clientid_);
  1143. }
  1144. }
  1145. }
  1146. Lease4Ptr
  1147. AllocEngine::discoverLease4(AllocEngine::ClientContext4& ctx) {
  1148. // Find an existing lease for this client. This function will return true
  1149. // if there is a conflict with existing lease and the allocation should
  1150. // not be continued.
  1151. Lease4Ptr client_lease;
  1152. findClientLease(ctx, client_lease);
  1153. // new_lease will hold the pointer to the lease that we will offer to the
  1154. // caller.
  1155. Lease4Ptr new_lease;
  1156. // Check if there is a reservation for the client. If there is, we want to
  1157. // assign the reserved address, rather than any other one.
  1158. if (hasAddressReservation(ctx)) {
  1159. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1160. ALLOC_ENGINE_V4_DISCOVER_HR)
  1161. .arg(ctx.query_->getLabel())
  1162. .arg(ctx.host_->getIPv4Reservation().toText());
  1163. // If the client doesn't have a lease or the leased address is different
  1164. // than the reserved one then let's try to allocate the reserved address.
  1165. // Otherwise the address that the client has is the one for which it
  1166. // has a reservation, so just renew it.
  1167. if (!client_lease || (client_lease->addr_ != ctx.host_->getIPv4Reservation())) {
  1168. // The call below will return a pointer to the lease for the address
  1169. // reserved to this client, if the lease is available, i.e. is not
  1170. // currently assigned to any other client.
  1171. // Note that we don't remove the existing client's lease at this point
  1172. // because this is not a real allocation, we just offer what we can
  1173. // allocate in the DHCPREQUEST time.
  1174. new_lease = allocateOrReuseLease4(ctx.host_->getIPv4Reservation(), ctx);
  1175. if (!new_lease) {
  1176. LOG_WARN(alloc_engine_logger, ALLOC_ENGINE_DISCOVER_ADDRESS_CONFLICT)
  1177. .arg(ctx.host_->getIPv4Reservation().toText())
  1178. .arg(ctx.conflicting_lease_ ? ctx.conflicting_lease_->toText() :
  1179. "(no lease info)");
  1180. }
  1181. } else {
  1182. new_lease = renewLease4(client_lease, ctx);
  1183. }
  1184. }
  1185. // Client does not have a reservation or the allocation of the reserved
  1186. // address has failed, probably because the reserved address is in use
  1187. // by another client. If the client has a lease, we will check if we can
  1188. // offer this lease to the client. The lease can't be offered in the
  1189. // situation when it is reserved for another client or when the address
  1190. // is not in the dynamic pool. The former may be the result of adding the
  1191. // new reservation for the address used by this client. The latter may
  1192. // be due to the client using the reserved out-of-the pool address, for
  1193. // which the reservation has just been removed.
  1194. if (!new_lease && client_lease &&
  1195. ctx.subnet_->inPool(Lease::TYPE_V4, client_lease->addr_) &&
  1196. !addressReserved(client_lease->addr_, ctx)) {
  1197. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1198. ALLOC_ENGINE_V4_OFFER_EXISTING_LEASE)
  1199. .arg(ctx.query_->getLabel());
  1200. new_lease = renewLease4(client_lease, ctx);
  1201. }
  1202. // The client doesn't have any lease or the lease can't be offered
  1203. // because it is either reserved for some other client or the
  1204. // address is not in the dynamic pool.
  1205. // Let's use the client's hint (requested IP address), if the client
  1206. // has provided it, and try to offer it. This address must not be
  1207. // reserved for another client, and must be in the range of the
  1208. // dynamic pool.
  1209. if (!new_lease && !ctx.requested_address_.isV4Zero() &&
  1210. ctx.subnet_->inPool(Lease::TYPE_V4, ctx.requested_address_) &&
  1211. !addressReserved(ctx.requested_address_, ctx)) {
  1212. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1213. ALLOC_ENGINE_V4_OFFER_NEW_LEASE)
  1214. .arg(ctx.query_->getLabel());
  1215. new_lease = allocateOrReuseLease4(ctx.requested_address_, ctx);
  1216. }
  1217. // The allocation engine failed to allocate all of the candidate
  1218. // addresses. We will now use the allocator to pick the address
  1219. // from the dynamic pool.
  1220. if (!new_lease) {
  1221. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1222. ALLOC_ENGINE_V4_OFFER_NEW_LEASE)
  1223. .arg(ctx.query_->getLabel());
  1224. new_lease = allocateUnreservedLease4(ctx);
  1225. }
  1226. // Some of the methods like reuseExpiredLease4 may set the old lease to point
  1227. // to the lease which they remove/override. If it is not set, but we have
  1228. // found that the client has the lease the client's lease is the one
  1229. // to return as an old lease.
  1230. if (!ctx.old_lease_ && client_lease) {
  1231. ctx.old_lease_ = client_lease;
  1232. }
  1233. return (new_lease);
  1234. }
  1235. Lease4Ptr
  1236. AllocEngine::requestLease4(AllocEngine::ClientContext4& ctx) {
  1237. // Find an existing lease for this client. This function will return true
  1238. // if there is a conflict with existing lease and the allocation should
  1239. // not be continued.
  1240. Lease4Ptr client_lease;
  1241. findClientLease(ctx, client_lease);
  1242. // Obtain the sole instance of the LeaseMgr.
  1243. LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
  1244. // When the client sends the DHCPREQUEST, it should always specify the
  1245. // address which it is requesting or renewing. That is, the client should
  1246. // either use the requested IP address option or set the ciaddr. However,
  1247. // we try to be liberal and allow the clients to not specify an address
  1248. // in which case the allocation engine will pick a suitable address
  1249. // for the client.
  1250. if (!ctx.requested_address_.isV4Zero()) {
  1251. // If the client has specified an address, make sure this address
  1252. // is not reserved for another client. If it is, stop here because
  1253. // we can't allocate this address.
  1254. if (addressReserved(ctx.requested_address_, ctx)) {
  1255. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1256. ALLOC_ENGINE_V4_REQUEST_ADDRESS_RESERVED)
  1257. .arg(ctx.query_->getLabel())
  1258. .arg(ctx.requested_address_.toText());
  1259. return (Lease4Ptr());
  1260. }
  1261. } else if (hasAddressReservation(ctx)) {
  1262. // The client hasn't specified an address to allocate, so the
  1263. // allocation engine needs to find an appropriate address.
  1264. // If there is a reservation for the client, let's try to
  1265. // allocate the reserved address.
  1266. ctx.requested_address_ = ctx.host_->getIPv4Reservation();
  1267. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1268. ALLOC_ENGINE_V4_REQUEST_USE_HR)
  1269. .arg(ctx.query_->getLabel())
  1270. .arg(ctx.requested_address_.toText());
  1271. }
  1272. if (!ctx.requested_address_.isV4Zero()) {
  1273. // There is a specific address to be allocated. Let's find out if
  1274. // the address is in use.
  1275. Lease4Ptr existing = LeaseMgrFactory::instance().getLease4(ctx.requested_address_);
  1276. // If the address is in use (allocated and not expired), we check
  1277. // if the address is in use by our client or another client.
  1278. // If it is in use by another client, the address can't be
  1279. // allocated.
  1280. if (existing && !existing->expired() &&
  1281. !existing->belongsToClient(ctx.hwaddr_, ctx.clientid_)) {
  1282. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1283. ALLOC_ENGINE_V4_REQUEST_IN_USE)
  1284. .arg(ctx.query_->getLabel())
  1285. .arg(ctx.requested_address_.toText());
  1286. return (Lease4Ptr());
  1287. }
  1288. // If the client has a reservation but it is requesting a different
  1289. // address it is possible that the client was offered this different
  1290. // address because the reserved address is in use. We will have to
  1291. // check if the address is in use.
  1292. if (hasAddressReservation(ctx) &&
  1293. (ctx.host_->getIPv4Reservation() != ctx.requested_address_)) {
  1294. existing = LeaseMgrFactory::instance().getLease4(ctx.host_->getIPv4Reservation());
  1295. // If the reserved address is not in use, i.e. the lease doesn't
  1296. // exist or is expired, and the client is requesting a different
  1297. // address, return NULL. The client should go back to the
  1298. // DHCPDISCOVER and the reserved address will be offered.
  1299. if (!existing || existing->expired()) {
  1300. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1301. ALLOC_ENGINE_V4_REQUEST_INVALID)
  1302. .arg(ctx.query_->getLabel())
  1303. .arg(ctx.host_->getIPv4Reservation().toText())
  1304. .arg(ctx.requested_address_.toText());
  1305. return (Lease4Ptr());
  1306. }
  1307. }
  1308. // The use of the out-of-pool addresses is only allowed when the requested
  1309. // address is reserved for the client. If the address is not reserved one
  1310. // and it doesn't belong to the dynamic pool, do not allocate it.
  1311. if ((!hasAddressReservation(ctx) ||
  1312. (ctx.host_->getIPv4Reservation() != ctx.requested_address_)) &&
  1313. !ctx.subnet_->inPool(Lease4::TYPE_V4, ctx.requested_address_)) {
  1314. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1315. ALLOC_ENGINE_V4_REQUEST_OUT_OF_POOL)
  1316. .arg(ctx.query_->getLabel())
  1317. .arg(ctx.requested_address_);
  1318. return (Lease4Ptr());
  1319. }
  1320. }
  1321. // We have gone through all the checks, so we can now allocate the address
  1322. // for the client.
  1323. // If the client is requesting an address which is assigned to the client
  1324. // let's just renew this address. Also, renew this address if the client
  1325. // doesn't request any specific address.
  1326. if (client_lease) {
  1327. if ((client_lease->addr_ == ctx.requested_address_) ||
  1328. ctx.requested_address_.isV4Zero()) {
  1329. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1330. ALLOC_ENGINE_V4_REQUEST_EXTEND_LEASE)
  1331. .arg(ctx.query_->getLabel())
  1332. .arg(ctx.requested_address_);
  1333. return (renewLease4(client_lease, ctx));
  1334. }
  1335. }
  1336. // new_lease will hold the pointer to the allocated lease if we allocate
  1337. // successfully.
  1338. Lease4Ptr new_lease;
  1339. // The client doesn't have the lease or it is requesting an address
  1340. // which it doesn't have. Let's try to allocate the requested address.
  1341. if (!ctx.requested_address_.isV4Zero()) {
  1342. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1343. ALLOC_ENGINE_V4_REQUEST_ALLOC_REQUESTED)
  1344. .arg(ctx.query_->getLabel())
  1345. .arg(ctx.requested_address_.toText());
  1346. // The call below will return a pointer to the lease allocated
  1347. // for the client if there is no lease for the requested address,
  1348. // or the existing lease has expired. If the allocation fails,
  1349. // e.g. because the lease is in use, we will return NULL to
  1350. // indicate that we were unable to allocate the lease.
  1351. new_lease = allocateOrReuseLease4(ctx.requested_address_, ctx);
  1352. } else {
  1353. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1354. ALLOC_ENGINE_V4_REQUEST_PICK_ADDRESS)
  1355. .arg(ctx.query_->getLabel());
  1356. // We will only get here if the client didn't specify which
  1357. // address it wanted to be allocated. The allocation engine will
  1358. // to pick the address from the dynamic pool.
  1359. new_lease = allocateUnreservedLease4(ctx);
  1360. }
  1361. // If we allocated the lease for the client, but the client already had a
  1362. // lease, we will need to return the pointer to the previous lease and
  1363. // the previous lease needs to be removed from the lease database.
  1364. if (new_lease && client_lease) {
  1365. ctx.old_lease_ = Lease4Ptr(new Lease4(*client_lease));
  1366. LOG_DEBUG(alloc_engine_logger, ALLOC_ENGINE_DBG_TRACE,
  1367. ALLOC_ENGINE_V4_REQUEST_REMOVE_LEASE)
  1368. .arg(ctx.query_->getLabel())
  1369. .arg(client_lease->addr_.toText());
  1370. lease_mgr.deleteLease(client_lease->addr_);
  1371. }
  1372. // Return the allocated lease or NULL pointer if allocation was
  1373. // unsuccessful.
  1374. return (new_lease);
  1375. }
  1376. Lease4Ptr
  1377. AllocEngine::createLease4(const ClientContext4& ctx, const IOAddress& addr) {
  1378. if (!ctx.hwaddr_) {
  1379. isc_throw(BadValue, "Can't create a lease with NULL HW address");
  1380. }
  1381. if (!ctx.subnet_) {
  1382. isc_throw(BadValue, "Can't create a lease without a subnet");
  1383. }
  1384. time_t now = time(NULL);
  1385. // @todo: remove this kludge after ticket #2590 is implemented
  1386. std::vector<uint8_t> local_copy;
  1387. if (ctx.clientid_) {
  1388. local_copy = ctx.clientid_->getDuid();
  1389. }
  1390. Lease4Ptr lease(new Lease4(addr, ctx.hwaddr_, &local_copy[0], local_copy.size(),
  1391. ctx.subnet_->getValid(), ctx.subnet_->getT1(),
  1392. ctx.subnet_->getT2(),
  1393. now, ctx.subnet_->getID()));
  1394. // Set FQDN specific lease parameters.
  1395. lease->fqdn_fwd_ = ctx.fwd_dns_update_;
  1396. lease->fqdn_rev_ = ctx.rev_dns_update_;
  1397. lease->hostname_ = ctx.hostname_;
  1398. // Let's execute all callouts registered for lease4_select
  1399. if (ctx.callout_handle_ &&
  1400. HooksManager::getHooksManager().calloutsPresent(hook_index_lease4_select_)) {
  1401. // Delete all previous arguments
  1402. ctx.callout_handle_->deleteAllArguments();
  1403. // Pass necessary arguments
  1404. // Subnet from which we do the allocation (That's as far as we can go
  1405. // with using SubnetPtr to point to Subnet4 object. Users should not
  1406. // be confused with dynamic_pointer_casts. They should get a concrete
  1407. // pointer (Subnet4Ptr) pointing to a Subnet4 object.
  1408. Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(ctx.subnet_);
  1409. ctx.callout_handle_->setArgument("subnet4", subnet4);
  1410. // Is this solicit (fake = true) or request (fake = false)
  1411. ctx.callout_handle_->setArgument("fake_allocation", ctx.fake_allocation_);
  1412. // Pass the intended lease as well
  1413. ctx.callout_handle_->setArgument("lease4", lease);
  1414. // This is the first callout, so no need to clear any arguments
  1415. HooksManager::callCallouts(hook_index_lease4_select_, *ctx.callout_handle_);
  1416. // Callouts decided to skip the action. This means that the lease is not
  1417. // assigned, so the client will get NoAddrAvail as a result. The lease
  1418. // won't be inserted into the database.
  1419. if (ctx.callout_handle_->getSkip()) {
  1420. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE4_SELECT_SKIP);
  1421. return (Lease4Ptr());
  1422. }
  1423. // Let's use whatever callout returned. Hopefully it is the same lease
  1424. // we handled to it.
  1425. ctx.callout_handle_->getArgument("lease4", lease);
  1426. }
  1427. if (!ctx.fake_allocation_) {
  1428. // That is a real (REQUEST) allocation
  1429. bool status = LeaseMgrFactory::instance().addLease(lease);
  1430. if (status) {
  1431. return (lease);
  1432. } else {
  1433. // One of many failures with LeaseMgr (e.g. lost connection to the
  1434. // database, database failed etc.). One notable case for that
  1435. // is that we are working in multi-process mode and we lost a race
  1436. // (some other process got that address first)
  1437. return (Lease4Ptr());
  1438. }
  1439. } else {
  1440. // That is only fake (DISCOVER) allocation
  1441. // It is for OFFER only. We should not insert the lease into LeaseMgr,
  1442. // but rather check that we could have inserted it.
  1443. Lease4Ptr existing = LeaseMgrFactory::instance().getLease4(addr);
  1444. if (!existing) {
  1445. return (lease);
  1446. } else {
  1447. return (Lease4Ptr());
  1448. }
  1449. }
  1450. }
  1451. Lease4Ptr
  1452. AllocEngine::renewLease4(const Lease4Ptr& lease,
  1453. AllocEngine::ClientContext4& ctx) {
  1454. if (!lease) {
  1455. isc_throw(BadValue, "null lease specified for renewLease4");
  1456. }
  1457. // Let's keep the old data. This is essential if we are using memfile
  1458. // (the lease returned points directly to the lease4 object in the database)
  1459. // We'll need it if we want to skip update (i.e. roll back renewal)
  1460. /// @todo: remove this once #3083 is implemented
  1461. Lease4 old_values = *lease;
  1462. ctx.old_lease_.reset(new Lease4(old_values));
  1463. // Update the lease with the information from the context.
  1464. updateLease4Information(lease, ctx);
  1465. bool skip = false;
  1466. // Execute all callouts registered for lease4_renew.
  1467. if (HooksManager::getHooksManager().
  1468. calloutsPresent(Hooks.hook_index_lease4_renew_)) {
  1469. // Delete all previous arguments
  1470. ctx.callout_handle_->deleteAllArguments();
  1471. // Subnet from which we do the allocation. Convert the general subnet
  1472. // pointer to a pointer to a Subnet4. Note that because we are using
  1473. // boost smart pointers here, we need to do the cast using the boost
  1474. // version of dynamic_pointer_cast.
  1475. Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(ctx.subnet_);
  1476. // Pass the parameters
  1477. ctx.callout_handle_->setArgument("subnet4", subnet4);
  1478. ctx.callout_handle_->setArgument("clientid", ctx.clientid_);
  1479. ctx.callout_handle_->setArgument("hwaddr", ctx.hwaddr_);
  1480. // Pass the lease to be updated
  1481. ctx.callout_handle_->setArgument("lease4", lease);
  1482. // Call all installed callouts
  1483. HooksManager::callCallouts(Hooks.hook_index_lease4_renew_,
  1484. *ctx.callout_handle_);
  1485. // Callouts decided to skip the next processing step. The next
  1486. // processing step would actually renew the lease, so skip at this
  1487. // stage means "keep the old lease as it is".
  1488. if (ctx.callout_handle_->getSkip()) {
  1489. skip = true;
  1490. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS,
  1491. DHCPSRV_HOOK_LEASE4_RENEW_SKIP);
  1492. }
  1493. }
  1494. if (!ctx.fake_allocation_ && !skip) {
  1495. // for REQUEST we do update the lease
  1496. LeaseMgrFactory::instance().updateLease4(lease);
  1497. }
  1498. if (skip) {
  1499. // Rollback changes (really useful only for memfile)
  1500. /// @todo: remove this once #3083 is implemented
  1501. *lease = old_values;
  1502. }
  1503. return (lease);
  1504. }
  1505. Lease4Ptr
  1506. AllocEngine::reuseExpiredLease4(Lease4Ptr& expired,
  1507. AllocEngine::ClientContext4& ctx) {
  1508. if (!expired) {
  1509. isc_throw(BadValue, "null lease specified for reuseExpiredLease");
  1510. }
  1511. if (!ctx.subnet_) {
  1512. isc_throw(BadValue, "null subnet specified for the reuseExpiredLease");
  1513. }
  1514. updateLease4Information(expired, ctx);
  1515. expired->fixed_ = false;
  1516. /// @todo: log here that the lease was reused (there's ticket #2524 for
  1517. /// logging in libdhcpsrv)
  1518. // Let's execute all callouts registered for lease4_select
  1519. if (ctx.callout_handle_ && HooksManager::getHooksManager()
  1520. .calloutsPresent(hook_index_lease4_select_)) {
  1521. // Delete all previous arguments
  1522. ctx.callout_handle_->deleteAllArguments();
  1523. // Pass necessary arguments
  1524. // Subnet from which we do the allocation. Convert the general subnet
  1525. // pointer to a pointer to a Subnet4. Note that because we are using
  1526. // boost smart pointers here, we need to do the cast using the boost
  1527. // version of dynamic_pointer_cast.
  1528. Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(ctx.subnet_);
  1529. ctx.callout_handle_->setArgument("subnet4", subnet4);
  1530. // Is this solicit (fake = true) or request (fake = false)
  1531. ctx.callout_handle_->setArgument("fake_allocation",
  1532. ctx.fake_allocation_);
  1533. // The lease that will be assigned to a client
  1534. ctx.callout_handle_->setArgument("lease4", expired);
  1535. // Call the callouts
  1536. HooksManager::callCallouts(hook_index_lease4_select_, *ctx.callout_handle_);
  1537. // Callouts decided to skip the action. This means that the lease is not
  1538. // assigned, so the client will get NoAddrAvail as a result. The lease
  1539. // won't be inserted into the database.
  1540. if (ctx.callout_handle_->getSkip()) {
  1541. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS,
  1542. DHCPSRV_HOOK_LEASE4_SELECT_SKIP);
  1543. return (Lease4Ptr());
  1544. }
  1545. // Let's use whatever callout returned. Hopefully it is the same lease
  1546. // we handed to it.
  1547. ctx.callout_handle_->getArgument("lease4", expired);
  1548. }
  1549. if (!ctx.fake_allocation_) {
  1550. // for REQUEST we do update the lease
  1551. LeaseMgrFactory::instance().updateLease4(expired);
  1552. }
  1553. // We do nothing for SOLICIT. We'll just update database when
  1554. // the client gets back to us with REQUEST message.
  1555. // it's not really expired at this stage anymore - let's return it as
  1556. // an updated lease
  1557. return (expired);
  1558. }
  1559. Lease4Ptr
  1560. AllocEngine::allocateOrReuseLease4(const IOAddress& candidate, ClientContext4& ctx) {
  1561. ctx.conflicting_lease_.reset();
  1562. Lease4Ptr exist_lease = LeaseMgrFactory::instance().getLease4(candidate);
  1563. if (exist_lease) {
  1564. if (exist_lease->expired()) {
  1565. ctx.old_lease_ = Lease4Ptr(new Lease4(*exist_lease));
  1566. return (reuseExpiredLease4(exist_lease, ctx));
  1567. } else {
  1568. // If there is a lease and it is not expired, pass this lease back
  1569. // to the caller in the context. The caller may need to know
  1570. // which lease we're conflicting with.
  1571. ctx.conflicting_lease_ = exist_lease;
  1572. }
  1573. } else {
  1574. return (createLease4(ctx, candidate));
  1575. }
  1576. return (Lease4Ptr());
  1577. }
  1578. Lease4Ptr
  1579. AllocEngine::allocateUnreservedLease4(ClientContext4& ctx) {
  1580. Lease4Ptr new_lease;
  1581. AllocatorPtr allocator = getAllocator(Lease::TYPE_V4);
  1582. const uint64_t max_attempts = ctx.subnet_->getPoolCapacity(Lease::TYPE_V4);
  1583. for (uint64_t i = 0; i < max_attempts; ++i) {
  1584. IOAddress candidate = allocator->pickAddress(ctx.subnet_, ctx.clientid_,
  1585. ctx.requested_address_);
  1586. // If address is not reserved for another client, try to allocate it.
  1587. if (!addressReserved(candidate, ctx)) {
  1588. // The call below will return the non-NULL pointer if we
  1589. // successfully allocate this lease. This means that the
  1590. // address is not in use by another client.
  1591. new_lease = allocateOrReuseLease4(candidate, ctx);
  1592. if (new_lease) {
  1593. return (new_lease);
  1594. }
  1595. }
  1596. }
  1597. return (new_lease);
  1598. }
  1599. void
  1600. AllocEngine::updateLease4Information(const Lease4Ptr& lease,
  1601. AllocEngine::ClientContext4& ctx) const {
  1602. lease->subnet_id_ = ctx.subnet_->getID();
  1603. lease->hwaddr_ = ctx.hwaddr_;
  1604. lease->client_id_ = ctx.clientid_;
  1605. lease->cltt_ = time(NULL);
  1606. lease->t1_ = ctx.subnet_->getT1();
  1607. lease->t2_ = ctx.subnet_->getT2();
  1608. lease->valid_lft_ = ctx.subnet_->getValid();
  1609. lease->fqdn_fwd_ = ctx.fwd_dns_update_;
  1610. lease->fqdn_rev_ = ctx.rev_dns_update_;
  1611. lease->hostname_ = ctx.hostname_;
  1612. }
  1613. }; // end of isc::dhcp namespace
  1614. }; // end of isc namespace