alloc_engine.cc 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  1. // Copyright (C) 2012-2013 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()
  46. :Allocator() {
  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::pickAddress(const SubnetPtr& subnet,
  73. const DuidPtr&,
  74. const IOAddress&) {
  75. // Let's get the last allocated address. It is usually set correctly,
  76. // but there are times when it won't be (like after removing a pool or
  77. // perhaps restarting the server).
  78. IOAddress last = subnet->getLastAllocated();
  79. const PoolCollection& pools = subnet->getPools();
  80. if (pools.empty()) {
  81. isc_throw(AllocFailed, "No pools defined in selected subnet");
  82. }
  83. // first we need to find a pool the last address belongs to.
  84. PoolCollection::const_iterator it;
  85. for (it = pools.begin(); it != pools.end(); ++it) {
  86. if ((*it)->inRange(last)) {
  87. break;
  88. }
  89. }
  90. // last one was bogus for one of several reasons:
  91. // - we just booted up and that's the first address we're allocating
  92. // - a subnet was removed or other reconfiguration just completed
  93. // - perhaps allocation algorithm was changed
  94. if (it == pools.end()) {
  95. // ok to access first element directly. We checked that pools is non-empty
  96. IOAddress next = pools[0]->getFirstAddress();
  97. subnet->setLastAllocated(next);
  98. return (next);
  99. }
  100. // Ok, we have a pool that the last address belonged to, let's use it.
  101. IOAddress next = increaseAddress(last); // basically addr++
  102. if ((*it)->inRange(next)) {
  103. // the next one is in the pool as well, so we haven't hit pool boundary yet
  104. subnet->setLastAllocated(next);
  105. return (next);
  106. }
  107. // We hit pool boundary, let's try to jump to the next pool and try again
  108. ++it;
  109. if (it == pools.end()) {
  110. // Really out of luck today. That was the last pool. Let's rewind
  111. // to the beginning.
  112. next = pools[0]->getFirstAddress();
  113. subnet->setLastAllocated(next);
  114. return (next);
  115. }
  116. // there is a next pool, let's try first address from it
  117. next = (*it)->getFirstAddress();
  118. subnet->setLastAllocated(next);
  119. return (next);
  120. }
  121. AllocEngine::HashedAllocator::HashedAllocator()
  122. :Allocator() {
  123. isc_throw(NotImplemented, "Hashed allocator is not implemented");
  124. }
  125. isc::asiolink::IOAddress
  126. AllocEngine::HashedAllocator::pickAddress(const SubnetPtr&,
  127. const DuidPtr&,
  128. const IOAddress&) {
  129. isc_throw(NotImplemented, "Hashed allocator is not implemented");
  130. }
  131. AllocEngine::RandomAllocator::RandomAllocator()
  132. :Allocator() {
  133. isc_throw(NotImplemented, "Random allocator is not implemented");
  134. }
  135. isc::asiolink::IOAddress
  136. AllocEngine::RandomAllocator::pickAddress(const SubnetPtr&,
  137. const DuidPtr&,
  138. const IOAddress&) {
  139. isc_throw(NotImplemented, "Random allocator is not implemented");
  140. }
  141. AllocEngine::AllocEngine(AllocType engine_type, unsigned int attempts)
  142. :attempts_(attempts) {
  143. switch (engine_type) {
  144. case ALLOC_ITERATIVE:
  145. allocator_ = boost::shared_ptr<Allocator>(new IterativeAllocator());
  146. break;
  147. case ALLOC_HASHED:
  148. allocator_ = boost::shared_ptr<Allocator>(new HashedAllocator());
  149. break;
  150. case ALLOC_RANDOM:
  151. allocator_ = boost::shared_ptr<Allocator>(new RandomAllocator());
  152. break;
  153. default:
  154. isc_throw(BadValue, "Invalid/unsupported allocation algorithm");
  155. }
  156. // Register hook points
  157. hook_index_lease4_select_ = Hooks.hook_index_lease4_select_;
  158. hook_index_lease6_select_ = Hooks.hook_index_lease6_select_;
  159. }
  160. Lease6Collection
  161. AllocEngine::allocateAddress6(const Subnet6Ptr& subnet,
  162. const DuidPtr& duid,
  163. uint32_t iaid,
  164. const IOAddress& hint,
  165. const bool fwd_dns_update,
  166. const bool rev_dns_update,
  167. const std::string& hostname,
  168. bool fake_allocation,
  169. const isc::hooks::CalloutHandlePtr& callout_handle) {
  170. try {
  171. // That check is not necessary. We create allocator in AllocEngine
  172. // constructor
  173. if (!allocator_) {
  174. isc_throw(InvalidOperation, "No allocator selected");
  175. }
  176. if (!subnet) {
  177. isc_throw(InvalidOperation, "Subnet is required for allocation");
  178. }
  179. if (!duid) {
  180. isc_throw(InvalidOperation, "DUID is mandatory for allocation");
  181. }
  182. // check if there's existing lease for that subnet/duid/iaid combination.
  183. /// @todo: Make this generic (cover temp. addrs and prefixes)
  184. Lease6Collection existing = LeaseMgrFactory::instance().getLeases6(
  185. Lease6::LEASE_IA_NA, *duid, iaid, subnet->getID());
  186. if (!existing.empty()) {
  187. // we have at least one lease already. This is a returning client,
  188. // probably after his reboot.
  189. return (existing);
  190. }
  191. // check if the hint is in pool and is available
  192. if (subnet->inPool(hint)) {
  193. /// @todo: We support only one hint for now
  194. Lease6Ptr lease = LeaseMgrFactory::instance().getLease6(
  195. Lease6::LEASE_IA_NA, hint);
  196. if (!lease) {
  197. /// @todo: check if the hint is reserved once we have host support
  198. /// implemented
  199. // the hint is valid and not currently used, let's create a lease for it
  200. /// @todo: We support only one lease per ia for now
  201. lease = createLease6(subnet, duid, iaid, hint, fwd_dns_update,
  202. rev_dns_update, hostname, callout_handle,
  203. fake_allocation);
  204. // It can happen that the lease allocation failed (we could have lost
  205. // the race condition. That means that the hint is lo longer usable and
  206. // we need to continue the regular allocation path.
  207. if (lease) {
  208. /// @todo: We support only one lease per ia for now
  209. Lease6Collection collection;
  210. collection.push_back(lease);
  211. return (collection);
  212. }
  213. } else {
  214. if (lease->expired()) {
  215. /// We found a lease and it is expired, so we can reuse it
  216. /// @todo: We support only one lease per ia for now
  217. lease = reuseExpiredLease(lease, subnet, duid, iaid,
  218. fwd_dns_update, rev_dns_update,
  219. hostname, callout_handle,
  220. fake_allocation);
  221. Lease6Collection collection;
  222. collection.push_back(lease);
  223. return (collection);
  224. }
  225. }
  226. }
  227. // Hint is in the pool but is not available. Search the pool until first of
  228. // the following occurs:
  229. // - we find a free address
  230. // - we find an address for which the lease has expired
  231. // - we exhaust number of tries
  232. //
  233. // @todo: Current code does not handle pool exhaustion well. It will be
  234. // improved. Current problems:
  235. // 1. with attempts set to too large value (e.g. 1000) and a small pool (e.g.
  236. // 10 addresses), we will iterate over it 100 times before giving up
  237. // 2. attempts 0 mean unlimited (this is really UINT_MAX, not infinite)
  238. // 3. the whole concept of infinite attempts is just asking for infinite loop
  239. // We may consider some form or reference counting (this pool has X addresses
  240. // left), but this has one major problem. We exactly control allocation
  241. // moment, but we currently do not control expiration time at all
  242. unsigned int i = attempts_;
  243. do {
  244. IOAddress candidate = allocator_->pickAddress(subnet, duid, hint);
  245. /// @todo: check if the address is reserved once we have host support
  246. /// implemented
  247. Lease6Ptr existing = LeaseMgrFactory::instance().getLease6(
  248. Lease6::LEASE_IA_NA, candidate);
  249. if (!existing) {
  250. // there's no existing lease for selected candidate, so it is
  251. // free. Let's allocate it.
  252. Lease6Ptr lease = createLease6(subnet, duid, iaid, candidate,
  253. fwd_dns_update, rev_dns_update,
  254. hostname,
  255. callout_handle, fake_allocation);
  256. if (lease) {
  257. Lease6Collection collection;
  258. collection.push_back(lease);
  259. return (collection);
  260. }
  261. // Although the address was free just microseconds ago, it may have
  262. // been taken just now. If the lease insertion fails, we continue
  263. // allocation attempts.
  264. } else {
  265. if (existing->expired()) {
  266. existing = reuseExpiredLease(existing, subnet, duid, iaid,
  267. fwd_dns_update, rev_dns_update,
  268. hostname, callout_handle,
  269. fake_allocation);
  270. Lease6Collection collection;
  271. collection.push_back(existing);
  272. return (collection);
  273. }
  274. }
  275. // Continue trying allocation until we run out of attempts
  276. // (or attempts are set to 0, which means infinite)
  277. --i;
  278. } while ((i > 0) || !attempts_);
  279. // Unable to allocate an address, return an empty lease.
  280. LOG_WARN(dhcpsrv_logger, DHCPSRV_ADDRESS6_ALLOC_FAIL).arg(attempts_);
  281. } catch (const isc::Exception& e) {
  282. // Some other error, return an empty lease.
  283. LOG_ERROR(dhcpsrv_logger, DHCPSRV_ADDRESS6_ALLOC_ERROR).arg(e.what());
  284. }
  285. return (Lease6Collection());
  286. }
  287. Lease4Ptr
  288. AllocEngine::allocateAddress4(const SubnetPtr& subnet,
  289. const ClientIdPtr& clientid,
  290. const HWAddrPtr& hwaddr,
  291. const IOAddress& hint,
  292. const bool fwd_dns_update,
  293. const bool rev_dns_update,
  294. const std::string& hostname,
  295. bool fake_allocation,
  296. const isc::hooks::CalloutHandlePtr& callout_handle,
  297. Lease4Ptr& old_lease) {
  298. // The NULL pointer indicates that the old lease didn't exist. It may
  299. // be later set to non NULL value if existing lease is found in the
  300. // database.
  301. old_lease.reset();
  302. try {
  303. // Allocator is always created in AllocEngine constructor and there is
  304. // currently no other way to set it, so that check is not really necessary.
  305. if (!allocator_) {
  306. isc_throw(InvalidOperation, "No allocator selected");
  307. }
  308. if (!subnet) {
  309. isc_throw(InvalidOperation, "Can't allocate IPv4 address without subnet");
  310. }
  311. if (!hwaddr) {
  312. isc_throw(InvalidOperation, "HWAddr must be defined");
  313. }
  314. // Check if there's existing lease for that subnet/clientid/hwaddr combination.
  315. Lease4Ptr existing = LeaseMgrFactory::instance().getLease4(*hwaddr, subnet->getID());
  316. if (existing) {
  317. // Save the old lease, before renewal.
  318. old_lease.reset(new Lease4(*existing));
  319. // We have a lease already. This is a returning client, probably after
  320. // its reboot.
  321. existing = renewLease4(subnet, clientid, hwaddr,
  322. fwd_dns_update, rev_dns_update, hostname,
  323. existing, callout_handle, fake_allocation);
  324. if (existing) {
  325. return (existing);
  326. }
  327. // If renewal failed (e.g. the lease no longer matches current configuration)
  328. // let's continue the allocation process
  329. }
  330. if (clientid) {
  331. existing = LeaseMgrFactory::instance().getLease4(*clientid, subnet->getID());
  332. if (existing) {
  333. // Save the old lease before renewal.
  334. old_lease.reset(new Lease4(*existing));
  335. // we have a lease already. This is a returning client, probably after
  336. // its reboot.
  337. existing = renewLease4(subnet, clientid, hwaddr,
  338. fwd_dns_update, rev_dns_update,
  339. hostname, existing, callout_handle,
  340. fake_allocation);
  341. // @todo: produce a warning. We haven't found him using MAC address, but
  342. // we found him using client-id
  343. if (existing) {
  344. return (existing);
  345. }
  346. }
  347. }
  348. // check if the hint is in pool and is available
  349. if (subnet->inPool(hint)) {
  350. existing = LeaseMgrFactory::instance().getLease4(hint);
  351. if (!existing) {
  352. /// @todo: Check if the hint is reserved once we have host support
  353. /// implemented
  354. // The hint is valid and not currently used, let's create a lease for it
  355. Lease4Ptr lease = createLease4(subnet, clientid, hwaddr, hint,
  356. fwd_dns_update, rev_dns_update,
  357. hostname, callout_handle,
  358. fake_allocation);
  359. // It can happen that the lease allocation failed (we could have lost
  360. // the race condition. That means that the hint is lo longer usable and
  361. // we need to continue the regular allocation path.
  362. if (lease) {
  363. return (lease);
  364. }
  365. } else {
  366. if (existing->expired()) {
  367. // Save the old lease, before reusing it.
  368. old_lease.reset(new Lease4(*existing));
  369. return (reuseExpiredLease(existing, subnet, clientid, hwaddr,
  370. fwd_dns_update, rev_dns_update,
  371. hostname, callout_handle,
  372. fake_allocation));
  373. }
  374. }
  375. }
  376. // Hint is in the pool but is not available. Search the pool until first of
  377. // the following occurs:
  378. // - we find a free address
  379. // - we find an address for which the lease has expired
  380. // - we exhaust the number of tries
  381. //
  382. // @todo: Current code does not handle pool exhaustion well. It will be
  383. // improved. Current problems:
  384. // 1. with attempts set to too large value (e.g. 1000) and a small pool (e.g.
  385. // 10 addresses), we will iterate over it 100 times before giving up
  386. // 2. attempts 0 mean unlimited (this is really UINT_MAX, not infinite)
  387. // 3. the whole concept of infinite attempts is just asking for infinite loop
  388. // We may consider some form or reference counting (this pool has X addresses
  389. // left), but this has one major problem. We exactly control allocation
  390. // moment, but we currently do not control expiration time at all
  391. unsigned int i = attempts_;
  392. do {
  393. IOAddress candidate = allocator_->pickAddress(subnet, clientid, hint);
  394. /// @todo: check if the address is reserved once we have host support
  395. /// implemented
  396. Lease4Ptr existing = LeaseMgrFactory::instance().getLease4(candidate);
  397. if (!existing) {
  398. // there's no existing lease for selected candidate, so it is
  399. // free. Let's allocate it.
  400. Lease4Ptr lease = createLease4(subnet, clientid, hwaddr,
  401. candidate, fwd_dns_update,
  402. rev_dns_update, hostname,
  403. callout_handle, fake_allocation);
  404. if (lease) {
  405. return (lease);
  406. }
  407. // Although the address was free just microseconds ago, it may have
  408. // been taken just now. If the lease insertion fails, we continue
  409. // allocation attempts.
  410. } else {
  411. if (existing->expired()) {
  412. // Save old lease before reusing it.
  413. old_lease.reset(new Lease4(*existing));
  414. return (reuseExpiredLease(existing, subnet, clientid, hwaddr,
  415. fwd_dns_update, rev_dns_update,
  416. hostname, callout_handle,
  417. fake_allocation));
  418. }
  419. }
  420. // Continue trying allocation until we run out of attempts
  421. // (or attempts are set to 0, which means infinite)
  422. --i;
  423. } while ((i > 0) || !attempts_);
  424. // Unable to allocate an address, return an empty lease.
  425. LOG_WARN(dhcpsrv_logger, DHCPSRV_ADDRESS4_ALLOC_FAIL).arg(attempts_);
  426. } catch (const isc::Exception& e) {
  427. // Some other error, return an empty lease.
  428. LOG_ERROR(dhcpsrv_logger, DHCPSRV_ADDRESS4_ALLOC_ERROR).arg(e.what());
  429. }
  430. return (Lease4Ptr());
  431. }
  432. Lease4Ptr AllocEngine::renewLease4(const SubnetPtr& subnet,
  433. const ClientIdPtr& clientid,
  434. const HWAddrPtr& hwaddr,
  435. const bool fwd_dns_update,
  436. const bool rev_dns_update,
  437. const std::string& hostname,
  438. const Lease4Ptr& lease,
  439. const isc::hooks::CalloutHandlePtr& callout_handle,
  440. bool fake_allocation /* = false */) {
  441. if (!lease) {
  442. isc_throw(InvalidOperation, "Lease4 must be specified");
  443. }
  444. // Let's keep the old data. This is essential if we are using memfile
  445. // (the lease returned points directly to the lease4 object in the database)
  446. // We'll need it if we want to skip update (i.e. roll back renewal)
  447. /// @todo: remove this once #3083 is implemented
  448. Lease4 old_values = *lease;
  449. lease->subnet_id_ = subnet->getID();
  450. lease->hwaddr_ = hwaddr->hwaddr_;
  451. lease->client_id_ = clientid;
  452. lease->cltt_ = time(NULL);
  453. lease->t1_ = subnet->getT1();
  454. lease->t2_ = subnet->getT2();
  455. lease->valid_lft_ = subnet->getValid();
  456. lease->fqdn_fwd_ = fwd_dns_update;
  457. lease->fqdn_rev_ = rev_dns_update;
  458. lease->hostname_ = hostname;
  459. bool skip = false;
  460. // Execute all callouts registered for packet6_send
  461. if (HooksManager::getHooksManager().calloutsPresent(Hooks.hook_index_lease4_renew_)) {
  462. // Delete all previous arguments
  463. callout_handle->deleteAllArguments();
  464. // Subnet from which we do the allocation. Convert the general subnet
  465. // pointer to a pointer to a Subnet4. Note that because we are using
  466. // boost smart pointers here, we need to do the cast using the boost
  467. // version of dynamic_pointer_cast.
  468. Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(subnet);
  469. // Pass the parameters
  470. callout_handle->setArgument("subnet4", subnet4);
  471. callout_handle->setArgument("clientid", clientid);
  472. callout_handle->setArgument("hwaddr", hwaddr);
  473. // Pass the lease to be updated
  474. callout_handle->setArgument("lease4", lease);
  475. // Call all installed callouts
  476. HooksManager::callCallouts(Hooks.hook_index_lease4_renew_, *callout_handle);
  477. // Callouts decided to skip the next processing step. The next
  478. // processing step would to actually renew the lease, so skip at this
  479. // stage means "keep the old lease as it is".
  480. if (callout_handle->getSkip()) {
  481. skip = true;
  482. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE4_RENEW_SKIP);
  483. }
  484. }
  485. if (!fake_allocation && !skip) {
  486. // for REQUEST we do update the lease
  487. LeaseMgrFactory::instance().updateLease4(lease);
  488. }
  489. if (skip) {
  490. // Rollback changes (really useful only for memfile)
  491. /// @todo: remove this once #3083 is implemented
  492. *lease = old_values;
  493. }
  494. return (lease);
  495. }
  496. Lease6Ptr AllocEngine::reuseExpiredLease(Lease6Ptr& expired,
  497. const Subnet6Ptr& subnet,
  498. const DuidPtr& duid,
  499. uint32_t iaid,
  500. const bool fwd_dns_update,
  501. const bool rev_dns_update,
  502. const std::string& hostname,
  503. const isc::hooks::CalloutHandlePtr& callout_handle,
  504. bool fake_allocation /*= false */ ) {
  505. if (!expired->expired()) {
  506. isc_throw(BadValue, "Attempt to recycle lease that is still valid");
  507. }
  508. // address, lease type and prefixlen (0) stay the same
  509. expired->iaid_ = iaid;
  510. expired->duid_ = duid;
  511. expired->preferred_lft_ = subnet->getPreferred();
  512. expired->valid_lft_ = subnet->getValid();
  513. expired->t1_ = subnet->getT1();
  514. expired->t2_ = subnet->getT2();
  515. expired->cltt_ = time(NULL);
  516. expired->subnet_id_ = subnet->getID();
  517. expired->fixed_ = false;
  518. expired->hostname_ = hostname;
  519. expired->fqdn_fwd_ = fwd_dns_update;
  520. expired->fqdn_rev_ = rev_dns_update;
  521. /// @todo: log here that the lease was reused (there's ticket #2524 for
  522. /// logging in libdhcpsrv)
  523. // Let's execute all callouts registered for lease6_select
  524. if (callout_handle &&
  525. HooksManager::getHooksManager().calloutsPresent(hook_index_lease6_select_)) {
  526. // Delete all previous arguments
  527. callout_handle->deleteAllArguments();
  528. // Pass necessary arguments
  529. // Subnet from which we do the allocation
  530. callout_handle->setArgument("subnet6", subnet);
  531. // Is this solicit (fake = true) or request (fake = false)
  532. callout_handle->setArgument("fake_allocation", fake_allocation);
  533. // The lease that will be assigned to a client
  534. callout_handle->setArgument("lease6", expired);
  535. // Call the callouts
  536. HooksManager::callCallouts(hook_index_lease6_select_, *callout_handle);
  537. // Callouts decided to skip the action. This means that the lease is not
  538. // assigned, so the client will get NoAddrAvail as a result. The lease
  539. // won't be inserted into the database.
  540. if (callout_handle->getSkip()) {
  541. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE6_SELECT_SKIP);
  542. return (Lease6Ptr());
  543. }
  544. // Let's use whatever callout returned. Hopefully it is the same lease
  545. // we handled to it.
  546. callout_handle->getArgument("lease6", expired);
  547. }
  548. if (!fake_allocation) {
  549. // for REQUEST we do update the lease
  550. LeaseMgrFactory::instance().updateLease6(expired);
  551. }
  552. // We do nothing for SOLICIT. We'll just update database when
  553. // the client gets back to us with REQUEST message.
  554. // it's not really expired at this stage anymore - let's return it as
  555. // an updated lease
  556. return (expired);
  557. }
  558. Lease4Ptr AllocEngine::reuseExpiredLease(Lease4Ptr& expired,
  559. const SubnetPtr& subnet,
  560. const ClientIdPtr& clientid,
  561. const HWAddrPtr& hwaddr,
  562. const bool fwd_dns_update,
  563. const bool rev_dns_update,
  564. const std::string& hostname,
  565. const isc::hooks::CalloutHandlePtr& callout_handle,
  566. bool fake_allocation /*= false */ ) {
  567. if (!expired->expired()) {
  568. isc_throw(BadValue, "Attempt to recycle lease that is still valid");
  569. }
  570. // address, lease type and prefixlen (0) stay the same
  571. expired->client_id_ = clientid;
  572. expired->hwaddr_ = hwaddr->hwaddr_;
  573. expired->valid_lft_ = subnet->getValid();
  574. expired->t1_ = subnet->getT1();
  575. expired->t2_ = subnet->getT2();
  576. expired->cltt_ = time(NULL);
  577. expired->subnet_id_ = subnet->getID();
  578. expired->fixed_ = false;
  579. expired->hostname_ = hostname;
  580. expired->fqdn_fwd_ = fwd_dns_update;
  581. expired->fqdn_rev_ = rev_dns_update;
  582. /// @todo: log here that the lease was reused (there's ticket #2524 for
  583. /// logging in libdhcpsrv)
  584. // Let's execute all callouts registered for lease4_select
  585. if (callout_handle &&
  586. HooksManager::getHooksManager().calloutsPresent(hook_index_lease4_select_)) {
  587. // Delete all previous arguments
  588. callout_handle->deleteAllArguments();
  589. // Pass necessary arguments
  590. // Subnet from which we do the allocation. Convert the general subnet
  591. // pointer to a pointer to a Subnet4. Note that because we are using
  592. // boost smart pointers here, we need to do the cast using the boost
  593. // version of dynamic_pointer_cast.
  594. Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(subnet);
  595. callout_handle->setArgument("subnet4", subnet4);
  596. // Is this solicit (fake = true) or request (fake = false)
  597. callout_handle->setArgument("fake_allocation", fake_allocation);
  598. // The lease that will be assigned to a client
  599. callout_handle->setArgument("lease4", expired);
  600. // Call the callouts
  601. HooksManager::callCallouts(hook_index_lease6_select_, *callout_handle);
  602. // Callouts decided to skip the action. This means that the lease is not
  603. // assigned, so the client will get NoAddrAvail as a result. The lease
  604. // won't be inserted into the database.
  605. if (callout_handle->getSkip()) {
  606. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE4_SELECT_SKIP);
  607. return (Lease4Ptr());
  608. }
  609. // Let's use whatever callout returned. Hopefully it is the same lease
  610. // we handled to it.
  611. callout_handle->getArgument("lease4", expired);
  612. }
  613. if (!fake_allocation) {
  614. // for REQUEST we do update the lease
  615. LeaseMgrFactory::instance().updateLease4(expired);
  616. }
  617. // We do nothing for SOLICIT. We'll just update database when
  618. // the client gets back to us with REQUEST message.
  619. // it's not really expired at this stage anymore - let's return it as
  620. // an updated lease
  621. return (expired);
  622. }
  623. Lease6Ptr AllocEngine::createLease6(const Subnet6Ptr& subnet,
  624. const DuidPtr& duid,
  625. uint32_t iaid,
  626. const IOAddress& addr,
  627. const bool fwd_dns_update,
  628. const bool rev_dns_update,
  629. const std::string& hostname,
  630. const isc::hooks::CalloutHandlePtr& callout_handle,
  631. bool fake_allocation /*= false */ ) {
  632. Lease6Ptr lease(new Lease6(Lease6::LEASE_IA_NA, addr, duid, iaid,
  633. subnet->getPreferred(), subnet->getValid(),
  634. subnet->getT1(), subnet->getT2(), subnet->getID()));
  635. lease->fqdn_fwd_ = fwd_dns_update;
  636. lease->fqdn_rev_ = rev_dns_update;
  637. lease->hostname_ = hostname;
  638. // Let's execute all callouts registered for lease6_select
  639. if (callout_handle &&
  640. HooksManager::getHooksManager().calloutsPresent(hook_index_lease6_select_)) {
  641. // Delete all previous arguments
  642. callout_handle->deleteAllArguments();
  643. // Pass necessary arguments
  644. // Subnet from which we do the allocation
  645. callout_handle->setArgument("subnet6", subnet);
  646. // Is this solicit (fake = true) or request (fake = false)
  647. callout_handle->setArgument("fake_allocation", fake_allocation);
  648. callout_handle->setArgument("lease6", lease);
  649. // This is the first callout, so no need to clear any arguments
  650. HooksManager::callCallouts(hook_index_lease6_select_, *callout_handle);
  651. // Callouts decided to skip the action. This means that the lease is not
  652. // assigned, so the client will get NoAddrAvail as a result. The lease
  653. // won't be inserted into the database.
  654. if (callout_handle->getSkip()) {
  655. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE6_SELECT_SKIP);
  656. return (Lease6Ptr());
  657. }
  658. // Let's use whatever callout returned. Hopefully it is the same lease
  659. // we handled to it.
  660. callout_handle->getArgument("lease6", lease);
  661. }
  662. if (!fake_allocation) {
  663. // That is a real (REQUEST) allocation
  664. bool status = LeaseMgrFactory::instance().addLease(lease);
  665. if (status) {
  666. return (lease);
  667. } else {
  668. // One of many failures with LeaseMgr (e.g. lost connection to the
  669. // database, database failed etc.). One notable case for that
  670. // is that we are working in multi-process mode and we lost a race
  671. // (some other process got that address first)
  672. return (Lease6Ptr());
  673. }
  674. } else {
  675. // That is only fake (SOLICIT without rapid-commit) allocation
  676. // It is for advertise only. We should not insert the lease into LeaseMgr,
  677. // but rather check that we could have inserted it.
  678. Lease6Ptr existing = LeaseMgrFactory::instance().getLease6(
  679. Lease6::LEASE_IA_NA, addr);
  680. if (!existing) {
  681. return (lease);
  682. } else {
  683. return (Lease6Ptr());
  684. }
  685. }
  686. }
  687. Lease4Ptr AllocEngine::createLease4(const SubnetPtr& subnet,
  688. const DuidPtr& clientid,
  689. const HWAddrPtr& hwaddr,
  690. const IOAddress& addr,
  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 (!hwaddr) {
  697. isc_throw(BadValue, "Can't create a lease with NULL HW address");
  698. }
  699. time_t now = time(NULL);
  700. // @todo: remove this kludge after ticket #2590 is implemented
  701. std::vector<uint8_t> local_copy;
  702. if (clientid) {
  703. local_copy = clientid->getDuid();
  704. }
  705. Lease4Ptr lease(new Lease4(addr, &hwaddr->hwaddr_[0], hwaddr->hwaddr_.size(),
  706. &local_copy[0], local_copy.size(), subnet->getValid(),
  707. subnet->getT1(), subnet->getT2(), now,
  708. subnet->getID()));
  709. // Set FQDN specific lease parameters.
  710. lease->fqdn_fwd_ = fwd_dns_update;
  711. lease->fqdn_rev_ = rev_dns_update;
  712. lease->hostname_ = hostname;
  713. // Let's execute all callouts registered for lease4_select
  714. if (callout_handle &&
  715. HooksManager::getHooksManager().calloutsPresent(hook_index_lease4_select_)) {
  716. // Delete all previous arguments
  717. callout_handle->deleteAllArguments();
  718. // Pass necessary arguments
  719. // Subnet from which we do the allocation (That's as far as we can go
  720. // with using SubnetPtr to point to Subnet4 object. Users should not
  721. // be confused with dynamic_pointer_casts. They should get a concrete
  722. // pointer (Subnet4Ptr) pointing to a Subnet4 object.
  723. Subnet4Ptr subnet4 = boost::dynamic_pointer_cast<Subnet4>(subnet);
  724. callout_handle->setArgument("subnet4", subnet4);
  725. // Is this solicit (fake = true) or request (fake = false)
  726. callout_handle->setArgument("fake_allocation", fake_allocation);
  727. // Pass the intended lease as well
  728. callout_handle->setArgument("lease4", lease);
  729. // This is the first callout, so no need to clear any arguments
  730. HooksManager::callCallouts(hook_index_lease4_select_, *callout_handle);
  731. // Callouts decided to skip the action. This means that the lease is not
  732. // assigned, so the client will get NoAddrAvail as a result. The lease
  733. // won't be inserted into the database.
  734. if (callout_handle->getSkip()) {
  735. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_HOOKS, DHCPSRV_HOOK_LEASE4_SELECT_SKIP);
  736. return (Lease4Ptr());
  737. }
  738. // Let's use whatever callout returned. Hopefully it is the same lease
  739. // we handled to it.
  740. callout_handle->getArgument("lease4", lease);
  741. }
  742. if (!fake_allocation) {
  743. // That is a real (REQUEST) allocation
  744. bool status = LeaseMgrFactory::instance().addLease(lease);
  745. if (status) {
  746. return (lease);
  747. } else {
  748. // One of many failures with LeaseMgr (e.g. lost connection to the
  749. // database, database failed etc.). One notable case for that
  750. // is that we are working in multi-process mode and we lost a race
  751. // (some other process got that address first)
  752. return (Lease4Ptr());
  753. }
  754. } else {
  755. // That is only fake (DISCOVER) allocation
  756. // It is for OFFER only. We should not insert the lease into LeaseMgr,
  757. // but rather check that we could have inserted it.
  758. Lease4Ptr existing = LeaseMgrFactory::instance().getLease4(addr);
  759. if (!existing) {
  760. return (lease);
  761. } else {
  762. return (Lease4Ptr());
  763. }
  764. }
  765. }
  766. AllocEngine::~AllocEngine() {
  767. // no need to delete allocator. smart_ptr will do the trick for us
  768. }
  769. }; // end of isc::dhcp namespace
  770. }; // end of isc namespace