dhcp6_srv.cc 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  1. // Copyright (C) 2011-2012 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <config.h>
  15. #include <asiolink/io_address.h>
  16. #include <dhcp/dhcp6.h>
  17. #include <dhcp/duid.h>
  18. #include <dhcp/iface_mgr.h>
  19. #include <dhcp/libdhcp++.h>
  20. #include <dhcp/option6_addrlst.h>
  21. #include <dhcp/option6_ia.h>
  22. #include <dhcp/option6_iaaddr.h>
  23. #include <dhcp/option6_iaaddr.h>
  24. #include <dhcp/option6_int_array.h>
  25. #include <dhcp/option_custom.h>
  26. #include <dhcp/pkt6.h>
  27. #include <dhcp6/dhcp6_log.h>
  28. #include <dhcp6/dhcp6_srv.h>
  29. #include <dhcpsrv/cfgmgr.h>
  30. #include <dhcpsrv/lease_mgr.h>
  31. #include <dhcpsrv/lease_mgr_factory.h>
  32. #include <dhcpsrv/subnet.h>
  33. #include <exceptions/exceptions.h>
  34. #include <util/io_utilities.h>
  35. #include <util/range_utilities.h>
  36. #include <boost/foreach.hpp>
  37. #include <stdlib.h>
  38. #include <time.h>
  39. using namespace isc;
  40. using namespace isc::asiolink;
  41. using namespace isc::dhcp;
  42. using namespace isc::util;
  43. using namespace std;
  44. namespace isc {
  45. namespace dhcp {
  46. Dhcpv6Srv::Dhcpv6Srv(uint16_t port, const char* dbconfig)
  47. : alloc_engine_(), serverid_(), shutdown_(true) {
  48. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_START, DHCP6_OPEN_SOCKET).arg(port);
  49. // Initialize objects required for DHCP server operation.
  50. try {
  51. // Port 0 is used for testing purposes. It means that the server should
  52. // not open any sockets at all. Some tests, e.g. configuration parser,
  53. // require Dhcpv6Srv object, but they don't really need it to do
  54. // anything. This speed up and simplifies the tests.
  55. if (port > 0) {
  56. if (IfaceMgr::instance().countIfaces() == 0) {
  57. LOG_ERROR(dhcp6_logger, DHCP6_NO_INTERFACES);
  58. return;
  59. }
  60. IfaceMgr::instance().openSockets6(port);
  61. }
  62. setServerID();
  63. // Instantiate LeaseMgr
  64. LeaseMgrFactory::create(dbconfig);
  65. LOG_INFO(dhcp6_logger, DHCP6_DB_BACKEND_STARTED)
  66. .arg(LeaseMgrFactory::instance().getType())
  67. .arg(LeaseMgrFactory::instance().getName());
  68. // Instantiate allocation engine
  69. alloc_engine_.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE, 100));
  70. } catch (const std::exception &e) {
  71. LOG_ERROR(dhcp6_logger, DHCP6_SRV_CONSTRUCT_ERROR).arg(e.what());
  72. return;
  73. }
  74. // All done, so can proceed
  75. shutdown_ = false;
  76. }
  77. Dhcpv6Srv::~Dhcpv6Srv() {
  78. IfaceMgr::instance().closeSockets();
  79. LeaseMgrFactory::destroy();
  80. }
  81. void Dhcpv6Srv::shutdown() {
  82. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_SHUTDOWN_REQUEST);
  83. shutdown_ = true;
  84. }
  85. bool Dhcpv6Srv::run() {
  86. while (!shutdown_) {
  87. /// @todo: calculate actual timeout to the next event (e.g. lease
  88. /// expiration) once we have lease database. The idea here is that
  89. /// it is possible to do everything in a single process/thread.
  90. /// For now, we are just calling select for 1000 seconds. There
  91. /// were some issues reported on some systems when calling select()
  92. /// with too large values. Unfortunately, I don't recall the details.
  93. int timeout = 1000;
  94. // client's message and server's response
  95. Pkt6Ptr query;
  96. Pkt6Ptr rsp;
  97. try {
  98. query = IfaceMgr::instance().receive6(timeout);
  99. } catch (const std::exception& e) {
  100. LOG_ERROR(dhcp6_logger, DHCP6_PACKET_RECEIVE_FAIL).arg(e.what());
  101. }
  102. if (query) {
  103. if (!query->unpack()) {
  104. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL,
  105. DHCP6_PACKET_PARSE_FAIL);
  106. continue;
  107. }
  108. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_PACKET_RECEIVED)
  109. .arg(query->getName());
  110. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL_DATA, DHCP6_QUERY_DATA)
  111. .arg(static_cast<int>(query->getType()))
  112. .arg(query->getBuffer().getLength())
  113. .arg(query->toText());
  114. try {
  115. switch (query->getType()) {
  116. case DHCPV6_SOLICIT:
  117. rsp = processSolicit(query);
  118. break;
  119. case DHCPV6_REQUEST:
  120. rsp = processRequest(query);
  121. break;
  122. case DHCPV6_RENEW:
  123. rsp = processRenew(query);
  124. break;
  125. case DHCPV6_REBIND:
  126. rsp = processRebind(query);
  127. break;
  128. case DHCPV6_CONFIRM:
  129. rsp = processConfirm(query);
  130. break;
  131. case DHCPV6_RELEASE:
  132. rsp = processRelease(query);
  133. break;
  134. case DHCPV6_DECLINE:
  135. rsp = processDecline(query);
  136. break;
  137. case DHCPV6_INFORMATION_REQUEST:
  138. rsp = processInfRequest(query);
  139. break;
  140. default:
  141. // Only action is to output a message if debug is enabled,
  142. // and that will be covered by the debug statement before
  143. // the "switch" statement.
  144. ;
  145. }
  146. } catch (const RFCViolation& e) {
  147. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_REQUIRED_OPTIONS_CHECK_FAIL)
  148. .arg(query->getName())
  149. .arg(query->getRemoteAddr())
  150. .arg(e.what());
  151. }
  152. if (rsp) {
  153. rsp->setRemoteAddr(query->getRemoteAddr());
  154. rsp->setLocalAddr(query->getLocalAddr());
  155. rsp->setRemotePort(DHCP6_CLIENT_PORT);
  156. rsp->setLocalPort(DHCP6_SERVER_PORT);
  157. rsp->setIndex(query->getIndex());
  158. rsp->setIface(query->getIface());
  159. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL_DATA,
  160. DHCP6_RESPONSE_DATA)
  161. .arg(rsp->getType()).arg(rsp->toText());
  162. if (rsp->pack()) {
  163. try {
  164. IfaceMgr::instance().send(rsp);
  165. } catch (const std::exception& e) {
  166. LOG_ERROR(dhcp6_logger, DHCP6_PACKET_SEND_FAIL).arg(e.what());
  167. }
  168. } else {
  169. LOG_ERROR(dhcp6_logger, DHCP6_PACK_FAIL);
  170. }
  171. }
  172. }
  173. }
  174. return (true);
  175. }
  176. void Dhcpv6Srv::setServerID() {
  177. /// @todo: DUID should be generated once and then stored, rather
  178. /// than generated each time
  179. /// @todo: This code implements support for DUID-LLT (the recommended one).
  180. /// We should eventually add support for other DUID types: DUID-LL, DUID-EN
  181. /// and DUID-UUID
  182. const IfaceMgr::IfaceCollection& ifaces = IfaceMgr::instance().getIfaces();
  183. // Let's find suitable interface.
  184. for (IfaceMgr::IfaceCollection::const_iterator iface = ifaces.begin();
  185. iface != ifaces.end(); ++iface) {
  186. // All the following checks could be merged into one multi-condition
  187. // statement, but let's keep them separated as perhaps one day
  188. // we will grow knobs to selectively turn them on or off. Also,
  189. // this code is used only *once* during first start on a new machine
  190. // and then server-id is stored. (or at least it will be once
  191. // DUID storage is implemente
  192. // I wish there was a this_is_a_real_physical_interface flag...
  193. // MAC address should be at least 6 bytes. Although there is no such
  194. // requirement in any RFC, all decent physical interfaces (Ethernet,
  195. // WiFi, Infiniband, etc.) have 6 bytes long MAC address. We want to
  196. // base our DUID on real hardware address, rather than virtual
  197. // interface that pretends that underlying IP address is its MAC.
  198. if (iface->getMacLen() < MIN_MAC_LEN) {
  199. continue;
  200. }
  201. // Let's don't use loopback.
  202. if (iface->flag_loopback_) {
  203. continue;
  204. }
  205. // Let's skip downed interfaces. It is better to use working ones.
  206. if (!iface->flag_up_) {
  207. continue;
  208. }
  209. // Some interfaces (like lo on Linux) report 6-bytes long
  210. // MAC adress 00:00:00:00:00:00. Let's not use such weird interfaces
  211. // to generate DUID.
  212. if (isRangeZero(iface->getMac(), iface->getMac() + iface->getMacLen())) {
  213. continue;
  214. }
  215. // Ok, we have useful MAC. Let's generate DUID-LLT based on
  216. // it. See RFC3315, Section 9.2 for details.
  217. // DUID uses seconds since midnight of 01-01-2000, time() returns
  218. // seconds since 01-01-1970. DUID_TIME_EPOCH substution corrects that.
  219. time_t seconds = time(NULL);
  220. seconds -= DUID_TIME_EPOCH;
  221. OptionBuffer srvid(8 + iface->getMacLen());
  222. writeUint16(DUID::DUID_LLT, &srvid[0]);
  223. writeUint16(HWTYPE_ETHERNET, &srvid[2]);
  224. writeUint32(static_cast<uint32_t>(seconds), &srvid[4]);
  225. memcpy(&srvid[0] + 8, iface->getMac(), iface->getMacLen());
  226. serverid_ = OptionPtr(new Option(Option::V6, D6O_SERVERID,
  227. srvid.begin(), srvid.end()));
  228. return;
  229. }
  230. // If we reached here, there are no suitable interfaces found.
  231. // Either interface detection is not supported on this platform or
  232. // this is really weird box. Let's use DUID-EN instead.
  233. // See Section 9.3 of RFC3315 for details.
  234. OptionBuffer srvid(12);
  235. writeUint16(DUID::DUID_EN, &srvid[0]);
  236. writeUint32(ENTERPRISE_ID_ISC, &srvid[2]);
  237. // Length of the identifier is company specific. I hereby declare
  238. // ISC "standard" of 6 bytes long pseudo-random numbers.
  239. srandom(time(NULL));
  240. fillRandom(&srvid[6], &srvid[12]);
  241. serverid_ = OptionPtr(new Option(Option::V6, D6O_SERVERID,
  242. srvid.begin(), srvid.end()));
  243. }
  244. void Dhcpv6Srv::copyDefaultOptions(const Pkt6Ptr& question, Pkt6Ptr& answer) {
  245. // Add client-id.
  246. OptionPtr clientid = question->getOption(D6O_CLIENTID);
  247. if (clientid) {
  248. answer->addOption(clientid);
  249. }
  250. // TODO: Should throw if there is no client-id (except anonymous INF-REQUEST)
  251. }
  252. void Dhcpv6Srv::appendDefaultOptions(const Pkt6Ptr& question, Pkt6Ptr& answer) {
  253. // add server-id
  254. answer->addOption(getServerID());
  255. // Get the subnet object. It holds options to be sent to the client
  256. // that belongs to the particular subnet.
  257. Subnet6Ptr subnet = CfgMgr::instance().getSubnet6(question->getRemoteAddr());
  258. // Warn if subnet is not supported and quit.
  259. if (!subnet) {
  260. LOG_WARN(dhcp6_logger, DHCP6_NO_SUBNET_DEF_OPT)
  261. .arg(question->getRemoteAddr().toText());
  262. return;
  263. }
  264. }
  265. void Dhcpv6Srv::appendRequestedOptions(const Pkt6Ptr& question, Pkt6Ptr& answer) {
  266. // Get the subnet for a particular address.
  267. Subnet6Ptr subnet = CfgMgr::instance().getSubnet6(question->getRemoteAddr());
  268. if (!subnet) {
  269. LOG_WARN(dhcp6_logger, DHCP6_NO_SUBNET_REQ_OPT)
  270. .arg(question->getRemoteAddr().toText());
  271. return;
  272. }
  273. // Client requests some options using ORO option. Try to
  274. // get this option from client's message.
  275. boost::shared_ptr<Option6IntArray<uint16_t> > option_oro =
  276. boost::dynamic_pointer_cast<Option6IntArray<uint16_t> >(question->getOption(D6O_ORO));
  277. // Option ORO not found. Don't do anything then.
  278. if (!option_oro) {
  279. return;
  280. }
  281. // Get the list of options that client requested.
  282. const std::vector<uint16_t>& requested_opts = option_oro->getValues();
  283. // Get the list of options configured for a subnet.
  284. const Subnet::OptionContainer& options = subnet->getOptions();
  285. const Subnet::OptionContainerTypeIndex& idx = options.get<1>();
  286. // Try to match requested options with those configured for a subnet.
  287. // If match is found, append configured option to the answer message.
  288. BOOST_FOREACH(uint16_t opt, requested_opts) {
  289. const Subnet::OptionContainerTypeRange& range = idx.equal_range(opt);
  290. BOOST_FOREACH(Subnet::OptionDescriptor desc, range) {
  291. answer->addOption(desc.option);
  292. }
  293. }
  294. }
  295. OptionPtr Dhcpv6Srv::createStatusCode(uint16_t code, const std::string& text) {
  296. // @todo This function uses OptionCustom class to manage contents
  297. // of the data fields. Since this this option is frequently used
  298. // it may be good to implement dedicated class to avoid performance
  299. // impact.
  300. // Get the definition of the option holding status code.
  301. OptionDefinitionPtr status_code_def =
  302. LibDHCP::getOptionDef(Option::V6, D6O_STATUS_CODE);
  303. // This definition is assumed to be initialized in LibDHCP.
  304. assert(status_code_def);
  305. // As there is no dedicated class to represent Status Code
  306. // the OptionCustom class should be returned here.
  307. boost::shared_ptr<OptionCustom> option_status =
  308. boost::dynamic_pointer_cast<
  309. OptionCustom>(status_code_def->optionFactory(Option::V6, D6O_STATUS_CODE));
  310. assert(option_status);
  311. // Set status code to 'code' (0 - means data field #0).
  312. option_status->writeInteger(code, 0);
  313. // Set a message (1 - means data field #1).
  314. option_status->writeString(text, 1);
  315. return (option_status);
  316. }
  317. void Dhcpv6Srv::sanityCheck(const Pkt6Ptr& pkt, RequirementLevel clientid,
  318. RequirementLevel serverid) {
  319. Option::OptionCollection client_ids = pkt->getOptions(D6O_CLIENTID);
  320. switch (clientid) {
  321. case MANDATORY:
  322. if (client_ids.size() != 1) {
  323. isc_throw(RFCViolation, "Exactly 1 client-id option expected in "
  324. << pkt->getName() << ", but " << client_ids.size()
  325. << " received");
  326. }
  327. break;
  328. case OPTIONAL:
  329. if (client_ids.size() > 1) {
  330. isc_throw(RFCViolation, "Too many (" << client_ids.size()
  331. << ") client-id options received in " << pkt->getName());
  332. }
  333. break;
  334. case FORBIDDEN:
  335. // doesn't make sense - client-id is always allowed
  336. break;
  337. }
  338. Option::OptionCollection server_ids = pkt->getOptions(D6O_SERVERID);
  339. switch (serverid) {
  340. case FORBIDDEN:
  341. if (server_ids.size() > 0) {
  342. isc_throw(RFCViolation, "Exactly 1 server-id option expected, but "
  343. << server_ids.size() << " received in " << pkt->getName());
  344. }
  345. break;
  346. case MANDATORY:
  347. if (server_ids.size() != 1) {
  348. isc_throw(RFCViolation, "Invalid number of server-id options received ("
  349. << server_ids.size() << "), exactly 1 expected in message "
  350. << pkt->getName());
  351. }
  352. break;
  353. case OPTIONAL:
  354. if (server_ids.size() > 1) {
  355. isc_throw(RFCViolation, "Too many (" << server_ids.size()
  356. << ") server-id options received in " << pkt->getName());
  357. }
  358. }
  359. }
  360. Subnet6Ptr Dhcpv6Srv::selectSubnet(const Pkt6Ptr& question) {
  361. Subnet6Ptr subnet = CfgMgr::instance().getSubnet6(question->getRemoteAddr());
  362. return (subnet);
  363. }
  364. void Dhcpv6Srv::assignLeases(const Pkt6Ptr& question, Pkt6Ptr& answer) {
  365. // We need to allocate addresses for all IA_NA options in the client's
  366. // question (i.e. SOLICIT or REQUEST) message.
  367. // @todo add support for IA_TA
  368. // @todo add support for IA_PD
  369. // We need to select a subnet the client is connected in.
  370. Subnet6Ptr subnet = selectSubnet(question);
  371. if (!subnet) {
  372. // This particular client is out of luck today. We do not have
  373. // information about the subnet he is connected to. This likely means
  374. // misconfiguration of the server (or some relays). We will continue to
  375. // process this message, but our response will be almost useless: no
  376. // addresses or prefixes, no subnet specific configuration etc. The only
  377. // thing this client can get is some global information (like DNS
  378. // servers).
  379. // perhaps this should be logged on some higher level? This is most likely
  380. // configuration bug.
  381. LOG_ERROR(dhcp6_logger, DHCP6_SUBNET_SELECTION_FAILED);
  382. } else {
  383. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL_DATA, DHCP6_SUBNET_SELECTED)
  384. .arg(subnet->toText());
  385. }
  386. // @todo: We should implement Option6Duid some day, but we can do without it
  387. // just fine for now
  388. // Let's find client's DUID. Client is supposed to include its client-id
  389. // option almost all the time (the only exception is an anonymous inf-request,
  390. // but that is mostly a theoretical case). Our allocation engine needs DUID
  391. // and will refuse to allocate anything to anonymous clients.
  392. DuidPtr duid;
  393. OptionPtr opt_duid = question->getOption(D6O_CLIENTID);
  394. if (opt_duid) {
  395. duid = DuidPtr(new DUID(opt_duid->getData()));
  396. } else {
  397. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_CLIENTID_MISSING);
  398. // Let's drop the message. This client is not sane.
  399. isc_throw(RFCViolation, "Mandatory client-id is missing in received message");
  400. }
  401. // Now that we have all information about the client, let's iterate over all
  402. // received options and handle IA_NA options one by one and store our
  403. // responses in answer message (ADVERTISE or REPLY).
  404. //
  405. // @todo: expand this to cover IA_PD and IA_TA once we implement support for
  406. // prefix delegation and temporary addresses.
  407. for (Option::OptionCollection::iterator opt = question->options_.begin();
  408. opt != question->options_.end(); ++opt) {
  409. switch (opt->second->getType()) {
  410. case D6O_IA_NA: {
  411. OptionPtr answer_opt = assignIA_NA(subnet, duid, question,
  412. boost::dynamic_pointer_cast<Option6IA>(opt->second));
  413. if (answer_opt) {
  414. answer->addOption(answer_opt);
  415. }
  416. break;
  417. }
  418. default:
  419. break;
  420. }
  421. }
  422. }
  423. OptionPtr Dhcpv6Srv::assignIA_NA(const Subnet6Ptr& subnet, const DuidPtr& duid,
  424. Pkt6Ptr question, boost::shared_ptr<Option6IA> ia) {
  425. // If there is no subnet selected for handling this IA_NA, the only thing to do left is
  426. // to say that we are sorry, but the user won't get an address. As a convenience, we
  427. // use a different status text to indicate that (compare to the same status code,
  428. // but different wording below)
  429. if (!subnet) {
  430. // Create empty IA_NA option with IAID matching the request.
  431. // Note that we don't use OptionDefinition class to create this option.
  432. // This is because we prefer using a constructor of Option6IA that
  433. // initializes IAID. Otherwise we would have to use setIAID() after
  434. // creation of the option which has some performance implications.
  435. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_NA, ia->getIAID()));
  436. // Insert status code NoAddrsAvail.
  437. ia_rsp->addOption(createStatusCode(STATUS_NoAddrsAvail, "Sorry, no subnet available."));
  438. return (ia_rsp);
  439. }
  440. // Check if the client sent us a hint in his IA_NA. Clients may send an
  441. // address in their IA_NA options as a suggestion (e.g. the last address
  442. // they used before).
  443. boost::shared_ptr<Option6IAAddr> hintOpt = boost::dynamic_pointer_cast<Option6IAAddr>
  444. (ia->getOption(D6O_IAADDR));
  445. IOAddress hint("::");
  446. if (hintOpt) {
  447. hint = hintOpt->getAddress();
  448. }
  449. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_PROCESS_IA_NA_REQUEST)
  450. .arg(duid?duid->toText():"(no-duid)").arg(ia->getIAID())
  451. .arg(hintOpt?hint.toText():"(no hint)");
  452. // "Fake" allocation is processing of SOLICIT message. We pretend to do an
  453. // allocation, but we do not put the lease in the database. That is ok,
  454. // because we do not guarantee that the user will get that exact lease. If
  455. // the user selects this server to do actual allocation (i.e. sends REQUEST)
  456. // it should include this hint. That will help us during the actual lease
  457. // allocation.
  458. bool fake_allocation = false;
  459. if (question->getType() == DHCPV6_SOLICIT) {
  460. /// @todo: Check if we support rapid commit
  461. fake_allocation = true;
  462. }
  463. // Use allocation engine to pick a lease for this client. Allocation engine
  464. // will try to honour the hint, but it is just a hint - some other address
  465. // may be used instead. If fake_allocation is set to false, the lease will
  466. // be inserted into the LeaseMgr as well.
  467. Lease6Ptr lease = alloc_engine_->allocateAddress6(subnet, duid, ia->getIAID(),
  468. hint, fake_allocation);
  469. // Create IA_NA that we will put in the response.
  470. // Do not use OptionDefinition to create option's instance so
  471. // as we can initialize IAID using a constructor.
  472. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_NA, ia->getIAID()));
  473. if (lease) {
  474. // We have a lease! Let's wrap its content into IA_NA option
  475. // with IAADDR suboption.
  476. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, fake_allocation?
  477. DHCP6_LEASE_ADVERT:DHCP6_LEASE_ALLOC)
  478. .arg(lease->addr_.toText())
  479. .arg(duid?duid->toText():"(no-duid)")
  480. .arg(ia->getIAID());
  481. ia_rsp->setT1(subnet->getT1());
  482. ia_rsp->setT2(subnet->getT2());
  483. boost::shared_ptr<Option6IAAddr>
  484. addr(new Option6IAAddr(D6O_IAADDR,
  485. lease->addr_,
  486. lease->preferred_lft_,
  487. lease->valid_lft_));
  488. ia_rsp->addOption(addr);
  489. // It would be possible to insert status code=0(success) as well,
  490. // but this is considered waste of bandwidth as absence of status
  491. // code is considered a success.
  492. } else {
  493. // Allocation engine did not allocate a lease. The engine logged
  494. // cause of that failure. The only thing left is to insert
  495. // status code to pass the sad news to the client.
  496. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, fake_allocation?
  497. DHCP6_LEASE_ADVERT_FAIL:DHCP6_LEASE_ALLOC_FAIL)
  498. .arg(duid?duid->toText():"(no-duid)")
  499. .arg(ia->getIAID())
  500. .arg(subnet->toText());
  501. ia_rsp->addOption(createStatusCode(STATUS_NoAddrsAvail,
  502. "Sorry, no address could be allocated."));
  503. }
  504. return (ia_rsp);
  505. }
  506. OptionPtr Dhcpv6Srv::renewIA_NA(const Subnet6Ptr& subnet, const DuidPtr& duid,
  507. Pkt6Ptr question, boost::shared_ptr<Option6IA> ia) {
  508. Lease6Ptr lease = LeaseMgrFactory::instance().getLease6(*duid, ia->getIAID(),
  509. subnet->getID());
  510. if (!lease) {
  511. // client renewing a lease that we don't know about.
  512. // Create empty IA_NA option with IAID matching the request.
  513. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_NA, ia->getIAID()));
  514. // Insert status code NoAddrsAvail.
  515. ia_rsp->addOption(createStatusCode(STATUS_NoAddrsAvail,
  516. "Sorry, no known leases for this duid/iaid."));
  517. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_UNKNOWN_RENEW)
  518. .arg(duid->toText())
  519. .arg(ia->getIAID())
  520. .arg(subnet->toText());
  521. return (ia_rsp);
  522. }
  523. lease->preferred_lft_ = subnet->getPreferred();
  524. lease->valid_lft_ = subnet->getValid();
  525. lease->t1_ = subnet->getT1();
  526. lease->t2_ = subnet->getT2();
  527. lease->cltt_ = time(NULL);
  528. LeaseMgrFactory::instance().updateLease6(lease);
  529. // Create empty IA_NA option with IAID matching the request.
  530. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_NA, ia->getIAID()));
  531. ia_rsp->setT1(subnet->getT1());
  532. ia_rsp->setT2(subnet->getT2());
  533. boost::shared_ptr<Option6IAAddr> addr(new Option6IAAddr(D6O_IAADDR,
  534. lease->addr_, lease->preferred_lft_,
  535. lease->valid_lft_));
  536. ia_rsp->addOption(addr);
  537. return (ia_rsp);
  538. }
  539. void Dhcpv6Srv::renewLeases(const Pkt6Ptr& renew, Pkt6Ptr& reply) {
  540. // We need to renew addresses for all IA_NA options in the client's
  541. // RENEW message.
  542. // @todo add support for IA_TA
  543. // @todo add support for IA_PD
  544. // We need to select a subnet the client is connected in.
  545. Subnet6Ptr subnet = selectSubnet(renew);
  546. if (!subnet) {
  547. // This particular client is out of luck today. We do not have
  548. // information about the subnet he is connected to. This likely means
  549. // misconfiguration of the server (or some relays). We will continue to
  550. // process this message, but our response will be almost useless: no
  551. // addresses or prefixes, no subnet specific configuration etc. The only
  552. // thing this client can get is some global information (like DNS
  553. // servers).
  554. // perhaps this should be logged on some higher level? This is most likely
  555. // configuration bug.
  556. LOG_ERROR(dhcp6_logger, DHCP6_SUBNET_SELECTION_FAILED);
  557. } else {
  558. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL_DATA, DHCP6_SUBNET_SELECTED)
  559. .arg(subnet->toText());
  560. }
  561. // Let's find client's DUID. Client is supposed to include its client-id
  562. // option almost all the time (the only exception is an anonymous inf-request,
  563. // but that is mostly a theoretical case). Our allocation engine needs DUID
  564. // and will refuse to allocate anything to anonymous clients.
  565. OptionPtr opt_duid = renew->getOption(D6O_CLIENTID);
  566. if (!opt_duid) {
  567. // This should not happen. We have checked this before.
  568. reply->addOption(createStatusCode(STATUS_UnspecFail,
  569. "You did not include mandatory client-id"));
  570. return;
  571. }
  572. DuidPtr duid(new DUID(opt_duid->getData()));
  573. for (Option::OptionCollection::iterator opt = renew->options_.begin();
  574. opt != renew->options_.end(); ++opt) {
  575. switch (opt->second->getType()) {
  576. case D6O_IA_NA: {
  577. OptionPtr answer_opt = renewIA_NA(subnet, duid, renew,
  578. boost::dynamic_pointer_cast<Option6IA>(opt->second));
  579. if (answer_opt) {
  580. reply->addOption(answer_opt);
  581. }
  582. break;
  583. }
  584. default:
  585. break;
  586. }
  587. }
  588. }
  589. void Dhcpv6Srv::releaseLeases(const Pkt6Ptr& release, Pkt6Ptr& reply) {
  590. // We need to release addresses for all IA_NA options in the client's
  591. // RELEASE message.
  592. // @todo Add support for IA_TA
  593. // @todo Add support for IA_PD
  594. // @todo Consider supporting more than one address in a single IA_NA.
  595. // That was envisaged by RFC3315, but it never happened. The only
  596. // software that supports that is Dibbler, but its author seriously doubts
  597. // if anyone is really using it. Clients that want more than one address
  598. // just include more instances of IA_NA options.
  599. // Let's find client's DUID. Client is supposed to include its client-id
  600. // option almost all the time (the only exception is an anonymous inf-request,
  601. // but that is mostly a theoretical case). Our allocation engine needs DUID
  602. // and will refuse to allocate anything to anonymous clients.
  603. OptionPtr opt_duid = release->getOption(D6O_CLIENTID);
  604. if (!opt_duid) {
  605. // This should not happen. We have checked this before.
  606. reply->addOption(createStatusCode(STATUS_UnspecFail,
  607. "You did not include mandatory client-id"));
  608. return;
  609. }
  610. DuidPtr duid(new DUID(opt_duid->getData()));
  611. int general_status = STATUS_Success;
  612. for (Option::OptionCollection::iterator opt = release->options_.begin();
  613. opt != release->options_.end(); ++opt) {
  614. switch (opt->second->getType()) {
  615. case D6O_IA_NA: {
  616. OptionPtr answer_opt = releaseIA_NA(duid, release, general_status,
  617. boost::dynamic_pointer_cast<Option6IA>(opt->second));
  618. if (answer_opt) {
  619. reply->addOption(answer_opt);
  620. }
  621. break;
  622. }
  623. default:
  624. break;
  625. }
  626. }
  627. // To be pedantic, we should also include status code in the top-level
  628. // scope, not just in each IA_NA. See RFC3315, section 18.2.6.
  629. // This behavior will likely go away in RFC3315bis.
  630. reply->addOption(createStatusCode(general_status,
  631. "Summary status for all processed IA_NAs"));
  632. }
  633. OptionPtr Dhcpv6Srv::releaseIA_NA(const DuidPtr& duid, Pkt6Ptr question,
  634. int& general_status,
  635. boost::shared_ptr<Option6IA> ia) {
  636. // Release can be done in one of two ways:
  637. // Approach 1: extract address from client's IA_NA and see if it belongs
  638. // to this particular client.
  639. // Approach 2: find a subnet for this client, get a lease for
  640. // this subnet/duid/iaid and check if its content matches to what the
  641. // client is asking us to release.
  642. //
  643. // This method implements approach 1.
  644. // That's our response
  645. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_NA, ia->getIAID()));
  646. boost::shared_ptr<Option6IAAddr> release_addr = boost::dynamic_pointer_cast<Option6IAAddr>
  647. (ia->getOption(D6O_IAADDR));
  648. if (!release_addr) {
  649. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  650. "You did not include address in your RELEASE"));
  651. general_status = STATUS_NoBinding;
  652. return (ia_rsp);
  653. }
  654. Lease6Ptr lease = LeaseMgrFactory::instance().getLease6(release_addr->getAddress());
  655. if (!lease) {
  656. // client releasing a lease that we don't know about.
  657. // Insert status code NoAddrsAvail.
  658. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  659. "Sorry, no known leases for this duid/iaid, can't release."));
  660. general_status = STATUS_NoBinding;
  661. LOG_WARN(dhcp6_logger, DHCP6_UNKNOWN_RELEASE)
  662. .arg(duid->toText())
  663. .arg(ia->getIAID());
  664. return (ia_rsp);
  665. }
  666. if (!lease->duid_) {
  667. // Something is gravely wrong here. We do have a lease, but it does not
  668. // have mandatory DUID information attached. Someone was messing with our
  669. // database.
  670. LOG_ERROR(dhcp6_logger, DHCP6_DB_ERROR_LEASE6_WITHOUT_DUID)
  671. .arg(release_addr->getAddress().toText());
  672. general_status = STATUS_UnspecFail;
  673. ia_rsp->addOption(createStatusCode(STATUS_UnspecFail,
  674. "Database consistency check failed when trying to RELEASE"));
  675. return (ia_rsp);
  676. }
  677. if (*duid != *(lease->duid_)) {
  678. // Sorry, it's not your address. You can't release it.
  679. LOG_WARN(dhcp6_logger, DHCP6_RELEASE_FAIL_WRONG_DUID)
  680. .arg(release_addr->getAddress().toText())
  681. .arg(duid->toText())
  682. .arg(lease->duid_->toText());
  683. general_status = STATUS_NoBinding;
  684. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  685. "This address does not belong to you, you can't release it"));
  686. return (ia_rsp);
  687. }
  688. if (ia->getIAID() != lease->iaid_) {
  689. // This address belongs to this client, but to a different IA
  690. LOG_WARN(dhcp6_logger, DHCP6_RELEASE_FAIL_WRONG_IAID)
  691. .arg(release_addr->getAddress().toText())
  692. .arg(duid->toText())
  693. .arg(ia->getIAID())
  694. .arg(lease->iaid_);
  695. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  696. "This is your address, but you used wrong IAID"));
  697. general_status = STATUS_NoBinding;
  698. return (ia_rsp);
  699. }
  700. // It is not necessary if the address matches as we used getLease6(addr)
  701. // method that is supposed to return a proper lease.
  702. // Ok, we've passed all checks. Let's release this address.
  703. if (!LeaseMgrFactory::instance().deleteLease(lease->addr_)) {
  704. ia_rsp->addOption(createStatusCode(STATUS_UnspecFail,
  705. "Server failed to release a lease"));
  706. LOG_ERROR(dhcp6_logger, DHCP6_RELEASE_FAIL)
  707. .arg(lease->addr_.toText())
  708. .arg(duid->toText())
  709. .arg(lease->iaid_);
  710. general_status = STATUS_UnspecFail;
  711. return (ia_rsp);
  712. } else {
  713. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_RELEASE)
  714. .arg(lease->addr_.toText())
  715. .arg(duid->toText())
  716. .arg(lease->iaid_);
  717. ia_rsp->addOption(createStatusCode(STATUS_Success,
  718. "Lease released. Thank you, please come again."));
  719. return (ia_rsp);
  720. }
  721. }
  722. Pkt6Ptr Dhcpv6Srv::processSolicit(const Pkt6Ptr& solicit) {
  723. sanityCheck(solicit, MANDATORY, FORBIDDEN);
  724. Pkt6Ptr advertise(new Pkt6(DHCPV6_ADVERTISE, solicit->getTransid()));
  725. copyDefaultOptions(solicit, advertise);
  726. appendDefaultOptions(solicit, advertise);
  727. appendRequestedOptions(solicit, advertise);
  728. assignLeases(solicit, advertise);
  729. return (advertise);
  730. }
  731. Pkt6Ptr Dhcpv6Srv::processRequest(const Pkt6Ptr& request) {
  732. sanityCheck(request, MANDATORY, MANDATORY);
  733. Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, request->getTransid()));
  734. copyDefaultOptions(request, reply);
  735. appendDefaultOptions(request, reply);
  736. appendRequestedOptions(request, reply);
  737. assignLeases(request, reply);
  738. return (reply);
  739. }
  740. Pkt6Ptr Dhcpv6Srv::processRenew(const Pkt6Ptr& renew) {
  741. sanityCheck(renew, MANDATORY, MANDATORY);
  742. Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, renew->getTransid()));
  743. copyDefaultOptions(renew, reply);
  744. appendDefaultOptions(renew, reply);
  745. appendRequestedOptions(renew, reply);
  746. renewLeases(renew, reply);
  747. return reply;
  748. }
  749. Pkt6Ptr Dhcpv6Srv::processRebind(const Pkt6Ptr& rebind) {
  750. /// @todo: Implement this
  751. Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, rebind->getTransid()));
  752. return reply;
  753. }
  754. Pkt6Ptr Dhcpv6Srv::processConfirm(const Pkt6Ptr& confirm) {
  755. /// @todo: Implement this
  756. Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, confirm->getTransid()));
  757. return reply;
  758. }
  759. Pkt6Ptr Dhcpv6Srv::processRelease(const Pkt6Ptr& release) {
  760. sanityCheck(release, MANDATORY, MANDATORY);
  761. Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, release->getTransid()));
  762. copyDefaultOptions(release, reply);
  763. appendDefaultOptions(release, reply);
  764. releaseLeases(release, reply);
  765. return reply;
  766. }
  767. Pkt6Ptr Dhcpv6Srv::processDecline(const Pkt6Ptr& decline) {
  768. /// @todo: Implement this
  769. Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, decline->getTransid()));
  770. return reply;
  771. }
  772. Pkt6Ptr Dhcpv6Srv::processInfRequest(const Pkt6Ptr& infRequest) {
  773. /// @todo: Implement this
  774. Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, infRequest->getTransid()));
  775. return reply;
  776. }
  777. };
  778. };