alloc_engine.cc 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328
  1. // Copyright (C) 2012-2014 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 <dhcpsrv/alloc_engine.h>
  15. #include <dhcpsrv/dhcpsrv_log.h>
  16. #include <dhcpsrv/host_mgr.h>
  17. #include <dhcpsrv/lease_mgr_factory.h>
  18. #include <hooks/server_hooks.h>
  19. #include <hooks/hooks_manager.h>
  20. #include <cstring>
  21. #include <vector>
  22. #include <string.h>
  23. using namespace isc::asiolink;
  24. using namespace isc::hooks;
  25. namespace {
  26. /// Structure that holds registered hook indexes
  27. struct AllocEngineHooks {
  28. int hook_index_lease4_select_; ///< index for "lease4_receive" hook point
  29. int hook_index_lease4_renew_; ///< index for "lease4_renew" hook point
  30. int hook_index_lease6_select_; ///< index for "lease6_receive" hook point
  31. /// Constructor that registers hook points for AllocationEngine
  32. AllocEngineHooks() {
  33. hook_index_lease4_select_ = HooksManager::registerHook("lease4_select");
  34. hook_index_lease4_renew_ = HooksManager::registerHook("lease4_renew");
  35. hook_index_lease6_select_ = HooksManager::registerHook("lease6_select");
  36. }
  37. };
  38. // Declare a Hooks object. As this is outside any function or method, it
  39. // will be instantiated (and the constructor run) when the module is loaded.
  40. // As a result, the hook indexes will be defined before any method in this
  41. // module is called.
  42. AllocEngineHooks Hooks;
  43. }; // anonymous namespace
  44. namespace isc {
  45. namespace dhcp {
  46. AllocEngine::IterativeAllocator::IterativeAllocator(Lease::Type lease_type)
  47. :Allocator(lease_type) {
  48. }
  49. isc::asiolink::IOAddress
  50. AllocEngine::IterativeAllocator::increaseAddress(const isc::asiolink::IOAddress& addr) {
  51. // Get a buffer holding an address.
  52. const std::vector<uint8_t>& vec = addr.toBytes();
  53. // Get the address length.
  54. const int len = vec.size();
  55. // Since the same array will be used to hold the IPv4 and IPv6
  56. // address we have to make sure that the size of the array
  57. // we allocate will work for both types of address.
  58. BOOST_STATIC_ASSERT(V4ADDRESS_LEN <= V6ADDRESS_LEN);
  59. uint8_t packed[V6ADDRESS_LEN];
  60. // Copy the address. It can be either V4 or V6.
  61. std::memcpy(packed, &vec[0], len);
  62. // Start increasing the least significant byte
  63. for (int i = len - 1; i >= 0; --i) {
  64. ++packed[i];
  65. // if we haven't overflowed (0xff -> 0x0), than we are done
  66. if (packed[i] != 0) {
  67. break;
  68. }
  69. }
  70. return (IOAddress::fromBytes(addr.getFamily(), packed));
  71. }
  72. isc::asiolink::IOAddress
  73. AllocEngine::IterativeAllocator::increasePrefix(const isc::asiolink::IOAddress& prefix,
  74. const uint8_t prefix_len) {
  75. if (!prefix.isV6()) {
  76. isc_throw(BadValue, "Prefix operations are for IPv6 only (attempted to "
  77. "increase prefix " << prefix << ")");
  78. }
  79. // Get a buffer holding an address.
  80. const std::vector<uint8_t>& vec = prefix.toBytes();
  81. if (prefix_len < 1 || prefix_len > 128) {
  82. isc_throw(BadValue, "Cannot increase prefix: invalid prefix length: "
  83. << prefix_len);
  84. }
  85. // Brief explanation what happens here:
  86. // http://www.youtube.com/watch?v=NFQCYpIHLNQ
  87. uint8_t n_bytes = (prefix_len - 1)/8;
  88. uint8_t n_bits = 8 - (prefix_len - n_bytes*8);
  89. uint8_t mask = 1 << n_bits;
  90. // Longer explanation: n_bytes specifies number of full bytes that are
  91. // in-prefix. They can also be used as an offset for the first byte that
  92. // is not in prefix. n_bits specifies number of bits on the last byte that
  93. // is (often partially) in prefix. For example for a /125 prefix, the values
  94. // are 15 and 3, respectively. Mask is a bitmask that has the least
  95. // significant bit from the prefix set.
  96. uint8_t packed[V6ADDRESS_LEN];
  97. // Copy the address. It must be V6, but we already checked that.
  98. std::memcpy(packed, &vec[0], V6ADDRESS_LEN);
  99. // Can we safely increase only the last byte in prefix without overflow?
  100. if (packed[n_bytes] + uint16_t(mask) < 256u) {
  101. packed[n_bytes] += mask;
  102. return (IOAddress::fromBytes(AF_INET6, packed));
  103. }
  104. // Overflow (done on uint8_t, but the sum is greater than 255)
  105. packed[n_bytes] += mask;
  106. // Deal with the overflow. Start increasing the least significant byte
  107. for (int i = n_bytes - 1; i >= 0; --i) {
  108. ++packed[i];
  109. // If we haven't overflowed (0xff->0x0) the next byte, then we are done
  110. if (packed[i] != 0) {
  111. break;
  112. }
  113. }
  114. return (IOAddress::fromBytes(AF_INET6, packed));
  115. }
  116. isc::asiolink::IOAddress
  117. AllocEngine::IterativeAllocator::pickAddress(const SubnetPtr& subnet,
  118. const DuidPtr&,
  119. const IOAddress&) {
  120. // Is this prefix allocation?
  121. bool prefix = pool_type_ == Lease::TYPE_PD;
  122. // Let's get the last allocated address. It is usually set correctly,
  123. // but there are times when it won't be (like after removing a pool or
  124. // perhaps restarting the server).
  125. IOAddress last = subnet->getLastAllocated(pool_type_);
  126. const PoolCollection& pools = subnet->getPools(pool_type_);
  127. if (pools.empty()) {
  128. isc_throw(AllocFailed, "No pools defined in selected subnet");
  129. }
  130. // first we need to find a pool the last address belongs to.
  131. PoolCollection::const_iterator it;
  132. for (it = pools.begin(); it != pools.end(); ++it) {
  133. if ((*it)->inRange(last)) {
  134. break;
  135. }
  136. }
  137. // last one was bogus for one of several reasons:
  138. // - we just booted up and that's the first address we're allocating
  139. // - a subnet was removed or other reconfiguration just completed
  140. // - perhaps allocation algorithm was changed
  141. if (it == pools.end()) {
  142. // ok to access first element directly. We checked that pools is non-empty
  143. IOAddress next = pools[0]->getFirstAddress();
  144. subnet->setLastAllocated(pool_type_, next);
  145. return (next);
  146. }
  147. // Ok, we have a pool that the last address belonged to, let's use it.
  148. IOAddress next("::");
  149. if (!prefix) {
  150. next = increaseAddress(last); // basically addr++
  151. } else {
  152. Pool6Ptr pool6 = boost::dynamic_pointer_cast<Pool6>(*it);
  153. if (!pool6) {
  154. // Something is gravely wrong here
  155. isc_throw(Unexpected, "Wrong type of pool: " << (*it)->toText()
  156. << " is not Pool6");
  157. }
  158. // Get the next prefix
  159. next = increasePrefix(last, pool6->getLength());
  160. }
  161. if ((*it)->inRange(next)) {
  162. // the next one is in the pool as well, so we haven't hit pool boundary yet
  163. subnet->setLastAllocated(pool_type_, next);
  164. return (next);
  165. }
  166. // We hit pool boundary, let's try to jump to the next pool and try again
  167. ++it;
  168. if (it == pools.end()) {
  169. // Really out of luck today. That was the last pool. Let's rewind
  170. // to the beginning.
  171. next = pools[0]->getFirstAddress();
  172. subnet->setLastAllocated(pool_type_, next);
  173. return (next);
  174. }
  175. // there is a next pool, let's try first address from it
  176. next = (*it)->getFirstAddress();
  177. subnet->setLastAllocated(pool_type_, next);
  178. return (next);
  179. }
  180. AllocEngine::HashedAllocator::HashedAllocator(Lease::Type lease_type)
  181. :Allocator(lease_type) {
  182. isc_throw(NotImplemented, "Hashed allocator is not implemented");
  183. }
  184. isc::asiolink::IOAddress
  185. AllocEngine::HashedAllocator::pickAddress(const SubnetPtr&,
  186. const DuidPtr&,
  187. const IOAddress&) {
  188. isc_throw(NotImplemented, "Hashed allocator is not implemented");
  189. }
  190. AllocEngine::RandomAllocator::RandomAllocator(Lease::Type lease_type)
  191. :Allocator(lease_type) {
  192. isc_throw(NotImplemented, "Random allocator is not implemented");
  193. }
  194. isc::asiolink::IOAddress
  195. AllocEngine::RandomAllocator::pickAddress(const SubnetPtr&,
  196. const DuidPtr&,
  197. const IOAddress&) {
  198. isc_throw(NotImplemented, "Random allocator is not implemented");
  199. }
  200. AllocEngine::AllocEngine(AllocType engine_type, unsigned int attempts,
  201. bool ipv6)
  202. :attempts_(attempts) {
  203. // Choose the basic (normal address) lease type
  204. Lease::Type basic_type = ipv6 ? Lease::TYPE_NA : Lease::TYPE_V4;
  205. // Initalize normal address allocators
  206. switch (engine_type) {
  207. case ALLOC_ITERATIVE:
  208. allocators_[basic_type] = AllocatorPtr(new IterativeAllocator(basic_type));
  209. break;
  210. case ALLOC_HASHED:
  211. allocators_[basic_type] = AllocatorPtr(new HashedAllocator(basic_type));
  212. break;
  213. case ALLOC_RANDOM:
  214. allocators_[basic_type] = AllocatorPtr(new RandomAllocator(basic_type));
  215. break;
  216. default:
  217. isc_throw(BadValue, "Invalid/unsupported allocation algorithm");
  218. }
  219. // If this is IPv6 allocation engine, initalize also temporary addrs
  220. // and prefixes
  221. if (ipv6) {
  222. switch (engine_type) {
  223. case ALLOC_ITERATIVE:
  224. allocators_[Lease::TYPE_TA] = AllocatorPtr(new IterativeAllocator(Lease::TYPE_TA));
  225. allocators_[Lease::TYPE_PD] = AllocatorPtr(new IterativeAllocator(Lease::TYPE_PD));
  226. break;
  227. case ALLOC_HASHED:
  228. allocators_[Lease::TYPE_TA] = AllocatorPtr(new HashedAllocator(Lease::TYPE_TA));
  229. allocators_[Lease::TYPE_PD] = AllocatorPtr(new HashedAllocator(Lease::TYPE_PD));
  230. break;
  231. case ALLOC_RANDOM:
  232. allocators_[Lease::TYPE_TA] = AllocatorPtr(new RandomAllocator(Lease::TYPE_TA));
  233. allocators_[Lease::TYPE_PD] = AllocatorPtr(new RandomAllocator(Lease::TYPE_PD));
  234. break;
  235. default:
  236. isc_throw(BadValue, "Invalid/unsupported allocation algorithm");
  237. }
  238. }
  239. // Register hook points
  240. hook_index_lease4_select_ = Hooks.hook_index_lease4_select_;
  241. hook_index_lease6_select_ = Hooks.hook_index_lease6_select_;
  242. }
  243. Lease6Collection
  244. AllocEngine::allocateLeases6(const Subnet6Ptr& subnet, const DuidPtr& duid,
  245. const uint32_t iaid, const IOAddress& hint,
  246. Lease::Type type, const bool fwd_dns_update,
  247. const bool rev_dns_update,
  248. const std::string& hostname, bool fake_allocation,
  249. const isc::hooks::CalloutHandlePtr& callout_handle,
  250. Lease6Collection& old_leases, const HWAddrPtr& hwaddr) {
  251. try {
  252. AllocatorPtr allocator = getAllocator(type);
  253. if (!allocator) {
  254. isc_throw(InvalidOperation, "No allocator specified for "
  255. << Lease6::typeToText(type));
  256. }
  257. if (!subnet) {
  258. isc_throw(InvalidOperation, "Subnet is required for allocation");
  259. }
  260. if (!duid) {
  261. isc_throw(InvalidOperation, "DUID is mandatory for allocation");
  262. }
  263. // Check if there's existing lease for that subnet/duid/iaid
  264. // combination.
  265. /// @todo: Make this generic (cover temp. addrs and prefixes)
  266. Lease6Collection existing = LeaseMgrFactory::instance().getLeases6(type,
  267. *duid, iaid, subnet->getID());
  268. // There is at least one lease for this client. We will return these
  269. // leases for the client, but we may need to update FQDN information.
  270. if (!existing.empty()) {
  271. // Return old leases so the server can see what has changed.
  272. old_leases = existing;
  273. return (updateFqdnData(existing, fwd_dns_update, rev_dns_update,
  274. hostname, fake_allocation));
  275. }
  276. // check if the hint is in pool and is available
  277. // This is equivalent of subnet->inPool(hint), but returns the pool
  278. Pool6Ptr pool = boost::dynamic_pointer_cast<
  279. Pool6>(subnet->getPool(type, hint, false));
  280. if (pool) {
  281. /// @todo: We support only one hint for now
  282. Lease6Ptr lease = LeaseMgrFactory::instance().getLease6(type, hint);
  283. if (!lease) {
  284. /// @todo: check if the hint is reserved once we have host
  285. /// support implemented
  286. // The hint is valid and not currently used, let's create a
  287. // lease for it
  288. lease = createLease6(subnet, duid, iaid, hint,
  289. pool->getLength(), type,
  290. fwd_dns_update, rev_dns_update,
  291. hostname, hwaddr, callout_handle, fake_allocation);
  292. // It can happen that the lease allocation failed (we could
  293. // have lost the race condition. That means that the hint is
  294. // lo longer usable and we need to continue the regular
  295. // allocation path.
  296. if (lease) {
  297. // We are allocating a new lease (not renewing). So, the
  298. // old lease should be NULL.
  299. old_leases.push_back(Lease6Ptr());
  300. /// @todo: We support only one lease per ia for now
  301. Lease6Collection collection;
  302. collection.push_back(lease);
  303. return (collection);
  304. }
  305. } else {
  306. if (lease->expired()) {
  307. // Copy an existing, expired lease so as it can be returned
  308. // to the caller.
  309. Lease6Ptr old_lease(new Lease6(*lease));
  310. old_leases.push_back(old_lease);
  311. /// We found a lease and it is expired, so we can reuse it
  312. lease = reuseExpiredLease(lease, subnet, duid, iaid,
  313. pool->getLength(),
  314. fwd_dns_update, rev_dns_update,
  315. hostname, callout_handle,
  316. fake_allocation);
  317. /// @todo: We support only one lease per ia for now
  318. Lease6Collection collection;
  319. collection.push_back(lease);
  320. return (collection);
  321. }
  322. }
  323. }
  324. // Hint is in the pool but is not available. Search the pool until first of
  325. // the following occurs:
  326. // - we find a free address
  327. // - we find an address for which the lease has expired
  328. // - we exhaust number of tries
  329. //
  330. // @todo: Current code does not handle pool exhaustion well. It will be
  331. // improved. Current problems:
  332. // 1. with attempts set to too large value (e.g. 1000) and a small pool (e.g.
  333. // 10 addresses), we will iterate over it 100 times before giving up
  334. // 2. attempts 0 mean unlimited (this is really UINT_MAX, not infinite)
  335. // 3. the whole concept of infinite attempts is just asking for infinite loop
  336. // We may consider some form or reference counting (this pool has X addresses
  337. // left), but this has one major problem. We exactly control allocation
  338. // moment, but we currently do not control expiration time at all
  339. unsigned int i = attempts_;
  340. do {
  341. IOAddress candidate = allocator->pickAddress(subnet, duid, hint);
  342. /// @todo: check if the address is reserved once we have host support
  343. /// implemented
  344. // The first step is to find out prefix length. It is 128 for
  345. // non-PD leases.
  346. uint8_t prefix_len = 128;
  347. if (type == Lease::TYPE_PD) {
  348. Pool6Ptr pool = boost::dynamic_pointer_cast<Pool6>(
  349. subnet->getPool(type, candidate, false));
  350. prefix_len = pool->getLength();
  351. }
  352. Lease6Ptr existing = LeaseMgrFactory::instance().getLease6(type,
  353. candidate);
  354. if (!existing) {
  355. // there's no existing lease for selected candidate, so it is
  356. // free. Let's allocate it.
  357. Lease6Ptr lease = createLease6(subnet, duid, iaid, candidate,
  358. prefix_len, type, fwd_dns_update,
  359. rev_dns_update, hostname, hwaddr,
  360. callout_handle, fake_allocation);
  361. if (lease) {
  362. // We are allocating a new lease (not renewing). So, the
  363. // old lease should be NULL.
  364. old_leases.push_back(Lease6Ptr());
  365. Lease6Collection collection;
  366. collection.push_back(lease);
  367. return (collection);
  368. }
  369. // Although the address was free just microseconds ago, it may have
  370. // been taken just now. If the lease insertion fails, we continue
  371. // allocation attempts.
  372. } else {
  373. if (existing->expired()) {
  374. // Copy an existing, expired lease so as it can be returned
  375. // to the caller.
  376. Lease6Ptr old_lease(new Lease6(*existing));
  377. old_leases.push_back(old_lease);
  378. existing = reuseExpiredLease(existing, subnet, duid, iaid,
  379. prefix_len, fwd_dns_update,
  380. rev_dns_update, hostname,
  381. callout_handle, fake_allocation);
  382. Lease6Collection collection;
  383. collection.push_back(existing);
  384. return (collection);
  385. }
  386. }
  387. // Continue trying allocation until we run out of attempts
  388. // (or attempts are set to 0, which means infinite)
  389. --i;
  390. } while ((i > 0) || !attempts_);
  391. // Unable to allocate an address, return an empty lease.
  392. LOG_WARN(dhcpsrv_logger, DHCPSRV_ADDRESS6_ALLOC_FAIL).arg(attempts_);
  393. } catch (const isc::Exception& e) {
  394. // Some other error, return an empty lease.
  395. LOG_ERROR(dhcpsrv_logger, DHCPSRV_ADDRESS6_ALLOC_ERROR).arg(e.what());
  396. }
  397. return (Lease6Collection());
  398. }
  399. Lease4Ptr
  400. AllocEngine::allocateLease4(const SubnetPtr& subnet, const ClientIdPtr& clientid,
  401. const HWAddrPtr& hwaddr, const IOAddress& hint,
  402. const bool fwd_dns_update, const bool rev_dns_update,
  403. const std::string& hostname, bool fake_allocation,
  404. const isc::hooks::CalloutHandlePtr& callout_handle,
  405. Lease4Ptr& old_lease) {
  406. // The NULL pointer indicates that the old lease didn't exist. It may
  407. // be later set to non NULL value if existing lease is found in the
  408. // database.
  409. old_lease.reset();
  410. try {
  411. // Set allocator.
  412. AllocatorPtr allocator = getAllocator(Lease::TYPE_V4);
  413. if (!subnet) {
  414. isc_throw(BadValue, "Can't allocate IPv4 address without subnet");
  415. }
  416. if (!hwaddr) {
  417. isc_throw(BadValue, "HWAddr must be defined");
  418. }
  419. /// @todo The context for lease allocation should really be created
  420. /// by the DHCPv4 server and passed to this function. The reason for
  421. /// this is that the server should retrieve the Host object for the
  422. /// client because the Host object contains the data not only useful
  423. /// for the address allocation but also hostname and DHCP options
  424. /// for the client. The Host object should be passed in the context.
  425. /// Making this change would require a change to the allocateLease4
  426. /// API which would in turn require lots of changes in unit tests.
  427. /// The ticket introducing a context and host reservation in the
  428. /// allocation engine is complex enough by itself to warrant that
  429. /// the API change is done with a separate ticket.
  430. ClientContext4 ctx;
  431. ctx.subnet_ = subnet;
  432. ctx.clientid_ = clientid;
  433. ctx.hwaddr_ = hwaddr;
  434. ctx.requested_address_ = hint;
  435. ctx.fwd_dns_update_ = fwd_dns_update;
  436. ctx.rev_dns_update_ = rev_dns_update;
  437. ctx.hostname_ = hostname;
  438. ctx.fake_allocation_ = fake_allocation;
  439. ctx.callout_handle_ = callout_handle;
  440. ctx.old_lease_ = old_lease;
  441. ctx.host_ = HostMgr::instance().get4(subnet->getID(), hwaddr);
  442. // If there is a reservation for this client we want to allocate the
  443. // reserved address to the client, rather than any other address.
  444. if (ctx.host_) {
  445. // In some cases the client doesn't supply any address, e.g. when
  446. // it sends a DHCPDISCOVER. In such cases, we use the reserved
  447. // address as a hint.
  448. if (ctx.requested_address_ == IOAddress("0.0.0.0")) {
  449. ctx.requested_address_ = ctx.host_->getIPv4Reservation();
  450. // If the client supplied an address we have to check if this
  451. // address is reserved for this client. If not, we will send
  452. // DHCPNAK to inform the client that we were not able to
  453. // assign a requested address. The fake allocation (DHCPDISCOVER
  454. // case) is an exception. In such case we treat the address
  455. // supplied by the client as a hint, but we may offer address
  456. // other than desired by the client. So, we don't return an
  457. // empty lease.
  458. } else if (!ctx.fake_allocation_ &&
  459. (ctx.requested_address_ != ctx.host_->getIPv4Reservation())) {
  460. return (Lease4Ptr());
  461. }
  462. }
  463. // Check if the client has any leases in the lease database, using HW
  464. // address or client identifier.
  465. LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
  466. Lease4Ptr existing = lease_mgr.getLease4(*hwaddr, ctx.subnet_->getID());
  467. if (!existing && clientid) {
  468. existing = lease_mgr.getLease4(*clientid, ctx.subnet_->getID());
  469. }
  470. // If client has a lease there are two choices. The server may need
  471. // to renew (no address change) the lease. Or, the server may need
  472. // to replace the lease with a different one. This is the case when
  473. // the server has a dynamically assigned lease but an administrator
  474. // has made a new reservation for the client for a different address.
  475. if (existing) {
  476. existing = reallocateClientLease(existing, ctx);
  477. // The interrupt_processing_ flag indicates that the lease
  478. // reallocation was not successful and that the allocation
  479. // engine should cease allocation process for this client.
  480. // This may occur when the client is trying to renew the
  481. // lease which is reserved for someone else. The server should
  482. // send DHCPNAK to indicate that the client should try to
  483. // start over the allocation process.
  484. if (ctx.interrupt_processing_) {
  485. old_lease = ctx.old_lease_;
  486. return (Lease4Ptr());
  487. // If we tried to reallocate the reserved lease we return
  488. // at this point regardless if reallocation failed or passed.
  489. // We also return when allocation passed, no matter if this
  490. // was a reserved address or not.
  491. } else if (ctx.host_ || existing) {
  492. old_lease = ctx.old_lease_;
  493. return (existing);
  494. }
  495. }
  496. // There is no lease in the database for this client, so we will
  497. // proceed with a new allocation. We will try to allocate a
  498. // reserved address or an address from a dynamic pool if there is
  499. // no reservation.
  500. if (ctx.host_ || subnet->inPool(Lease::TYPE_V4, ctx.requested_address_)) {
  501. // If a client is requesting specific IP address, but the
  502. // reservation was made for a different address the server returns
  503. // NAK to the client. By returning NULL lease here we indicate to
  504. // the server that we're not able to fulfil client's request for the
  505. // particular IP address. We don't return NULL lease in case of the
  506. // fake allocation (DHCPDISCOVER) because in this case the address
  507. // supplied by the client is only a hint.
  508. if (!ctx.fake_allocation_ && ctx.host_ &&
  509. (ctx.requested_address_ != IOAddress("0.0.0.0")) &&
  510. (ctx.host_->getIPv4Reservation() != ctx.requested_address_)) {
  511. return (Lease4Ptr());
  512. }
  513. // The reserved address always takes precedence over an address
  514. // supplied by the client (renewed address or requested).
  515. const IOAddress& candidate = ctx.host_ ?
  516. ctx.host_->getIPv4Reservation() : ctx.requested_address_;
  517. // Once we picked an address we want to allocate, we have to check
  518. // if this address is available.
  519. existing = LeaseMgrFactory::instance().getLease4(candidate);
  520. if (!existing) {
  521. // The candidate address is currently unused. Let's create a
  522. // lease for it.
  523. Lease4Ptr lease = createLease4(subnet, clientid, hwaddr,
  524. candidate, fwd_dns_update,
  525. rev_dns_update,
  526. hostname, callout_handle,
  527. fake_allocation);
  528. // If we have allocated the lease let's return it. Also,
  529. // always return when tried to allocate reserved address,
  530. // regardless if allocation was successful or not. If it
  531. // was not successful, we will return a NULL pointer which
  532. // indicates to the server that it should send NAK to the
  533. // client.
  534. if (lease || ctx.host_) {
  535. return (lease);
  536. }
  537. // There is a lease for this address in the lease database but
  538. // it is possible that the lease has expired, in which case
  539. // we will be able to reuse it.
  540. } else {
  541. if (existing->expired()) {
  542. // Save the old lease, before reusing it.
  543. old_lease.reset(new Lease4(*existing));
  544. return (reuseExpiredLease(existing, ctx));
  545. // The existing lease is not expired (is in use by some
  546. // other client). If we are trying to get this lease because
  547. // the address has been reserved for the client we have no
  548. // choice but to return a NULL lease to indicate that the
  549. // allocation has failed.
  550. } else if (ctx.host_) {
  551. return (Lease4Ptr());
  552. }
  553. }
  554. }
  555. // No address was requested, requested address was not in pool or the
  556. // allocation was not successful so far. Let's try to find a different
  557. // address for the client. Search the pool until first of the following
  558. // occurs:
  559. // - we find a free address
  560. // - we find an address for which the lease has expired
  561. // - we exhaust the number of tries
  562. //
  563. /// @todo: Current code does not handle pool exhaustion well. It will be
  564. /// improved. Current problems:
  565. /// 1. with attempts set to too large value (e.g. 1000) and a small pool (e.g.
  566. /// 10 addresses), we will iterate over it 100 times before giving up
  567. /// 2. attempts 0 mean unlimited (this is really UINT_MAX, not infinite)
  568. /// 3. the whole concept of infinite attempts is just asking for infinite loop
  569. /// We may consider some form or reference counting (this pool has X addresses
  570. /// left), but this has one major problem. We exactly control allocation
  571. /// moment, but we currently do not control expiration time at all
  572. unsigned int i = attempts_;
  573. do {
  574. IOAddress candidate = allocator->pickAddress(subnet, clientid,
  575. ctx.requested_address_);
  576. // Check if this address is reserved. There is no need to check for
  577. // whom it is reserved, because if it has been reserved for us we would
  578. // have already allocated a lease.
  579. if (HostMgr::instance().get4(subnet->getID(), candidate)) {
  580. // Don't allocate a reserved address.
  581. continue;
  582. }
  583. Lease4Ptr existing = LeaseMgrFactory::instance().getLease4(candidate);
  584. if (!existing) {
  585. // there's no existing lease for selected candidate, so it is
  586. // free. Let's allocate it.
  587. Lease4Ptr lease = createLease4(subnet, clientid, hwaddr,
  588. candidate, fwd_dns_update,
  589. rev_dns_update, hostname,
  590. callout_handle, fake_allocation);
  591. if (lease) {
  592. return (lease);
  593. }
  594. // Although the address was free just microseconds ago, it may have
  595. // been taken just now. If the lease insertion fails, we continue
  596. // allocation attempts.
  597. } else {
  598. if (existing->expired()) {
  599. // Save old lease before reusing it.
  600. old_lease.reset(new Lease4(*existing));
  601. return (reuseExpiredLease(existing, ctx));
  602. }
  603. }
  604. // Continue trying allocation until we run out of attempts
  605. // (or attempts are set to 0, which means infinite)
  606. --i;
  607. } while ((i > 0) || !attempts_);
  608. // Unable to allocate an address, return an empty lease.
  609. LOG_WARN(dhcpsrv_logger, DHCPSRV_ADDRESS4_ALLOC_FAIL).arg(attempts_);
  610. } catch (const isc::Exception& e) {
  611. // Some other error, return an empty lease.
  612. LOG_ERROR(dhcpsrv_logger, DHCPSRV_ADDRESS4_ALLOC_ERROR).arg(e.what());
  613. }
  614. return (Lease4Ptr());
  615. }
  616. Lease4Ptr
  617. AllocEngine::renewLease4(const Lease4Ptr& lease,
  618. AllocEngine::ClientContext4& ctx) {
  619. if (!lease) {
  620. isc_throw(BadValue, "null lease specified for renewLease4");
  621. }
  622. // The ctx.host_ possibly contains a reservation for the client for which
  623. // we are renewing a lease. If this reservation exists, we assume that
  624. // there is no conflict in assigning the address to this client. Note
  625. // that the reallocateClientLease checks if the address reserved for
  626. // the client matches the address in the lease we're renewing here.
  627. if (!ctx.host_) {
  628. ConstHostPtr host = HostMgr::instance().get4(ctx.subnet_->getID(),
  629. lease->addr_);
  630. // Do not renew the lease if:
  631. // - If address is reserved for someone else or ...
  632. // - renewed address doesn't belong to a pool.
  633. if ((host && ctx.hwaddr_ && (*host->getHWAddress() != *ctx.hwaddr_)) ||
  634. (!ctx.subnet_->inPool(Lease::TYPE_V4, lease->addr_))) {
  635. ctx.interrupt_processing_ = !ctx.fake_allocation_;
  636. return (Lease4Ptr());
  637. }
  638. }
  639. // Let's keep the old data. This is essential if we are using memfile
  640. // (the lease returned points directly to the lease4 object in the database)
  641. // We'll need it if we want to skip update (i.e. roll back renewal)
  642. /// @todo: remove this once #3083 is implemented
  643. Lease4 old_values = *lease;
  644. // Update the lease with the information from the context.
  645. updateLease4Information(lease, ctx);
  646. bool skip = false;
  647. // Execute all callouts registered for lease4_renew.
  648. if (HooksManager::getHooksManager().
  649. calloutsPresent(Hooks.hook_index_lease4_renew_)) {
  650. // Delete all previous arguments
  651. ctx.callout_handle_->deleteAllArguments();
  652. // Subnet from which we do the allocation. Convert the general subnet
  653. // pointer to a pointer to a Subnet4. Note that because we are using
  654. // boost smart pointers here, we need to do the cast using the boost
  655. // version of dynamic_pointer_cast.
  656. Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(ctx.subnet_);
  657. // Pass the parameters
  658. ctx.callout_handle_->setArgument("subnet4", subnet4);
  659. ctx.callout_handle_->setArgument("clientid", ctx.clientid_);
  660. ctx.callout_handle_->setArgument("hwaddr", ctx.hwaddr_);
  661. // Pass the lease to be updated
  662. ctx.callout_handle_->setArgument("lease4", lease);
  663. // Call all installed callouts
  664. HooksManager::callCallouts(Hooks.hook_index_lease4_renew_,
  665. *ctx.callout_handle_);
  666. // Callouts decided to skip the next processing step. The next
  667. // processing step would to actually renew the lease, so skip at this
  668. // stage means "keep the old lease as it is".
  669. if (ctx.callout_handle_->getSkip()) {
  670. skip = true;
  671. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS,
  672. DHCPSRV_HOOK_LEASE4_RENEW_SKIP);
  673. }
  674. }
  675. if (!ctx.fake_allocation_ && !skip) {
  676. // for REQUEST we do update the lease
  677. LeaseMgrFactory::instance().updateLease4(lease);
  678. }
  679. if (skip) {
  680. // Rollback changes (really useful only for memfile)
  681. /// @todo: remove this once #3083 is implemented
  682. *lease = old_values;
  683. }
  684. return (lease);
  685. }
  686. Lease6Ptr AllocEngine::reuseExpiredLease(Lease6Ptr& expired,
  687. const Subnet6Ptr& subnet,
  688. const DuidPtr& duid,
  689. const uint32_t iaid,
  690. uint8_t prefix_len,
  691. const bool fwd_dns_update,
  692. const bool rev_dns_update,
  693. const std::string& hostname,
  694. const isc::hooks::CalloutHandlePtr& callout_handle,
  695. bool fake_allocation /*= false */ ) {
  696. if (!expired->expired()) {
  697. isc_throw(BadValue, "Attempt to recycle lease that is still valid");
  698. }
  699. if (expired->type_ != Lease::TYPE_PD) {
  700. prefix_len = 128; // non-PD lease types must be always /128
  701. }
  702. // address, lease type and prefixlen (0) stay the same
  703. expired->iaid_ = iaid;
  704. expired->duid_ = duid;
  705. expired->preferred_lft_ = subnet->getPreferred();
  706. expired->valid_lft_ = subnet->getValid();
  707. expired->t1_ = subnet->getT1();
  708. expired->t2_ = subnet->getT2();
  709. expired->cltt_ = time(NULL);
  710. expired->subnet_id_ = subnet->getID();
  711. expired->fixed_ = false;
  712. expired->hostname_ = hostname;
  713. expired->fqdn_fwd_ = fwd_dns_update;
  714. expired->fqdn_rev_ = rev_dns_update;
  715. expired->prefixlen_ = prefix_len;
  716. /// @todo: log here that the lease was reused (there's ticket #2524 for
  717. /// logging in libdhcpsrv)
  718. // Let's execute all callouts registered for lease6_select
  719. if (callout_handle &&
  720. HooksManager::getHooksManager().calloutsPresent(hook_index_lease6_select_)) {
  721. // Delete all previous arguments
  722. callout_handle->deleteAllArguments();
  723. // Pass necessary arguments
  724. // Subnet from which we do the allocation
  725. callout_handle->setArgument("subnet6", subnet);
  726. // Is this solicit (fake = true) or request (fake = false)
  727. callout_handle->setArgument("fake_allocation", fake_allocation);
  728. // The lease that will be assigned to a client
  729. callout_handle->setArgument("lease6", expired);
  730. // Call the callouts
  731. HooksManager::callCallouts(hook_index_lease6_select_, *callout_handle);
  732. // Callouts decided to skip the action. This means that the lease is not
  733. // assigned, so the client will get NoAddrAvail as a result. The lease
  734. // won't be inserted into the database.
  735. if (callout_handle->getSkip()) {
  736. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE6_SELECT_SKIP);
  737. return (Lease6Ptr());
  738. }
  739. // Let's use whatever callout returned. Hopefully it is the same lease
  740. // we handled to it.
  741. callout_handle->getArgument("lease6", expired);
  742. }
  743. if (!fake_allocation) {
  744. // for REQUEST we do update the lease
  745. LeaseMgrFactory::instance().updateLease6(expired);
  746. }
  747. // We do nothing for SOLICIT. We'll just update database when
  748. // the client gets back to us with REQUEST message.
  749. // it's not really expired at this stage anymore - let's return it as
  750. // an updated lease
  751. return (expired);
  752. }
  753. Lease4Ptr
  754. AllocEngine::reuseExpiredLease(Lease4Ptr& expired,
  755. AllocEngine::ClientContext4& ctx) {
  756. if (!expired) {
  757. isc_throw(BadValue, "null lease specified for reuseExpiredLease");
  758. }
  759. if (!ctx.subnet_) {
  760. isc_throw(BadValue, "null subnet specified for the reuseExpiredLease");
  761. }
  762. updateLease4Information(expired, ctx);
  763. expired->fixed_ = false;
  764. /// @todo: log here that the lease was reused (there's ticket #2524 for
  765. /// logging in libdhcpsrv)
  766. // Let's execute all callouts registered for lease4_select
  767. if (ctx.callout_handle_ && HooksManager::getHooksManager()
  768. .calloutsPresent(hook_index_lease4_select_)) {
  769. // Delete all previous arguments
  770. ctx.callout_handle_->deleteAllArguments();
  771. // Pass necessary arguments
  772. // Subnet from which we do the allocation. Convert the general subnet
  773. // pointer to a pointer to a Subnet4. Note that because we are using
  774. // boost smart pointers here, we need to do the cast using the boost
  775. // version of dynamic_pointer_cast.
  776. Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(ctx.subnet_);
  777. ctx.callout_handle_->setArgument("subnet4", subnet4);
  778. // Is this solicit (fake = true) or request (fake = false)
  779. ctx.callout_handle_->setArgument("fake_allocation",
  780. ctx.fake_allocation_);
  781. // The lease that will be assigned to a client
  782. ctx.callout_handle_->setArgument("lease4", expired);
  783. // Call the callouts
  784. HooksManager::callCallouts(hook_index_lease4_select_, *ctx.callout_handle_);
  785. // Callouts decided to skip the action. This means that the lease is not
  786. // assigned, so the client will get NoAddrAvail as a result. The lease
  787. // won't be inserted into the database.
  788. if (ctx.callout_handle_->getSkip()) {
  789. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS,
  790. DHCPSRV_HOOK_LEASE4_SELECT_SKIP);
  791. return (Lease4Ptr());
  792. }
  793. // Let's use whatever callout returned. Hopefully it is the same lease
  794. // we handled to it.
  795. ctx.callout_handle_->getArgument("lease4", expired);
  796. }
  797. if (!ctx.fake_allocation_) {
  798. // for REQUEST we do update the lease
  799. LeaseMgrFactory::instance().updateLease4(expired);
  800. }
  801. // We do nothing for SOLICIT. We'll just update database when
  802. // the client gets back to us with REQUEST message.
  803. // it's not really expired at this stage anymore - let's return it as
  804. // an updated lease
  805. return (expired);
  806. }
  807. Lease4Ptr
  808. AllocEngine::replaceClientLease(Lease4Ptr& lease, ClientContext4& ctx) {
  809. if (!lease) {
  810. isc_throw(BadValue, "null lease specified for replaceClientLease");
  811. }
  812. if (!ctx.subnet_) {
  813. isc_throw(BadValue, "null subnet specified for replaceClientLease");
  814. }
  815. if (ctx.requested_address_ == IOAddress("0.0.0.0")) {
  816. isc_throw(BadValue, "zero address specified for the"
  817. " replaceClientLease");
  818. }
  819. // Remember the previous address for this lease.
  820. IOAddress prev_address = lease->addr_;
  821. if (!ctx.host_) {
  822. ConstHostPtr host = HostMgr::instance().get4(ctx.subnet_->getID(),
  823. ctx.requested_address_);
  824. // If there is a reservation for the new address and the reservation
  825. // is made for another client, do not use this address.
  826. if (host && ctx.hwaddr_ && (*host->getHWAddress() != *ctx.hwaddr_)) {
  827. ctx.interrupt_processing_ = true;
  828. return (Lease4Ptr());
  829. }
  830. lease->addr_ = ctx.requested_address_;
  831. } else {
  832. lease->addr_ = ctx.host_->getIPv4Reservation();
  833. }
  834. updateLease4Information(lease, ctx);
  835. bool skip = false;
  836. // Execute callouts registered for lease4_select.
  837. if (ctx.callout_handle_ && HooksManager::getHooksManager()
  838. .calloutsPresent(hook_index_lease4_select_)) {
  839. // Delete all previous arguments.
  840. ctx.callout_handle_->deleteAllArguments();
  841. // Pass arguments.
  842. Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(ctx.subnet_);
  843. ctx.callout_handle_->setArgument("subnet4", subnet4);
  844. ctx.callout_handle_->setArgument("fake_allocation",
  845. ctx.fake_allocation_);
  846. ctx.callout_handle_->setArgument("lease4", lease);
  847. HooksManager::callCallouts(hook_index_lease4_select_,
  848. *ctx.callout_handle_);
  849. if (ctx.callout_handle_->getSkip()) {
  850. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS,
  851. DHCPSRV_HOOK_LEASE4_SELECT_SKIP);
  852. return (Lease4Ptr());
  853. }
  854. // Let's use whatever callout returned.
  855. ctx.callout_handle_->getArgument("lease4", lease);
  856. // Callouts decided to skip the next processing step. The next
  857. // processing step would to actually renew the lease, so skip at this
  858. // stage means "keep the old lease as it is".
  859. if (ctx.callout_handle_->getSkip()) {
  860. skip = true;
  861. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS,
  862. DHCPSRV_HOOK_LEASE4_SELECT_SKIP);
  863. }
  864. }
  865. /// @todo There should be a callout for a deletion of an old lease.
  866. /// The lease4_release callout is in appropriate, because by definition
  867. /// it is invoked when DHCPRELEASE packet is received.
  868. if (!ctx.fake_allocation_ && !skip) {
  869. // We can't use LeaseMgr::updateLease because it identifies the
  870. // lease by an IP address. Instead, we have to delete an old
  871. // lease and add a new one.
  872. LeaseMgrFactory::instance().deleteLease(prev_address);
  873. LeaseMgrFactory::instance().addLease(lease);
  874. }
  875. return (lease);
  876. }
  877. Lease4Ptr
  878. AllocEngine::reallocateClientLease(Lease4Ptr& lease,
  879. AllocEngine::ClientContext4& ctx) {
  880. // Save the old lease, before renewal.
  881. ctx.old_lease_.reset(new Lease4(*lease));
  882. /// The client's address will need to be modified in case if:
  883. /// - There is a reservation for the client (likely new one) and
  884. /// the currently used address is different.
  885. /// - Client requested some IP address and the requested address
  886. /// is different than the currently used one. Note that if this
  887. /// is a DHCPDISCOVER the requested IP address is ignored when
  888. /// it doesn't match the one in use.
  889. if ((ctx.host_ && (ctx.host_->getIPv4Reservation() != lease->addr_)) ||
  890. (!ctx.fake_allocation_ &&
  891. (ctx.requested_address_ != IOAddress("0.0.0.0")) &&
  892. (lease->addr_ != ctx.requested_address_))) {
  893. lease = replaceClientLease(lease, ctx);
  894. return (lease);
  895. } else {
  896. lease = renewLease4(lease, ctx);
  897. if (lease) {
  898. return (lease);
  899. }
  900. }
  901. return (Lease4Ptr());
  902. }
  903. Lease6Ptr AllocEngine::createLease6(const Subnet6Ptr& subnet,
  904. const DuidPtr& duid,
  905. const uint32_t iaid,
  906. const IOAddress& addr,
  907. uint8_t prefix_len,
  908. const Lease::Type type,
  909. const bool fwd_dns_update,
  910. const bool rev_dns_update,
  911. const std::string& hostname,
  912. const HWAddrPtr& hwaddr,
  913. const isc::hooks::CalloutHandlePtr& callout_handle,
  914. bool fake_allocation /*= false */ ) {
  915. if (type != Lease::TYPE_PD) {
  916. prefix_len = 128; // non-PD lease types must be always /128
  917. }
  918. Lease6Ptr lease(new Lease6(type, addr, duid, iaid,
  919. subnet->getPreferred(), subnet->getValid(),
  920. subnet->getT1(), subnet->getT2(), subnet->getID(),
  921. hwaddr, prefix_len));
  922. lease->fqdn_fwd_ = fwd_dns_update;
  923. lease->fqdn_rev_ = rev_dns_update;
  924. lease->hostname_ = hostname;
  925. // Let's execute all callouts registered for lease6_select
  926. if (callout_handle &&
  927. HooksManager::getHooksManager().calloutsPresent(hook_index_lease6_select_)) {
  928. // Delete all previous arguments
  929. callout_handle->deleteAllArguments();
  930. // Pass necessary arguments
  931. // Subnet from which we do the allocation
  932. callout_handle->setArgument("subnet6", subnet);
  933. // Is this solicit (fake = true) or request (fake = false)
  934. callout_handle->setArgument("fake_allocation", fake_allocation);
  935. callout_handle->setArgument("lease6", lease);
  936. // This is the first callout, so no need to clear any arguments
  937. HooksManager::callCallouts(hook_index_lease6_select_, *callout_handle);
  938. // Callouts decided to skip the action. This means that the lease is not
  939. // assigned, so the client will get NoAddrAvail as a result. The lease
  940. // won't be inserted into the database.
  941. if (callout_handle->getSkip()) {
  942. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE6_SELECT_SKIP);
  943. return (Lease6Ptr());
  944. }
  945. // Let's use whatever callout returned. Hopefully it is the same lease
  946. // we handled to it.
  947. callout_handle->getArgument("lease6", lease);
  948. }
  949. if (!fake_allocation) {
  950. // That is a real (REQUEST) allocation
  951. bool status = LeaseMgrFactory::instance().addLease(lease);
  952. if (status) {
  953. return (lease);
  954. } else {
  955. // One of many failures with LeaseMgr (e.g. lost connection to the
  956. // database, database failed etc.). One notable case for that
  957. // is that we are working in multi-process mode and we lost a race
  958. // (some other process got that address first)
  959. return (Lease6Ptr());
  960. }
  961. } else {
  962. // That is only fake (SOLICIT without rapid-commit) allocation
  963. // It is for advertise only. We should not insert the lease into LeaseMgr,
  964. // but rather check that we could have inserted it.
  965. Lease6Ptr existing = LeaseMgrFactory::instance().getLease6(
  966. Lease::TYPE_NA, addr);
  967. if (!existing) {
  968. return (lease);
  969. } else {
  970. return (Lease6Ptr());
  971. }
  972. }
  973. }
  974. Lease4Ptr AllocEngine::createLease4(const SubnetPtr& subnet,
  975. const DuidPtr& clientid,
  976. const HWAddrPtr& hwaddr,
  977. const IOAddress& addr,
  978. const bool fwd_dns_update,
  979. const bool rev_dns_update,
  980. const std::string& hostname,
  981. const isc::hooks::CalloutHandlePtr& callout_handle,
  982. bool fake_allocation /*= false */ ) {
  983. if (!hwaddr) {
  984. isc_throw(BadValue, "Can't create a lease with NULL HW address");
  985. }
  986. time_t now = time(NULL);
  987. // @todo: remove this kludge after ticket #2590 is implemented
  988. std::vector<uint8_t> local_copy;
  989. if (clientid) {
  990. local_copy = clientid->getDuid();
  991. }
  992. Lease4Ptr lease(new Lease4(addr, hwaddr, &local_copy[0], local_copy.size(),
  993. subnet->getValid(), subnet->getT1(), subnet->getT2(),
  994. now, subnet->getID()));
  995. // Set FQDN specific lease parameters.
  996. lease->fqdn_fwd_ = fwd_dns_update;
  997. lease->fqdn_rev_ = rev_dns_update;
  998. lease->hostname_ = hostname;
  999. // Let's execute all callouts registered for lease4_select
  1000. if (callout_handle &&
  1001. HooksManager::getHooksManager().calloutsPresent(hook_index_lease4_select_)) {
  1002. // Delete all previous arguments
  1003. callout_handle->deleteAllArguments();
  1004. // Pass necessary arguments
  1005. // Subnet from which we do the allocation (That's as far as we can go
  1006. // with using SubnetPtr to point to Subnet4 object. Users should not
  1007. // be confused with dynamic_pointer_casts. They should get a concrete
  1008. // pointer (Subnet4Ptr) pointing to a Subnet4 object.
  1009. Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(subnet);
  1010. callout_handle->setArgument("subnet4", subnet4);
  1011. // Is this solicit (fake = true) or request (fake = false)
  1012. callout_handle->setArgument("fake_allocation", fake_allocation);
  1013. // Pass the intended lease as well
  1014. callout_handle->setArgument("lease4", lease);
  1015. // This is the first callout, so no need to clear any arguments
  1016. HooksManager::callCallouts(hook_index_lease4_select_, *callout_handle);
  1017. // Callouts decided to skip the action. This means that the lease is not
  1018. // assigned, so the client will get NoAddrAvail as a result. The lease
  1019. // won't be inserted into the database.
  1020. if (callout_handle->getSkip()) {
  1021. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE4_SELECT_SKIP);
  1022. return (Lease4Ptr());
  1023. }
  1024. // Let's use whatever callout returned. Hopefully it is the same lease
  1025. // we handled to it.
  1026. callout_handle->getArgument("lease4", lease);
  1027. }
  1028. if (!fake_allocation) {
  1029. // That is a real (REQUEST) allocation
  1030. bool status = LeaseMgrFactory::instance().addLease(lease);
  1031. if (status) {
  1032. return (lease);
  1033. } else {
  1034. // One of many failures with LeaseMgr (e.g. lost connection to the
  1035. // database, database failed etc.). One notable case for that
  1036. // is that we are working in multi-process mode and we lost a race
  1037. // (some other process got that address first)
  1038. return (Lease4Ptr());
  1039. }
  1040. } else {
  1041. // That is only fake (DISCOVER) allocation
  1042. // It is for OFFER only. We should not insert the lease into LeaseMgr,
  1043. // but rather check that we could have inserted it.
  1044. Lease4Ptr existing = LeaseMgrFactory::instance().getLease4(addr);
  1045. if (!existing) {
  1046. return (lease);
  1047. } else {
  1048. return (Lease4Ptr());
  1049. }
  1050. }
  1051. }
  1052. void
  1053. AllocEngine::updateLease4Information(const Lease4Ptr& lease,
  1054. AllocEngine::ClientContext4& ctx) const {
  1055. // This should not happen in theory.
  1056. if (!lease) {
  1057. isc_throw(BadValue, "null lease specified for updateLease4Information");
  1058. }
  1059. if (!ctx.subnet_) {
  1060. isc_throw(BadValue, "null subnet specified for"
  1061. " updateLease4Information");
  1062. }
  1063. lease->subnet_id_ = ctx.subnet_->getID();
  1064. lease->hwaddr_ = ctx.hwaddr_;
  1065. lease->client_id_ = ctx.clientid_;
  1066. lease->cltt_ = time(NULL);
  1067. lease->t1_ = ctx.subnet_->getT1();
  1068. lease->t2_ = ctx.subnet_->getT2();
  1069. lease->valid_lft_ = ctx.subnet_->getValid();
  1070. lease->fqdn_fwd_ = ctx.fwd_dns_update_;
  1071. lease->fqdn_rev_ = ctx.rev_dns_update_;
  1072. lease->hostname_ = ctx.hostname_;
  1073. }
  1074. Lease6Collection
  1075. AllocEngine::updateFqdnData(const Lease6Collection& leases,
  1076. const bool fwd_dns_update,
  1077. const bool rev_dns_update,
  1078. const std::string& hostname,
  1079. const bool fake_allocation) {
  1080. Lease6Collection updated_leases;
  1081. for (Lease6Collection::const_iterator lease_it = leases.begin();
  1082. lease_it != leases.end(); ++lease_it) {
  1083. Lease6Ptr lease(new Lease6(**lease_it));
  1084. lease->fqdn_fwd_ = fwd_dns_update;
  1085. lease->fqdn_rev_ = rev_dns_update;
  1086. lease->hostname_ = hostname;
  1087. if (!fake_allocation &&
  1088. ((lease->fqdn_fwd_ != (*lease_it)->fqdn_fwd_) ||
  1089. (lease->fqdn_rev_ != (*lease_it)->fqdn_rev_) ||
  1090. (lease->hostname_ != (*lease_it)->hostname_))) {
  1091. LeaseMgrFactory::instance().updateLease6(lease);
  1092. }
  1093. updated_leases.push_back(lease);
  1094. }
  1095. return (updated_leases);
  1096. }
  1097. AllocEngine::AllocatorPtr AllocEngine::getAllocator(Lease::Type type) {
  1098. std::map<Lease::Type, AllocatorPtr>::const_iterator alloc = allocators_.find(type);
  1099. if (alloc == allocators_.end()) {
  1100. isc_throw(BadValue, "No allocator initialized for pool type "
  1101. << Lease::typeToText(type));
  1102. }
  1103. return (alloc->second);
  1104. }
  1105. AllocEngine::~AllocEngine() {
  1106. // no need to delete allocator. smart_ptr will do the trick for us
  1107. }
  1108. }; // end of isc::dhcp namespace
  1109. }; // end of isc namespace