alloc_engine.cc 44 KB

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