dhcp6_srv.cc 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878
  1. // Copyright (C) 2011-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 <config.h>
  15. #include <asiolink/io_address.h>
  16. #include <dhcp_ddns/ncr_msg.h>
  17. #include <dhcp/dhcp6.h>
  18. #include <dhcp/duid.h>
  19. #include <dhcp/iface_mgr.h>
  20. #include <dhcp/libdhcp++.h>
  21. #include <dhcp/option6_addrlst.h>
  22. #include <dhcp/option6_client_fqdn.h>
  23. #include <dhcp/option6_ia.h>
  24. #include <dhcp/option6_iaaddr.h>
  25. #include <dhcp/option6_iaaddr.h>
  26. #include <dhcp/option_custom.h>
  27. #include <dhcp/option_int_array.h>
  28. #include <dhcp/pkt6.h>
  29. #include <dhcp6/dhcp6_log.h>
  30. #include <dhcp6/dhcp6_srv.h>
  31. #include <dhcpsrv/cfgmgr.h>
  32. #include <dhcpsrv/lease_mgr.h>
  33. #include <dhcpsrv/lease_mgr_factory.h>
  34. #include <dhcpsrv/subnet.h>
  35. #include <dhcpsrv/utils.h>
  36. #include <exceptions/exceptions.h>
  37. #include <util/io_utilities.h>
  38. #include <util/range_utilities.h>
  39. #include <util/encode/hex.h>
  40. #include <hooks/hooks_manager.h>
  41. #include <hooks/callout_handle.h>
  42. #include <boost/foreach.hpp>
  43. #include <boost/tokenizer.hpp>
  44. #include <boost/algorithm/string/erase.hpp>
  45. #include <stdlib.h>
  46. #include <time.h>
  47. #include <iomanip>
  48. #include <fstream>
  49. using namespace isc;
  50. using namespace isc::asiolink;
  51. using namespace isc::dhcp_ddns;
  52. using namespace isc::dhcp;
  53. using namespace isc::hooks;
  54. using namespace isc::util;
  55. using namespace std;
  56. namespace {
  57. /// Structure that holds registered hook indexes
  58. struct Dhcp6Hooks {
  59. int hook_index_buffer6_receive_;///< index for "buffer6_receive" hook point
  60. int hook_index_pkt6_receive_; ///< index for "pkt6_receive" hook point
  61. int hook_index_subnet6_select_; ///< index for "subnet6_select" hook point
  62. int hook_index_lease6_renew_; ///< index for "lease6_renew" hook point
  63. int hook_index_lease6_release_; ///< index for "lease6_release" hook point
  64. int hook_index_pkt6_send_; ///< index for "pkt6_send" hook point
  65. int hook_index_buffer6_send_; ///< index for "buffer6_send" hook point
  66. /// Constructor that registers hook points for DHCPv6 engine
  67. Dhcp6Hooks() {
  68. hook_index_buffer6_receive_= HooksManager::registerHook("buffer6_receive");
  69. hook_index_pkt6_receive_ = HooksManager::registerHook("pkt6_receive");
  70. hook_index_subnet6_select_ = HooksManager::registerHook("subnet6_select");
  71. hook_index_lease6_renew_ = HooksManager::registerHook("lease6_renew");
  72. hook_index_lease6_release_ = HooksManager::registerHook("lease6_release");
  73. hook_index_pkt6_send_ = HooksManager::registerHook("pkt6_send");
  74. hook_index_buffer6_send_ = HooksManager::registerHook("buffer6_send");
  75. }
  76. };
  77. // Declare a Hooks object. As this is outside any function or method, it
  78. // will be instantiated (and the constructor run) when the module is loaded.
  79. // As a result, the hook indexes will be defined before any method in this
  80. // module is called.
  81. Dhcp6Hooks Hooks;
  82. }; // anonymous namespace
  83. namespace isc {
  84. namespace dhcp {
  85. namespace {
  86. // The following constants describe server's behavior with respect to the
  87. // DHCPv6 Client FQDN Option sent by a client. They will be removed
  88. // when DDNS parameters for DHCPv6 are implemented with the ticket #3034.
  89. // Should server always include the FQDN option in its response, regardless
  90. // if it has been requested in ORO (Disabled).
  91. const bool FQDN_ALWAYS_INCLUDE = false;
  92. // Enable AAAA RR update delegation to the client (Disabled).
  93. const bool FQDN_ALLOW_CLIENT_UPDATE = false;
  94. // Globally enable updates (Enabled).
  95. const bool FQDN_ENABLE_UPDATE = true;
  96. // The partial name generated for the client if empty name has been
  97. // supplied.
  98. const char* FQDN_GENERATED_PARTIAL_NAME = "myhost";
  99. // Do update, even if client requested no updates with N flag (Disabled).
  100. const bool FQDN_OVERRIDE_NO_UPDATE = false;
  101. // Server performs an update when client requested delegation (Enabled).
  102. const bool FQDN_OVERRIDE_CLIENT_UPDATE = true;
  103. // The fully qualified domain-name suffix if partial name provided by
  104. // a client.
  105. const char* FQDN_PARTIAL_SUFFIX = "example.com";
  106. // Should server replace the domain-name supplied by the client (Disabled).
  107. const bool FQDN_REPLACE_CLIENT_NAME = false;
  108. }
  109. /// @brief file name of a server-id file
  110. ///
  111. /// Server must store its duid in persistent storage that must not change
  112. /// between restarts. This is name of the file that is created in dataDir
  113. /// (see isc::dhcp::CfgMgr::getDataDir()). It is a text file that uses
  114. /// double digit hex values separated by colons format, e.g.
  115. /// 01:ff:02:03:06:80:90:ab:cd:ef. Server will create it during first
  116. /// run and then use it afterwards.
  117. static const char* SERVER_DUID_FILE = "b10-dhcp6-serverid";
  118. Dhcpv6Srv::Dhcpv6Srv(uint16_t port)
  119. :alloc_engine_(), serverid_(), shutdown_(true), port_(port)
  120. {
  121. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_START, DHCP6_OPEN_SOCKET).arg(port);
  122. // Initialize objects required for DHCP server operation.
  123. try {
  124. // Port 0 is used for testing purposes. It means that the server should
  125. // not open any sockets at all. Some tests, e.g. configuration parser,
  126. // require Dhcpv6Srv object, but they don't really need it to do
  127. // anything. This speed up and simplifies the tests.
  128. if (port > 0) {
  129. if (IfaceMgr::instance().countIfaces() == 0) {
  130. LOG_ERROR(dhcp6_logger, DHCP6_NO_INTERFACES);
  131. return;
  132. }
  133. IfaceMgr::instance().openSockets6(port_);
  134. }
  135. string duid_file = CfgMgr::instance().getDataDir() + "/" + string(SERVER_DUID_FILE);
  136. if (loadServerID(duid_file)) {
  137. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_START, DHCP6_SERVERID_LOADED)
  138. .arg(duidToString(getServerID()))
  139. .arg(duid_file);
  140. } else {
  141. generateServerID();
  142. LOG_INFO(dhcp6_logger, DHCP6_SERVERID_GENERATED)
  143. .arg(duidToString(getServerID()))
  144. .arg(duid_file);
  145. if (!writeServerID(duid_file)) {
  146. LOG_WARN(dhcp6_logger, DHCP6_SERVERID_WRITE_FAIL)
  147. .arg(duid_file);
  148. }
  149. }
  150. // Instantiate allocation engine
  151. alloc_engine_.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE, 100));
  152. /// @todo call loadLibraries() when handling configuration changes
  153. } catch (const std::exception &e) {
  154. LOG_ERROR(dhcp6_logger, DHCP6_SRV_CONSTRUCT_ERROR).arg(e.what());
  155. return;
  156. }
  157. // All done, so can proceed
  158. shutdown_ = false;
  159. }
  160. Dhcpv6Srv::~Dhcpv6Srv() {
  161. IfaceMgr::instance().closeSockets();
  162. LeaseMgrFactory::destroy();
  163. }
  164. void Dhcpv6Srv::shutdown() {
  165. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_SHUTDOWN_REQUEST);
  166. shutdown_ = true;
  167. }
  168. Pkt6Ptr Dhcpv6Srv::receivePacket(int timeout) {
  169. return (IfaceMgr::instance().receive6(timeout));
  170. }
  171. void Dhcpv6Srv::sendPacket(const Pkt6Ptr& packet) {
  172. IfaceMgr::instance().send(packet);
  173. }
  174. bool Dhcpv6Srv::run() {
  175. while (!shutdown_) {
  176. /// @todo Calculate actual timeout to the next event (e.g. lease
  177. /// expiration) once we have lease database. The idea here is that
  178. /// it is possible to do everything in a single process/thread.
  179. /// For now, we are just calling select for 1000 seconds. There
  180. /// were some issues reported on some systems when calling select()
  181. /// with too large values. Unfortunately, I don't recall the details.
  182. //cppcheck-suppress variableScope This is temporary anyway
  183. const int timeout = 1000;
  184. // client's message and server's response
  185. Pkt6Ptr query;
  186. Pkt6Ptr rsp;
  187. try {
  188. query = receivePacket(timeout);
  189. } catch (const std::exception& e) {
  190. LOG_ERROR(dhcp6_logger, DHCP6_PACKET_RECEIVE_FAIL).arg(e.what());
  191. }
  192. // Timeout may be reached or signal received, which breaks select() with no packet received
  193. if (!query) {
  194. continue;
  195. }
  196. bool skip_unpack = false;
  197. // The packet has just been received so contains the uninterpreted wire
  198. // data; execute callouts registered for buffer6_receive.
  199. if (HooksManager::getHooksManager().calloutsPresent(Hooks.hook_index_buffer6_receive_)) {
  200. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  201. // Delete previously set arguments
  202. callout_handle->deleteAllArguments();
  203. // Pass incoming packet as argument
  204. callout_handle->setArgument("query6", query);
  205. // Call callouts
  206. HooksManager::callCallouts(Hooks.hook_index_buffer6_receive_, *callout_handle);
  207. // Callouts decided to skip the next processing step. The next
  208. // processing step would to parse the packet, so skip at this
  209. // stage means that callouts did the parsing already, so server
  210. // should skip parsing.
  211. if (callout_handle->getSkip()) {
  212. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_BUFFER_RCVD_SKIP);
  213. skip_unpack = true;
  214. }
  215. callout_handle->getArgument("query6", query);
  216. }
  217. // Unpack the packet information unless the buffer6_receive callouts
  218. // indicated they did it
  219. if (!skip_unpack) {
  220. if (!query->unpack()) {
  221. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL,
  222. DHCP6_PACKET_PARSE_FAIL);
  223. continue;
  224. }
  225. }
  226. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_PACKET_RECEIVED)
  227. .arg(query->getName());
  228. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL_DATA, DHCP6_QUERY_DATA)
  229. .arg(static_cast<int>(query->getType()))
  230. .arg(query->getBuffer().getLength())
  231. .arg(query->toText());
  232. // At this point the information in the packet has been unpacked into
  233. // the various packet fields and option objects has been cretated.
  234. // Execute callouts registered for packet6_receive.
  235. if (HooksManager::getHooksManager().calloutsPresent(Hooks.hook_index_pkt6_receive_)) {
  236. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  237. // Delete previously set arguments
  238. callout_handle->deleteAllArguments();
  239. // Pass incoming packet as argument
  240. callout_handle->setArgument("query6", query);
  241. // Call callouts
  242. HooksManager::callCallouts(Hooks.hook_index_pkt6_receive_, *callout_handle);
  243. // Callouts decided to skip the next processing step. The next
  244. // processing step would to process the packet, so skip at this
  245. // stage means drop.
  246. if (callout_handle->getSkip()) {
  247. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_PACKET_RCVD_SKIP);
  248. continue;
  249. }
  250. callout_handle->getArgument("query6", query);
  251. }
  252. try {
  253. NameChangeRequestPtr ncr;
  254. switch (query->getType()) {
  255. case DHCPV6_SOLICIT:
  256. rsp = processSolicit(query);
  257. break;
  258. case DHCPV6_REQUEST:
  259. rsp = processRequest(query);
  260. break;
  261. case DHCPV6_RENEW:
  262. rsp = processRenew(query);
  263. break;
  264. case DHCPV6_REBIND:
  265. rsp = processRebind(query);
  266. break;
  267. case DHCPV6_CONFIRM:
  268. rsp = processConfirm(query);
  269. break;
  270. case DHCPV6_RELEASE:
  271. rsp = processRelease(query);
  272. break;
  273. case DHCPV6_DECLINE:
  274. rsp = processDecline(query);
  275. break;
  276. case DHCPV6_INFORMATION_REQUEST:
  277. rsp = processInfRequest(query);
  278. break;
  279. default:
  280. // We received a packet type that we do not recognize.
  281. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_UNKNOWN_MSG_RECEIVED)
  282. .arg(static_cast<int>(query->getType()))
  283. .arg(query->getIface());
  284. // Only action is to output a message if debug is enabled,
  285. // and that will be covered by the debug statement before
  286. // the "switch" statement.
  287. ;
  288. }
  289. } catch (const RFCViolation& e) {
  290. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_REQUIRED_OPTIONS_CHECK_FAIL)
  291. .arg(query->getName())
  292. .arg(query->getRemoteAddr().toText())
  293. .arg(e.what());
  294. } catch (const isc::Exception& e) {
  295. // Catch-all exception (at least for ones based on the isc
  296. // Exception class, which covers more or less all that
  297. // are explicitly raised in the BIND 10 code). Just log
  298. // the problem and ignore the packet. (The problem is logged
  299. // as a debug message because debug is disabled by default -
  300. // it prevents a DDOS attack based on the sending of problem
  301. // packets.)
  302. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_PACKET_PROCESS_FAIL)
  303. .arg(query->getName())
  304. .arg(query->getRemoteAddr().toText())
  305. .arg(e.what());
  306. }
  307. if (rsp) {
  308. rsp->setRemoteAddr(query->getRemoteAddr());
  309. rsp->setLocalAddr(query->getLocalAddr());
  310. rsp->setRemotePort(DHCP6_CLIENT_PORT);
  311. rsp->setLocalPort(DHCP6_SERVER_PORT);
  312. rsp->setIndex(query->getIndex());
  313. rsp->setIface(query->getIface());
  314. // Specifies if server should do the packing
  315. bool skip_pack = false;
  316. // Server's reply packet now has all options and fields set.
  317. // Options are represented by individual objects, but the
  318. // output wire data has not been prepared yet.
  319. // Execute all callouts registered for packet6_send
  320. if (HooksManager::getHooksManager().calloutsPresent(Hooks.hook_index_pkt6_send_)) {
  321. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  322. // Delete all previous arguments
  323. callout_handle->deleteAllArguments();
  324. // Set our response
  325. callout_handle->setArgument("response6", rsp);
  326. // Call all installed callouts
  327. HooksManager::callCallouts(Hooks.hook_index_pkt6_send_, *callout_handle);
  328. // Callouts decided to skip the next processing step. The next
  329. // processing step would to pack the packet (create wire data).
  330. // That step will be skipped if any callout sets skip flag.
  331. // It essentially means that the callout already did packing,
  332. // so the server does not have to do it again.
  333. if (callout_handle->getSkip()) {
  334. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_PACKET_SEND_SKIP);
  335. skip_pack = true;
  336. }
  337. }
  338. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL_DATA,
  339. DHCP6_RESPONSE_DATA)
  340. .arg(static_cast<int>(rsp->getType())).arg(rsp->toText());
  341. if (!skip_pack) {
  342. try {
  343. rsp->pack();
  344. } catch (const std::exception& e) {
  345. LOG_ERROR(dhcp6_logger, DHCP6_PACK_FAIL)
  346. .arg(e.what());
  347. continue;
  348. }
  349. }
  350. try {
  351. // Now all fields and options are constructed into output wire buffer.
  352. // Option objects modification does not make sense anymore. Hooks
  353. // can only manipulate wire buffer at this stage.
  354. // Let's execute all callouts registered for buffer6_send
  355. if (HooksManager::getHooksManager().calloutsPresent(Hooks.hook_index_buffer6_send_)) {
  356. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  357. // Delete previously set arguments
  358. callout_handle->deleteAllArguments();
  359. // Pass incoming packet as argument
  360. callout_handle->setArgument("response6", rsp);
  361. // Call callouts
  362. HooksManager::callCallouts(Hooks.hook_index_buffer6_send_, *callout_handle);
  363. // Callouts decided to skip the next processing step. The next
  364. // processing step would to parse the packet, so skip at this
  365. // stage means drop.
  366. if (callout_handle->getSkip()) {
  367. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_BUFFER_SEND_SKIP);
  368. continue;
  369. }
  370. callout_handle->getArgument("response6", rsp);
  371. }
  372. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL_DATA,
  373. DHCP6_RESPONSE_DATA)
  374. .arg(static_cast<int>(rsp->getType())).arg(rsp->toText());
  375. sendPacket(rsp);
  376. } catch (const std::exception& e) {
  377. LOG_ERROR(dhcp6_logger, DHCP6_PACKET_SEND_FAIL)
  378. .arg(e.what());
  379. }
  380. // Send NameChangeRequests to the b10-dhcp_ddns module.
  381. sendNameChangeRequests();
  382. }
  383. }
  384. return (true);
  385. }
  386. bool Dhcpv6Srv::loadServerID(const std::string& file_name) {
  387. // load content of the file into a string
  388. fstream f(file_name.c_str(), ios::in);
  389. if (!f.is_open()) {
  390. return (false);
  391. }
  392. string hex_string;
  393. f >> hex_string;
  394. f.close();
  395. // remove any spaces
  396. boost::algorithm::erase_all(hex_string, " ");
  397. // now remove :
  398. /// @todo: We should check first if the format is sane.
  399. /// Otherwise 1:2:3:4 will be converted to 0x12, 0x34
  400. boost::algorithm::erase_all(hex_string, ":");
  401. std::vector<uint8_t> bin;
  402. // Decode the hex string and store it in bin (which happens
  403. // to be OptionBuffer format)
  404. isc::util::encode::decodeHex(hex_string, bin);
  405. // Now create server-id option
  406. serverid_.reset(new Option(Option::V6, D6O_SERVERID, bin));
  407. return (true);
  408. }
  409. std::string
  410. Dhcpv6Srv::duidToString(const OptionPtr& opt) {
  411. stringstream tmp;
  412. OptionBuffer data = opt->getData();
  413. bool colon = false;
  414. for (OptionBufferConstIter it = data.begin(); it != data.end(); ++it) {
  415. if (colon) {
  416. tmp << ":";
  417. }
  418. tmp << hex << setw(2) << setfill('0') << static_cast<uint16_t>(*it);
  419. if (!colon) {
  420. colon = true;
  421. }
  422. }
  423. return tmp.str();
  424. }
  425. bool
  426. Dhcpv6Srv::writeServerID(const std::string& file_name) {
  427. fstream f(file_name.c_str(), ios::out | ios::trunc);
  428. if (!f.good()) {
  429. return (false);
  430. }
  431. f << duidToString(getServerID());
  432. f.close();
  433. return (true);
  434. }
  435. void
  436. Dhcpv6Srv::generateServerID() {
  437. /// @todo: This code implements support for DUID-LLT (the recommended one).
  438. /// We should eventually add support for other DUID types: DUID-LL, DUID-EN
  439. /// and DUID-UUID
  440. const IfaceMgr::IfaceCollection& ifaces = IfaceMgr::instance().getIfaces();
  441. // Let's find suitable interface.
  442. for (IfaceMgr::IfaceCollection::const_iterator iface = ifaces.begin();
  443. iface != ifaces.end(); ++iface) {
  444. // All the following checks could be merged into one multi-condition
  445. // statement, but let's keep them separated as perhaps one day
  446. // we will grow knobs to selectively turn them on or off. Also,
  447. // this code is used only *once* during first start on a new machine
  448. // and then server-id is stored. (or at least it will be once
  449. // DUID storage is implemented)
  450. // I wish there was a this_is_a_real_physical_interface flag...
  451. // MAC address should be at least 6 bytes. Although there is no such
  452. // requirement in any RFC, all decent physical interfaces (Ethernet,
  453. // WiFi, Infiniband, etc.) have 6 bytes long MAC address. We want to
  454. // base our DUID on real hardware address, rather than virtual
  455. // interface that pretends that underlying IP address is its MAC.
  456. if (iface->getMacLen() < MIN_MAC_LEN) {
  457. continue;
  458. }
  459. // Let's don't use loopback.
  460. if (iface->flag_loopback_) {
  461. continue;
  462. }
  463. // Let's skip downed interfaces. It is better to use working ones.
  464. if (!iface->flag_up_) {
  465. continue;
  466. }
  467. // Some interfaces (like lo on Linux) report 6-bytes long
  468. // MAC address 00:00:00:00:00:00. Let's not use such weird interfaces
  469. // to generate DUID.
  470. if (isRangeZero(iface->getMac(), iface->getMac() + iface->getMacLen())) {
  471. continue;
  472. }
  473. // Ok, we have useful MAC. Let's generate DUID-LLT based on
  474. // it. See RFC3315, Section 9.2 for details.
  475. // DUID uses seconds since midnight of 01-01-2000, time() returns
  476. // seconds since 01-01-1970. DUID_TIME_EPOCH substution corrects that.
  477. time_t seconds = time(NULL);
  478. seconds -= DUID_TIME_EPOCH;
  479. OptionBuffer srvid(8 + iface->getMacLen());
  480. writeUint16(DUID::DUID_LLT, &srvid[0]);
  481. writeUint16(HWTYPE_ETHERNET, &srvid[2]);
  482. writeUint32(static_cast<uint32_t>(seconds), &srvid[4]);
  483. memcpy(&srvid[0] + 8, iface->getMac(), iface->getMacLen());
  484. serverid_ = OptionPtr(new Option(Option::V6, D6O_SERVERID,
  485. srvid.begin(), srvid.end()));
  486. return;
  487. }
  488. // If we reached here, there are no suitable interfaces found.
  489. // Either interface detection is not supported on this platform or
  490. // this is really weird box. Let's use DUID-EN instead.
  491. // See Section 9.3 of RFC3315 for details.
  492. OptionBuffer srvid(12);
  493. writeUint16(DUID::DUID_EN, &srvid[0]);
  494. writeUint32(ENTERPRISE_ID_ISC, &srvid[2]);
  495. // Length of the identifier is company specific. I hereby declare
  496. // ISC "standard" of 6 bytes long pseudo-random numbers.
  497. srandom(time(NULL));
  498. fillRandom(&srvid[6], &srvid[12]);
  499. serverid_ = OptionPtr(new Option(Option::V6, D6O_SERVERID,
  500. srvid.begin(), srvid.end()));
  501. }
  502. void
  503. Dhcpv6Srv::copyDefaultOptions(const Pkt6Ptr& question, Pkt6Ptr& answer) {
  504. // Add client-id.
  505. OptionPtr clientid = question->getOption(D6O_CLIENTID);
  506. if (clientid) {
  507. answer->addOption(clientid);
  508. }
  509. /// @todo: Should throw if there is no client-id (except anonymous INF-REQUEST)
  510. // If this is a relayed message, we need to copy relay information
  511. if (!question->relay_info_.empty()) {
  512. answer->copyRelayInfo(question);
  513. }
  514. }
  515. void
  516. Dhcpv6Srv::appendDefaultOptions(const Pkt6Ptr&, Pkt6Ptr& answer) {
  517. // add server-id
  518. answer->addOption(getServerID());
  519. }
  520. void
  521. Dhcpv6Srv::appendRequestedOptions(const Pkt6Ptr& question, Pkt6Ptr& answer) {
  522. // Get the configured subnet suitable for the incoming packet.
  523. Subnet6Ptr subnet = selectSubnet(question);
  524. // Leave if there is no subnet matching the incoming packet.
  525. // There is no need to log the error message here because
  526. // it will be logged in the assignLease() when it fails to
  527. // pick the suitable subnet. We don't want to duplicate
  528. // error messages in such case.
  529. if (!subnet) {
  530. return;
  531. }
  532. // Client requests some options using ORO option. Try to
  533. // get this option from client's message.
  534. boost::shared_ptr<OptionIntArray<uint16_t> > option_oro =
  535. boost::dynamic_pointer_cast<OptionIntArray<uint16_t> >(question->getOption(D6O_ORO));
  536. // Option ORO not found. Don't do anything then.
  537. if (!option_oro) {
  538. return;
  539. }
  540. // Get the list of options that client requested.
  541. const std::vector<uint16_t>& requested_opts = option_oro->getValues();
  542. BOOST_FOREACH(uint16_t opt, requested_opts) {
  543. Subnet::OptionDescriptor desc = subnet->getOptionDescriptor("dhcp6", opt);
  544. if (desc.option) {
  545. answer->addOption(desc.option);
  546. }
  547. }
  548. }
  549. OptionPtr
  550. Dhcpv6Srv::createStatusCode(uint16_t code, const std::string& text) {
  551. // @todo This function uses OptionCustom class to manage contents
  552. // of the data fields. Since this this option is frequently used
  553. // it may be good to implement dedicated class to avoid performance
  554. // impact.
  555. // Get the definition of the option holding status code.
  556. OptionDefinitionPtr status_code_def =
  557. LibDHCP::getOptionDef(Option::V6, D6O_STATUS_CODE);
  558. // This definition is assumed to be initialized in LibDHCP.
  559. assert(status_code_def);
  560. // As there is no dedicated class to represent Status Code
  561. // the OptionCustom class is used here instead.
  562. OptionCustomPtr option_status =
  563. OptionCustomPtr(new OptionCustom(*status_code_def, Option::V6));
  564. assert(option_status);
  565. // Set status code to 'code' (0 - means data field #0).
  566. option_status->writeInteger(code, 0);
  567. // Set a message (1 - means data field #1).
  568. option_status->writeString(text, 1);
  569. return (option_status);
  570. }
  571. void
  572. Dhcpv6Srv::sanityCheck(const Pkt6Ptr& pkt, RequirementLevel clientid,
  573. RequirementLevel serverid) {
  574. Option::OptionCollection client_ids = pkt->getOptions(D6O_CLIENTID);
  575. switch (clientid) {
  576. case MANDATORY:
  577. if (client_ids.size() != 1) {
  578. isc_throw(RFCViolation, "Exactly 1 client-id option expected in "
  579. << pkt->getName() << ", but " << client_ids.size()
  580. << " received");
  581. }
  582. break;
  583. case OPTIONAL:
  584. if (client_ids.size() > 1) {
  585. isc_throw(RFCViolation, "Too many (" << client_ids.size()
  586. << ") client-id options received in " << pkt->getName());
  587. }
  588. break;
  589. case FORBIDDEN:
  590. // doesn't make sense - client-id is always allowed
  591. break;
  592. }
  593. Option::OptionCollection server_ids = pkt->getOptions(D6O_SERVERID);
  594. switch (serverid) {
  595. case FORBIDDEN:
  596. if (!server_ids.empty()) {
  597. isc_throw(RFCViolation, "Server-id option was not expected, but "
  598. << server_ids.size() << " received in " << pkt->getName());
  599. }
  600. break;
  601. case MANDATORY:
  602. if (server_ids.size() != 1) {
  603. isc_throw(RFCViolation, "Invalid number of server-id options received ("
  604. << server_ids.size() << "), exactly 1 expected in message "
  605. << pkt->getName());
  606. }
  607. break;
  608. case OPTIONAL:
  609. if (server_ids.size() > 1) {
  610. isc_throw(RFCViolation, "Too many (" << server_ids.size()
  611. << ") server-id options received in " << pkt->getName());
  612. }
  613. }
  614. }
  615. Subnet6Ptr
  616. Dhcpv6Srv::selectSubnet(const Pkt6Ptr& question) {
  617. Subnet6Ptr subnet;
  618. if (question->relay_info_.empty()) {
  619. // This is a direct (non-relayed) message
  620. // Try to find a subnet if received packet from a directly connected client
  621. subnet = CfgMgr::instance().getSubnet6(question->getIface());
  622. if (!subnet) {
  623. // If no subnet was found, try to find it based on remote address
  624. subnet = CfgMgr::instance().getSubnet6(question->getRemoteAddr());
  625. }
  626. } else {
  627. // This is a relayed message
  628. OptionPtr interface_id = question->getAnyRelayOption(D6O_INTERFACE_ID,
  629. Pkt6::RELAY_GET_FIRST);
  630. if (interface_id) {
  631. subnet = CfgMgr::instance().getSubnet6(interface_id);
  632. }
  633. if (!subnet) {
  634. // If no interface-id was specified (or not configured on server), let's
  635. // try address matching
  636. IOAddress link_addr = question->relay_info_.back().linkaddr_;
  637. // if relay filled in link_addr field, then let's use it
  638. if (link_addr != IOAddress("::")) {
  639. subnet = CfgMgr::instance().getSubnet6(link_addr);
  640. }
  641. }
  642. }
  643. // Let's execute all callouts registered for subnet6_receive
  644. if (HooksManager::getHooksManager().calloutsPresent(Hooks.hook_index_subnet6_select_)) {
  645. CalloutHandlePtr callout_handle = getCalloutHandle(question);
  646. // We're reusing callout_handle from previous calls
  647. callout_handle->deleteAllArguments();
  648. // Set new arguments
  649. callout_handle->setArgument("query6", question);
  650. callout_handle->setArgument("subnet6", subnet);
  651. // We pass pointer to const collection for performance reasons.
  652. // Otherwise we would get a non-trivial performance penalty each
  653. // time subnet6_select is called.
  654. callout_handle->setArgument("subnet6collection", CfgMgr::instance().getSubnets6());
  655. // Call user (and server-side) callouts
  656. HooksManager::callCallouts(Hooks.hook_index_subnet6_select_, *callout_handle);
  657. // Callouts decided to skip this step. This means that no subnet will be
  658. // selected. Packet processing will continue, but it will be severly limited
  659. // (i.e. only global options will be assigned)
  660. if (callout_handle->getSkip()) {
  661. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_SUBNET6_SELECT_SKIP);
  662. return (Subnet6Ptr());
  663. }
  664. // Use whatever subnet was specified by the callout
  665. callout_handle->getArgument("subnet6", subnet);
  666. }
  667. return (subnet);
  668. }
  669. void
  670. Dhcpv6Srv::assignLeases(const Pkt6Ptr& question, Pkt6Ptr& answer,
  671. const Option6ClientFqdnPtr& fqdn) {
  672. // We need to allocate addresses for all IA_NA options in the client's
  673. // question (i.e. SOLICIT or REQUEST) message.
  674. // @todo add support for IA_TA
  675. // @todo add support for IA_PD
  676. // We need to select a subnet the client is connected in.
  677. Subnet6Ptr subnet = selectSubnet(question);
  678. if (!subnet) {
  679. // This particular client is out of luck today. We do not have
  680. // information about the subnet he is connected to. This likely means
  681. // misconfiguration of the server (or some relays). We will continue to
  682. // process this message, but our response will be almost useless: no
  683. // addresses or prefixes, no subnet specific configuration etc. The only
  684. // thing this client can get is some global information (like DNS
  685. // servers).
  686. LOG_WARN(dhcp6_logger, DHCP6_SUBNET_SELECTION_FAILED)
  687. .arg(question->getRemoteAddr().toText())
  688. .arg(question->getName());
  689. } else {
  690. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL_DATA, DHCP6_SUBNET_SELECTED)
  691. .arg(subnet->toText());
  692. }
  693. // @todo: We should implement Option6Duid some day, but we can do without it
  694. // just fine for now
  695. // Let's find client's DUID. Client is supposed to include its client-id
  696. // option almost all the time (the only exception is an anonymous inf-request,
  697. // but that is mostly a theoretical case). Our allocation engine needs DUID
  698. // and will refuse to allocate anything to anonymous clients.
  699. DuidPtr duid;
  700. OptionPtr opt_duid = question->getOption(D6O_CLIENTID);
  701. if (opt_duid) {
  702. duid = DuidPtr(new DUID(opt_duid->getData()));
  703. } else {
  704. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_CLIENTID_MISSING);
  705. // Let's drop the message. This client is not sane.
  706. isc_throw(RFCViolation, "Mandatory client-id is missing in received message");
  707. }
  708. // Now that we have all information about the client, let's iterate over all
  709. // received options and handle IA_NA options one by one and store our
  710. // responses in answer message (ADVERTISE or REPLY).
  711. //
  712. // @todo: expand this to cover IA_PD and IA_TA once we implement support for
  713. // prefix delegation and temporary addresses.
  714. for (Option::OptionCollection::iterator opt = question->options_.begin();
  715. opt != question->options_.end(); ++opt) {
  716. switch (opt->second->getType()) {
  717. case D6O_IA_NA: {
  718. OptionPtr answer_opt = assignIA_NA(subnet, duid, question,
  719. boost::dynamic_pointer_cast<
  720. Option6IA>(opt->second),
  721. fqdn);
  722. if (answer_opt) {
  723. answer->addOption(answer_opt);
  724. }
  725. break;
  726. }
  727. default:
  728. break;
  729. }
  730. }
  731. }
  732. Option6ClientFqdnPtr
  733. Dhcpv6Srv::processClientFqdn(const Pkt6Ptr& question) {
  734. // Get Client FQDN Option from the client's message. If this option hasn't
  735. // been included, do nothing.
  736. Option6ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<
  737. Option6ClientFqdn>(question->getOption(D6O_CLIENT_FQDN));
  738. if (!fqdn) {
  739. return (fqdn);
  740. }
  741. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL,
  742. DHCP6_DDNS_RECEIVE_FQDN).arg(fqdn->toText());
  743. // Prepare the FQDN option which will be included in the response to
  744. // the client.
  745. Option6ClientFqdnPtr fqdn_resp(new Option6ClientFqdn(*fqdn));
  746. // RFC 4704, section 6. - all flags set to 0.
  747. fqdn_resp->resetFlags();
  748. // Conditions when N flag has to be set to indicate that server will not
  749. // perform DNS updates:
  750. // 1. Updates are globally disabled,
  751. // 2. Client requested no update and server respects it,
  752. // 3. Client requested that the AAAA update is delegated to the client but
  753. // server neither respects delegation of updates nor it is configured
  754. // to send update on its own when client requested delegation.
  755. if (!FQDN_ENABLE_UPDATE ||
  756. (fqdn->getFlag(Option6ClientFqdn::FLAG_N) &&
  757. !FQDN_OVERRIDE_NO_UPDATE) ||
  758. (!fqdn->getFlag(Option6ClientFqdn::FLAG_S) &&
  759. !FQDN_ALLOW_CLIENT_UPDATE && !FQDN_OVERRIDE_CLIENT_UPDATE)) {
  760. fqdn_resp->setFlag(Option6ClientFqdn::FLAG_N, true);
  761. // Conditions when S flag is set to indicate that server will perform
  762. // DNS update on its own:
  763. // 1. Client requested that server performs DNS update and DNS updates are
  764. // globally enabled
  765. // 2. Client requested that server delegates AAAA update to the client but
  766. // server doesn't respect delegation and it is configured to perform
  767. // an update on its own when client requested delegation.
  768. } else if (fqdn->getFlag(Option6ClientFqdn::FLAG_S) ||
  769. (!fqdn->getFlag(Option6ClientFqdn::FLAG_S) &&
  770. !FQDN_ALLOW_CLIENT_UPDATE && FQDN_OVERRIDE_CLIENT_UPDATE)) {
  771. fqdn_resp->setFlag(Option6ClientFqdn::FLAG_S, true);
  772. }
  773. // Server MUST set the O flag if it has overridden the client's setting
  774. // of S flag.
  775. if (fqdn->getFlag(Option6ClientFqdn::FLAG_S) !=
  776. fqdn_resp->getFlag(Option6ClientFqdn::FLAG_S)) {
  777. fqdn_resp->setFlag(Option6ClientFqdn::FLAG_O, true);
  778. }
  779. // If client supplied partial or empty domain-name, server should
  780. // generate one.
  781. if (fqdn->getDomainNameType() == Option6ClientFqdn::PARTIAL) {
  782. std::ostringstream name;
  783. if (fqdn->getDomainName().empty()) {
  784. name << FQDN_GENERATED_PARTIAL_NAME;
  785. } else {
  786. name << fqdn->getDomainName();
  787. }
  788. name << "." << FQDN_PARTIAL_SUFFIX;
  789. fqdn_resp->setDomainName(name.str(), Option6ClientFqdn::FULL);
  790. // Server may be configured to replace a name supplied by a client,
  791. // even if client supplied fully qualified domain-name.
  792. } else if (FQDN_REPLACE_CLIENT_NAME) {
  793. std::ostringstream name;
  794. name << FQDN_GENERATED_PARTIAL_NAME << "." << FQDN_PARTIAL_SUFFIX;
  795. fqdn_resp->setDomainName(name.str(), Option6ClientFqdn::FULL);
  796. }
  797. // Return the FQDN option which can be included in the server's response.
  798. // Note that it doesn't have to be included, if client didn't request
  799. // it using ORO and server is not configured to always include it.
  800. return (fqdn_resp);
  801. }
  802. void
  803. Dhcpv6Srv::appendClientFqdn(const Pkt6Ptr& question,
  804. Pkt6Ptr& answer,
  805. const Option6ClientFqdnPtr& fqdn) {
  806. // If FQDN is NULL, it means that client did not request DNS Update, plus
  807. // server doesn't force updates.
  808. if (fqdn) {
  809. return;
  810. }
  811. // Server sends back the FQDN option to the client if client has requested
  812. // it using Option Request Option. However, server may be configured to
  813. // send the FQDN option in its response, regardless whether client requested
  814. // it or not.
  815. bool include_fqdn = FQDN_ALWAYS_INCLUDE;
  816. if (!include_fqdn) {
  817. OptionUint16ArrayPtr oro = boost::dynamic_pointer_cast<
  818. OptionUint16Array>(question->getOption(D6O_ORO));
  819. if (oro) {
  820. const std::vector<uint16_t>& values = oro->getValues();
  821. for (int i = 0; i < values.size(); ++i) {
  822. if (values[i] == D6O_CLIENT_FQDN) {
  823. include_fqdn = true;
  824. }
  825. }
  826. }
  827. }
  828. if (include_fqdn) {
  829. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL,
  830. DHCP6_DDNS_SEND_FQDN).arg(fqdn->toText());
  831. answer->addOption(fqdn);
  832. }
  833. }
  834. void
  835. Dhcpv6Srv::createNameChangeRequests(const Pkt6Ptr& answer,
  836. const Option6ClientFqdnPtr& opt_fqdn) {
  837. // It is likely that client haven't included the FQDN option in the message
  838. // and server is not configured to always update DNS. In such cases,
  839. // FQDN option will be NULL. This is valid state, so we simply return.
  840. if (!opt_fqdn) {
  841. return;
  842. }
  843. // The response message instance is always required. For instance it
  844. // holds the Client Identifier. It is a programming error if supplied
  845. // message is NULL.
  846. if (!answer) {
  847. isc_throw(isc::Unexpected, "an instance of the object"
  848. << " encapsulating server's message must not be"
  849. << " NULL when creating DNS NameChangeRequest");
  850. }
  851. // Get the Client Id. It is mandatory and a function creating a response
  852. // would have thrown an exception if it was missing. Thus throwning
  853. // Unexpected if it is missing as it is a programming error.
  854. OptionPtr opt_duid = answer->getOption(D6O_CLIENTID);
  855. if (!opt_duid) {
  856. isc_throw(isc::Unexpected,
  857. "client identifier is required when creating a new"
  858. " DNS NameChangeRequest");
  859. }
  860. DuidPtr duid = DuidPtr(new DUID(opt_duid->getData()));
  861. // Get the FQDN in the on-wire format. It will be needed to compute
  862. // DHCID.
  863. OutputBuffer name_buf(1);
  864. opt_fqdn->packDomainName(name_buf);
  865. const uint8_t* name_data = static_cast<const uint8_t*>(name_buf.getData());
  866. // @todo currently D2Dhcid accepts a vector holding FQDN.
  867. // However, it will be faster if we used a pointer name_data.
  868. std::vector<uint8_t> buf_vec(name_data, name_data + name_buf.getLength());
  869. // Compute DHCID from Client Identifier and FQDN.
  870. isc::dhcp_ddns::D2Dhcid dhcid(*duid, buf_vec);
  871. // Get all IAs from the answer. For each IA, holding an address we will
  872. // create a corresponding NameChangeRequest.
  873. Option::OptionCollection answer_ias = answer->getOptions(D6O_IA_NA);
  874. for (Option::OptionCollection::const_iterator answer_ia =
  875. answer_ias.begin(); answer_ia != answer_ias.end(); ++answer_ia) {
  876. Option6IAAddrPtr iaaddr = boost::static_pointer_cast<
  877. Option6IAAddr>(answer_ia->second->getOption(D6O_IAADDR));
  878. // We need an address to create a name-to-address mapping.
  879. // If address is missing for any reason, go to the next IA.
  880. if (!iaaddr) {
  881. continue;
  882. }
  883. // Create new NameChangeRequest. Use the domain name from the FQDN.
  884. // This is an FQDN included in the response to the client, so it
  885. // holds a fully qualified domain-name already (not partial).
  886. // Get the IP address from the lease. Also, use the S flag to determine
  887. // if forward change should be performed. This flag will always be
  888. // set if server has taken responsibility for the forward update.
  889. NameChangeRequest ncr(isc::dhcp_ddns::CHG_ADD,
  890. opt_fqdn->getFlag(Option6ClientFqdn::FLAG_S),
  891. true, opt_fqdn->getDomainName(),
  892. iaaddr->getAddress().toText(),
  893. dhcid, 0, iaaddr->getValid());
  894. // Add the request to the queue. This queue will be read elsewhere in
  895. // the code and all requests from this queue will be sent to the
  896. // D2 module.
  897. name_change_reqs_.push(ncr);
  898. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL,
  899. DHCP6_DDNS_CREATE_ADD_NAME_CHANGE_REQUEST).arg(ncr.toText());
  900. }
  901. }
  902. void
  903. Dhcpv6Srv::createRemovalNameChangeRequest(const Lease6Ptr& lease) {
  904. // If we haven't performed a DNS Update when lease was acquired,
  905. // there is nothing to do here.
  906. if (!lease->fqdn_fwd_ && !lease->fqdn_rev_) {
  907. return;
  908. }
  909. // When lease was added into a database the host name should have
  910. // been added. The hostname can be empty if someone messed up in the
  911. // lease data base and removed the hostname.
  912. if (lease->hostname_.empty()) {
  913. LOG_ERROR(dhcp6_logger, DHCP6_DDNS_REMOVE_EMPTY_HOSTNAME)
  914. .arg(lease->addr_.toText());
  915. return;
  916. }
  917. // If hostname is non-empty, try to convert it to wire format so as
  918. // DHCID can be computed from it. This may throw an exception if hostname
  919. // has invalid format. Again, this should be only possible in case of
  920. // manual intervention in the database.
  921. // The DHCID computation is further in this function.
  922. std::vector<uint8_t> hostname_wire;
  923. try {
  924. OptionDataTypeUtil::writeFqdn(lease->hostname_, hostname_wire);
  925. } catch (const Exception& ex) {
  926. LOG_ERROR(dhcp6_logger, DHCP6_DDNS_REMOVE_INVALID_HOSTNAME);
  927. return;
  928. }
  929. // DUID must have been checked already by the caller of this function.
  930. // Let's be on the safe side and make sure it is non-NULL and throw
  931. // an exception if it is NULL.
  932. if (!lease->duid_) {
  933. isc_throw(isc::Unexpected, "DUID must be set when creating"
  934. << " NameChangeRequest for DNS records removal for "
  935. << lease->addr_.toText());
  936. }
  937. isc::dhcp_ddns::D2Dhcid dhcid(*lease->duid_, hostname_wire);
  938. // Create a NameChangeRequest to remove the entry.
  939. NameChangeRequest ncr(isc::dhcp_ddns::CHG_REMOVE,
  940. lease->fqdn_fwd_, lease->fqdn_rev_,
  941. lease->hostname_,
  942. lease->addr_.toText(),
  943. dhcid, 0, lease->valid_lft_);
  944. name_change_reqs_.push(ncr);
  945. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL,
  946. DHCP6_DDNS_CREATE_REMOVE_NAME_CHANGE_REQUEST).arg(ncr.toText());
  947. }
  948. void
  949. Dhcpv6Srv::sendNameChangeRequests() {
  950. while (!name_change_reqs_.empty()) {
  951. // @todo Once next NameChangeRequest is picked from the queue
  952. // we should send it to the bind10-dhcp_ddns module. Currently we
  953. // just drop it.
  954. name_change_reqs_.pop();
  955. }
  956. }
  957. OptionPtr
  958. Dhcpv6Srv::assignIA_NA(const Subnet6Ptr& subnet, const DuidPtr& duid,
  959. const Pkt6Ptr& query, boost::shared_ptr<Option6IA> ia,
  960. const Option6ClientFqdnPtr& fqdn) {
  961. // If there is no subnet selected for handling this IA_NA, the only thing to do left is
  962. // to say that we are sorry, but the user won't get an address. As a convenience, we
  963. // use a different status text to indicate that (compare to the same status code,
  964. // but different wording below)
  965. if (!subnet) {
  966. // Create empty IA_NA option with IAID matching the request.
  967. // Note that we don't use OptionDefinition class to create this option.
  968. // This is because we prefer using a constructor of Option6IA that
  969. // initializes IAID. Otherwise we would have to use setIAID() after
  970. // creation of the option which has some performance implications.
  971. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_NA, ia->getIAID()));
  972. // Insert status code NoAddrsAvail.
  973. ia_rsp->addOption(createStatusCode(STATUS_NoAddrsAvail, "Sorry, no subnet available."));
  974. return (ia_rsp);
  975. }
  976. // Check if the client sent us a hint in his IA_NA. Clients may send an
  977. // address in their IA_NA options as a suggestion (e.g. the last address
  978. // they used before).
  979. boost::shared_ptr<Option6IAAddr> hintOpt = boost::dynamic_pointer_cast<Option6IAAddr>
  980. (ia->getOption(D6O_IAADDR));
  981. IOAddress hint("::");
  982. if (hintOpt) {
  983. hint = hintOpt->getAddress();
  984. }
  985. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_PROCESS_IA_NA_REQUEST)
  986. .arg(duid?duid->toText():"(no-duid)").arg(ia->getIAID())
  987. .arg(hintOpt?hint.toText():"(no hint)");
  988. // "Fake" allocation is processing of SOLICIT message. We pretend to do an
  989. // allocation, but we do not put the lease in the database. That is ok,
  990. // because we do not guarantee that the user will get that exact lease. If
  991. // the user selects this server to do actual allocation (i.e. sends REQUEST)
  992. // it should include this hint. That will help us during the actual lease
  993. // allocation.
  994. bool fake_allocation = false;
  995. if (query->getType() == DHCPV6_SOLICIT) {
  996. /// @todo: Check if we support rapid commit
  997. fake_allocation = true;
  998. }
  999. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  1000. // At this point, we have to make make some decisions with respect to the
  1001. // FQDN option that we have generated as a result of receiving client's
  1002. // FQDN. In particular, we have to get to know if the DNS update will be
  1003. // performed or not. It is possible that option is NULL, which is valid
  1004. // condition if client didn't request DNS updates and server didn't force
  1005. // the update.
  1006. bool do_fwd = false;
  1007. bool do_rev = false;
  1008. if (fqdn) {
  1009. // Flag S must not coexist with flag N being set to 1, so if S=1
  1010. // server takes responsibility for both reverse and forward updates.
  1011. // Otherwise, we have to check N.
  1012. if (fqdn->getFlag(Option6ClientFqdn::FLAG_S)) {
  1013. do_fwd = true;
  1014. do_rev = true;
  1015. } else if (!fqdn->getFlag(Option6ClientFqdn::FLAG_N)) {
  1016. do_rev = true;
  1017. }
  1018. }
  1019. // Set hostname only in case any of the updates is being performed.
  1020. std::string hostname;
  1021. if (do_fwd || do_rev) {
  1022. hostname = fqdn->getDomainName();
  1023. }
  1024. // Use allocation engine to pick a lease for this client. Allocation engine
  1025. // will try to honour the hint, but it is just a hint - some other address
  1026. // may be used instead. If fake_allocation is set to false, the lease will
  1027. // be inserted into the LeaseMgr as well.
  1028. Lease6Ptr lease = alloc_engine_->allocateAddress6(subnet, duid,
  1029. ia->getIAID(),
  1030. hint,
  1031. do_fwd, do_rev,
  1032. hostname,
  1033. fake_allocation,
  1034. callout_handle);
  1035. // Create IA_NA that we will put in the response.
  1036. // Do not use OptionDefinition to create option's instance so
  1037. // as we can initialize IAID using a constructor.
  1038. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_NA, ia->getIAID()));
  1039. if (lease) {
  1040. // We have a lease! Let's wrap its content into IA_NA option
  1041. // with IAADDR suboption.
  1042. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, fake_allocation?
  1043. DHCP6_LEASE_ADVERT:DHCP6_LEASE_ALLOC)
  1044. .arg(lease->addr_.toText())
  1045. .arg(duid?duid->toText():"(no-duid)")
  1046. .arg(ia->getIAID());
  1047. ia_rsp->setT1(subnet->getT1());
  1048. ia_rsp->setT2(subnet->getT2());
  1049. boost::shared_ptr<Option6IAAddr>
  1050. addr(new Option6IAAddr(D6O_IAADDR,
  1051. lease->addr_,
  1052. lease->preferred_lft_,
  1053. lease->valid_lft_));
  1054. ia_rsp->addOption(addr);
  1055. // It would be possible to insert status code=0(success) as well,
  1056. // but this is considered waste of bandwidth as absence of status
  1057. // code is considered a success.
  1058. // Allocation engine may have returned an existing lease. If so, we
  1059. // have to check that the FQDN settings we provided are the same
  1060. // that were set. If they aren't, we will have to remove existing
  1061. // DNS records and update the lease with the new settings.
  1062. if ((lease->hostname_ != hostname) || (lease->fqdn_fwd_ != do_fwd) ||
  1063. (lease->fqdn_rev_ != do_rev)) {
  1064. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL,
  1065. DHCP6_DDNS_LEASE_ASSIGN_FQDN_CHANGE)
  1066. .arg(lease->toText())
  1067. .arg(hostname)
  1068. .arg(do_rev ? "true" : "false")
  1069. .arg(do_fwd ? "true" : "false");
  1070. // Schedule removal of the existing lease.
  1071. createRemovalNameChangeRequest(lease);
  1072. // Set the new lease properties and update.
  1073. lease->hostname_ = hostname;
  1074. lease->fqdn_fwd_ = do_fwd;
  1075. lease->fqdn_rev_ = do_rev;
  1076. LeaseMgrFactory::instance().updateLease6(lease);
  1077. }
  1078. } else {
  1079. // Allocation engine did not allocate a lease. The engine logged
  1080. // cause of that failure. The only thing left is to insert
  1081. // status code to pass the sad news to the client.
  1082. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, fake_allocation ?
  1083. DHCP6_LEASE_ADVERT_FAIL : DHCP6_LEASE_ALLOC_FAIL)
  1084. .arg(duid?duid->toText():"(no-duid)")
  1085. .arg(ia->getIAID());
  1086. ia_rsp->addOption(createStatusCode(STATUS_NoAddrsAvail,
  1087. "Sorry, no address could be allocated."));
  1088. }
  1089. return (ia_rsp);
  1090. }
  1091. OptionPtr
  1092. Dhcpv6Srv::renewIA_NA(const Subnet6Ptr& subnet, const DuidPtr& duid,
  1093. const Pkt6Ptr& query, boost::shared_ptr<Option6IA> ia,
  1094. const Option6ClientFqdnPtr& fqdn) {
  1095. if (!subnet) {
  1096. // There's no subnet select for this client. There's nothing to renew.
  1097. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_NA, ia->getIAID()));
  1098. // Insert status code NoAddrsAvail.
  1099. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1100. "Sorry, no known leases for this duid/iaid."));
  1101. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_RENEW_UNKNOWN_SUBNET)
  1102. .arg(duid->toText())
  1103. .arg(ia->getIAID());
  1104. return (ia_rsp);
  1105. }
  1106. Lease6Ptr lease = LeaseMgrFactory::instance().getLease6(*duid, ia->getIAID(),
  1107. subnet->getID());
  1108. if (!lease) {
  1109. // client renewing a lease that we don't know about.
  1110. // Create empty IA_NA option with IAID matching the request.
  1111. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_NA, ia->getIAID()));
  1112. // Insert status code NoAddrsAvail.
  1113. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1114. "Sorry, no known leases for this duid/iaid."));
  1115. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_UNKNOWN_RENEW)
  1116. .arg(duid->toText())
  1117. .arg(ia->getIAID())
  1118. .arg(subnet->toText());
  1119. return (ia_rsp);
  1120. }
  1121. // Keep the old data in case the callout tells us to skip update
  1122. Lease6 old_data = *lease;
  1123. // At this point, we have to make make some decisions with respect to the
  1124. // FQDN option that we have generated as a result of receiving client's
  1125. // FQDN. In particular, we have to get to know if the DNS update will be
  1126. // performed or not. It is possible that option is NULL, which is valid
  1127. // condition if client didn't request DNS updates and server didn't force
  1128. // the update.
  1129. bool do_fwd = false;
  1130. bool do_rev = false;
  1131. if (fqdn) {
  1132. if (fqdn->getFlag(Option6ClientFqdn::FLAG_S)) {
  1133. do_fwd = true;
  1134. do_rev = true;
  1135. } else if (!fqdn->getFlag(Option6ClientFqdn::FLAG_N)) {
  1136. do_rev = true;
  1137. }
  1138. }
  1139. std::string hostname;
  1140. if (do_fwd || do_rev) {
  1141. hostname = fqdn->getDomainName();
  1142. }
  1143. // If the new FQDN settings have changed for the lease, we need to
  1144. // delete any existing FQDN records for this lease.
  1145. if ((lease->hostname_ != hostname) || (lease->fqdn_fwd_ != do_fwd) ||
  1146. (lease->fqdn_rev_ != do_rev)) {
  1147. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL,
  1148. DHCP6_DDNS_LEASE_RENEW_FQDN_CHANGE)
  1149. .arg(lease->toText())
  1150. .arg(hostname)
  1151. .arg(do_rev ? "true" : "false")
  1152. .arg(do_fwd ? "true" : "false");
  1153. createRemovalNameChangeRequest(lease);
  1154. }
  1155. lease->preferred_lft_ = subnet->getPreferred();
  1156. lease->valid_lft_ = subnet->getValid();
  1157. lease->t1_ = subnet->getT1();
  1158. lease->t2_ = subnet->getT2();
  1159. lease->cltt_ = time(NULL);
  1160. lease->hostname_ = hostname;
  1161. lease->fqdn_fwd_ = do_fwd;
  1162. lease->fqdn_rev_ = do_rev;
  1163. // Create empty IA_NA option with IAID matching the request.
  1164. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_NA, ia->getIAID()));
  1165. ia_rsp->setT1(subnet->getT1());
  1166. ia_rsp->setT2(subnet->getT2());
  1167. boost::shared_ptr<Option6IAAddr> addr(new Option6IAAddr(D6O_IAADDR,
  1168. lease->addr_, lease->preferred_lft_,
  1169. lease->valid_lft_));
  1170. ia_rsp->addOption(addr);
  1171. bool skip = false;
  1172. // Execute all callouts registered for packet6_send
  1173. if (HooksManager::getHooksManager().calloutsPresent(Hooks.hook_index_lease6_renew_)) {
  1174. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  1175. // Delete all previous arguments
  1176. callout_handle->deleteAllArguments();
  1177. // Pass the original packet
  1178. callout_handle->setArgument("query6", query);
  1179. // Pass the lease to be updated
  1180. callout_handle->setArgument("lease6", lease);
  1181. // Pass the IA option to be sent in response
  1182. callout_handle->setArgument("ia_na", ia_rsp);
  1183. // Call all installed callouts
  1184. HooksManager::callCallouts(Hooks.hook_index_lease6_renew_, *callout_handle);
  1185. // Callouts decided to skip the next processing step. The next
  1186. // processing step would to actually renew the lease, so skip at this
  1187. // stage means "keep the old lease as it is".
  1188. if (callout_handle->getSkip()) {
  1189. skip = true;
  1190. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_LEASE6_RENEW_SKIP);
  1191. }
  1192. }
  1193. if (!skip) {
  1194. LeaseMgrFactory::instance().updateLease6(lease);
  1195. } else {
  1196. // Copy back the original date to the lease. For MySQL it doesn't make
  1197. // much sense, but for memfile, the Lease6Ptr points to the actual lease
  1198. // in memfile, so the actual update is performed when we manipulate fields
  1199. // of returned Lease6Ptr, the actual updateLease6() is no-op.
  1200. *lease = old_data;
  1201. }
  1202. return (ia_rsp);
  1203. }
  1204. void
  1205. Dhcpv6Srv::renewLeases(const Pkt6Ptr& renew, Pkt6Ptr& reply,
  1206. const Option6ClientFqdnPtr& fqdn) {
  1207. // We need to renew addresses for all IA_NA options in the client's
  1208. // RENEW message.
  1209. // @todo add support for IA_TA
  1210. // @todo add support for IA_PD
  1211. // We need to select a subnet the client is connected in.
  1212. Subnet6Ptr subnet = selectSubnet(renew);
  1213. if (!subnet) {
  1214. // This particular client is out of luck today. We do not have
  1215. // information about the subnet he is connected to. This likely means
  1216. // misconfiguration of the server (or some relays). We will continue to
  1217. // process this message, but our response will be almost useless: no
  1218. // addresses or prefixes, no subnet specific configuration etc. The only
  1219. // thing this client can get is some global information (like DNS
  1220. // servers).
  1221. LOG_WARN(dhcp6_logger, DHCP6_SUBNET_SELECTION_FAILED)
  1222. .arg(renew->getRemoteAddr().toText())
  1223. .arg(renew->getName());
  1224. } else {
  1225. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL_DATA, DHCP6_SUBNET_SELECTED)
  1226. .arg(subnet->toText());
  1227. }
  1228. // Let's find client's DUID. Client is supposed to include its client-id
  1229. // option almost all the time (the only exception is an anonymous inf-request,
  1230. // but that is mostly a theoretical case). Our allocation engine needs DUID
  1231. // and will refuse to allocate anything to anonymous clients.
  1232. OptionPtr opt_duid = renew->getOption(D6O_CLIENTID);
  1233. if (!opt_duid) {
  1234. // This should not happen. We have checked this before.
  1235. reply->addOption(createStatusCode(STATUS_UnspecFail,
  1236. "You did not include mandatory client-id"));
  1237. return;
  1238. }
  1239. DuidPtr duid(new DUID(opt_duid->getData()));
  1240. for (Option::OptionCollection::iterator opt = renew->options_.begin();
  1241. opt != renew->options_.end(); ++opt) {
  1242. switch (opt->second->getType()) {
  1243. case D6O_IA_NA: {
  1244. OptionPtr answer_opt = renewIA_NA(subnet, duid, renew,
  1245. boost::dynamic_pointer_cast<
  1246. Option6IA>(opt->second),
  1247. fqdn);
  1248. if (answer_opt) {
  1249. reply->addOption(answer_opt);
  1250. }
  1251. break;
  1252. }
  1253. default:
  1254. break;
  1255. }
  1256. }
  1257. }
  1258. void
  1259. Dhcpv6Srv::releaseLeases(const Pkt6Ptr& release, Pkt6Ptr& reply) {
  1260. // We need to release addresses for all IA_NA options in the client's
  1261. // RELEASE message.
  1262. // @todo Add support for IA_TA
  1263. // @todo Add support for IA_PD
  1264. // @todo Consider supporting more than one address in a single IA_NA.
  1265. // That was envisaged by RFC3315, but it never happened. The only
  1266. // software that supports that is Dibbler, but its author seriously doubts
  1267. // if anyone is really using it. Clients that want more than one address
  1268. // just include more instances of IA_NA options.
  1269. // Let's find client's DUID. Client is supposed to include its client-id
  1270. // option almost all the time (the only exception is an anonymous inf-request,
  1271. // but that is mostly a theoretical case). Our allocation engine needs DUID
  1272. // and will refuse to allocate anything to anonymous clients.
  1273. OptionPtr opt_duid = release->getOption(D6O_CLIENTID);
  1274. if (!opt_duid) {
  1275. // This should not happen. We have checked this before.
  1276. // see sanityCheck() called from processRelease()
  1277. LOG_WARN(dhcp6_logger, DHCP6_RELEASE_MISSING_CLIENTID)
  1278. .arg(release->getRemoteAddr().toText());
  1279. reply->addOption(createStatusCode(STATUS_UnspecFail,
  1280. "You did not include mandatory client-id"));
  1281. return;
  1282. }
  1283. DuidPtr duid(new DUID(opt_duid->getData()));
  1284. int general_status = STATUS_Success;
  1285. for (Option::OptionCollection::iterator opt = release->options_.begin();
  1286. opt != release->options_.end(); ++opt) {
  1287. switch (opt->second->getType()) {
  1288. case D6O_IA_NA: {
  1289. OptionPtr answer_opt = releaseIA_NA(duid, release, general_status,
  1290. boost::dynamic_pointer_cast<Option6IA>(opt->second));
  1291. if (answer_opt) {
  1292. reply->addOption(answer_opt);
  1293. }
  1294. break;
  1295. }
  1296. // @todo: add support for IA_PD
  1297. // @todo: add support for IA_TA
  1298. default:
  1299. // remaining options are stateless and thus ignored in this context
  1300. ;
  1301. }
  1302. }
  1303. // To be pedantic, we should also include status code in the top-level
  1304. // scope, not just in each IA_NA. See RFC3315, section 18.2.6.
  1305. // This behavior will likely go away in RFC3315bis.
  1306. reply->addOption(createStatusCode(general_status,
  1307. "Summary status for all processed IA_NAs"));
  1308. }
  1309. OptionPtr
  1310. Dhcpv6Srv::releaseIA_NA(const DuidPtr& duid, const Pkt6Ptr& query,
  1311. int& general_status, boost::shared_ptr<Option6IA> ia) {
  1312. // Release can be done in one of two ways:
  1313. // Approach 1: extract address from client's IA_NA and see if it belongs
  1314. // to this particular client.
  1315. // Approach 2: find a subnet for this client, get a lease for
  1316. // this subnet/duid/iaid and check if its content matches to what the
  1317. // client is asking us to release.
  1318. //
  1319. // This method implements approach 1.
  1320. // That's our response
  1321. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_NA, ia->getIAID()));
  1322. boost::shared_ptr<Option6IAAddr> release_addr = boost::dynamic_pointer_cast<Option6IAAddr>
  1323. (ia->getOption(D6O_IAADDR));
  1324. if (!release_addr) {
  1325. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1326. "You did not include address in your RELEASE"));
  1327. general_status = STATUS_NoBinding;
  1328. return (ia_rsp);
  1329. }
  1330. Lease6Ptr lease = LeaseMgrFactory::instance().getLease6(release_addr->getAddress());
  1331. if (!lease) {
  1332. // client releasing a lease that we don't know about.
  1333. // Insert status code NoAddrsAvail.
  1334. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1335. "Sorry, no known leases for this duid/iaid, can't release."));
  1336. general_status = STATUS_NoBinding;
  1337. LOG_INFO(dhcp6_logger, DHCP6_UNKNOWN_RELEASE)
  1338. .arg(duid->toText())
  1339. .arg(ia->getIAID());
  1340. return (ia_rsp);
  1341. }
  1342. if (!lease->duid_) {
  1343. // Something is gravely wrong here. We do have a lease, but it does not
  1344. // have mandatory DUID information attached. Someone was messing with our
  1345. // database.
  1346. LOG_ERROR(dhcp6_logger, DHCP6_LEASE_WITHOUT_DUID)
  1347. .arg(release_addr->getAddress().toText());
  1348. general_status = STATUS_UnspecFail;
  1349. ia_rsp->addOption(createStatusCode(STATUS_UnspecFail,
  1350. "Database consistency check failed when trying to RELEASE"));
  1351. return (ia_rsp);
  1352. }
  1353. if (*duid != *(lease->duid_)) {
  1354. // Sorry, it's not your address. You can't release it.
  1355. LOG_INFO(dhcp6_logger, DHCP6_RELEASE_FAIL_WRONG_DUID)
  1356. .arg(duid->toText())
  1357. .arg(release_addr->getAddress().toText())
  1358. .arg(lease->duid_->toText());
  1359. general_status = STATUS_NoBinding;
  1360. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1361. "This address does not belong to you, you can't release it"));
  1362. return (ia_rsp);
  1363. }
  1364. if (ia->getIAID() != lease->iaid_) {
  1365. // This address belongs to this client, but to a different IA
  1366. LOG_WARN(dhcp6_logger, DHCP6_RELEASE_FAIL_WRONG_IAID)
  1367. .arg(duid->toText())
  1368. .arg(release_addr->getAddress().toText())
  1369. .arg(lease->iaid_)
  1370. .arg(ia->getIAID());
  1371. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1372. "This is your address, but you used wrong IAID"));
  1373. general_status = STATUS_NoBinding;
  1374. return (ia_rsp);
  1375. }
  1376. // It is not necessary to check if the address matches as we used
  1377. // getLease6(addr) method that is supposed to return a proper lease.
  1378. bool skip = false;
  1379. // Execute all callouts registered for packet6_send
  1380. if (HooksManager::getHooksManager().calloutsPresent(Hooks.hook_index_lease6_release_)) {
  1381. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  1382. // Delete all previous arguments
  1383. callout_handle->deleteAllArguments();
  1384. // Pass the original packet
  1385. callout_handle->setArgument("query6", query);
  1386. // Pass the lease to be updated
  1387. callout_handle->setArgument("lease6", lease);
  1388. // Call all installed callouts
  1389. HooksManager::callCallouts(Hooks.hook_index_lease6_release_, *callout_handle);
  1390. // Callouts decided to skip the next processing step. The next
  1391. // processing step would to send the packet, so skip at this
  1392. // stage means "drop response".
  1393. if (callout_handle->getSkip()) {
  1394. skip = true;
  1395. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_LEASE6_RELEASE_SKIP);
  1396. }
  1397. }
  1398. // Ok, we've passed all checks. Let's release this address.
  1399. bool success = false; // was the removal operation succeessful?
  1400. if (!skip) {
  1401. success = LeaseMgrFactory::instance().deleteLease(lease->addr_);
  1402. }
  1403. // Here the success should be true if we removed lease successfully
  1404. // and false if skip flag was set or the removal failed for whatever reason
  1405. if (!success) {
  1406. ia_rsp->addOption(createStatusCode(STATUS_UnspecFail,
  1407. "Server failed to release a lease"));
  1408. LOG_ERROR(dhcp6_logger, DHCP6_RELEASE_FAIL)
  1409. .arg(lease->addr_.toText())
  1410. .arg(duid->toText())
  1411. .arg(lease->iaid_);
  1412. general_status = STATUS_UnspecFail;
  1413. return (ia_rsp);
  1414. } else {
  1415. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_RELEASE)
  1416. .arg(lease->addr_.toText())
  1417. .arg(duid->toText())
  1418. .arg(lease->iaid_);
  1419. ia_rsp->addOption(createStatusCode(STATUS_Success,
  1420. "Lease released. Thank you, please come again."));
  1421. // Check if a lease has flags indicating that the FQDN update has
  1422. // been performed. If so, create NameChangeRequest which removes
  1423. // the entries.
  1424. createRemovalNameChangeRequest(lease);
  1425. return (ia_rsp);
  1426. }
  1427. }
  1428. Pkt6Ptr
  1429. Dhcpv6Srv::processSolicit(const Pkt6Ptr& solicit) {
  1430. sanityCheck(solicit, MANDATORY, FORBIDDEN);
  1431. Pkt6Ptr advertise(new Pkt6(DHCPV6_ADVERTISE, solicit->getTransid()));
  1432. copyDefaultOptions(solicit, advertise);
  1433. appendDefaultOptions(solicit, advertise);
  1434. appendRequestedOptions(solicit, advertise);
  1435. Option6ClientFqdnPtr fqdn = processClientFqdn(solicit);
  1436. assignLeases(solicit, advertise, fqdn);
  1437. appendClientFqdn(solicit, advertise, fqdn);
  1438. // Note, that we don't create NameChangeRequests here because we don't
  1439. // perform DNS Updates for Solicit. Client must send Request to update
  1440. // DNS.
  1441. return (advertise);
  1442. }
  1443. Pkt6Ptr
  1444. Dhcpv6Srv::processRequest(const Pkt6Ptr& request) {
  1445. sanityCheck(request, MANDATORY, MANDATORY);
  1446. Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, request->getTransid()));
  1447. copyDefaultOptions(request, reply);
  1448. appendDefaultOptions(request, reply);
  1449. appendRequestedOptions(request, reply);
  1450. Option6ClientFqdnPtr fqdn = processClientFqdn(request);
  1451. assignLeases(request, reply, fqdn);
  1452. appendClientFqdn(request, reply, fqdn);
  1453. createNameChangeRequests(reply, fqdn);
  1454. return (reply);
  1455. }
  1456. Pkt6Ptr
  1457. Dhcpv6Srv::processRenew(const Pkt6Ptr& renew) {
  1458. sanityCheck(renew, MANDATORY, MANDATORY);
  1459. Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, renew->getTransid()));
  1460. copyDefaultOptions(renew, reply);
  1461. appendDefaultOptions(renew, reply);
  1462. appendRequestedOptions(renew, reply);
  1463. Option6ClientFqdnPtr fqdn = processClientFqdn(renew);
  1464. renewLeases(renew, reply, fqdn);
  1465. appendClientFqdn(renew, reply, fqdn);
  1466. createNameChangeRequests(reply, fqdn);
  1467. return reply;
  1468. }
  1469. Pkt6Ptr
  1470. Dhcpv6Srv::processRebind(const Pkt6Ptr& rebind) {
  1471. /// @todo: Implement this
  1472. Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, rebind->getTransid()));
  1473. return reply;
  1474. }
  1475. Pkt6Ptr
  1476. Dhcpv6Srv::processConfirm(const Pkt6Ptr& confirm) {
  1477. /// @todo: Implement this
  1478. Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, confirm->getTransid()));
  1479. return reply;
  1480. }
  1481. Pkt6Ptr
  1482. Dhcpv6Srv::processRelease(const Pkt6Ptr& release) {
  1483. sanityCheck(release, MANDATORY, MANDATORY);
  1484. Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, release->getTransid()));
  1485. copyDefaultOptions(release, reply);
  1486. appendDefaultOptions(release, reply);
  1487. releaseLeases(release, reply);
  1488. // @todo If client sent a release and we should remove outstanding
  1489. // DNS records.
  1490. return (reply);
  1491. }
  1492. Pkt6Ptr
  1493. Dhcpv6Srv::processDecline(const Pkt6Ptr& decline) {
  1494. /// @todo: Implement this
  1495. Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, decline->getTransid()));
  1496. return reply;
  1497. }
  1498. Pkt6Ptr
  1499. Dhcpv6Srv::processInfRequest(const Pkt6Ptr& infRequest) {
  1500. /// @todo: Implement this
  1501. Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, infRequest->getTransid()));
  1502. return reply;
  1503. }
  1504. isc::hooks::CalloutHandlePtr Dhcpv6Srv::getCalloutHandle(const Pkt6Ptr& pkt) {
  1505. // This method returns a CalloutHandle for a given packet. It is guaranteed
  1506. // to return the same callout_handle (so user library contexts are
  1507. // preserved). This method works well if the server processes one packet
  1508. // at a time. Once the server architecture is extended to cover parallel
  1509. // packets processing (e.g. delayed-ack, some form of buffering etc.), this
  1510. // method has to be extended (e.g. store callouts in a map and use pkt as
  1511. // a key). Additional code would be required to release the callout handle
  1512. // once the server finished processing.
  1513. CalloutHandlePtr callout_handle;
  1514. static Pkt6Ptr old_pointer;
  1515. if (!callout_handle ||
  1516. old_pointer != pkt) {
  1517. // This is the first packet or a different packet than previously
  1518. // passed to getCalloutHandle()
  1519. // Remember the pointer to this packet
  1520. old_pointer = pkt;
  1521. callout_handle = HooksManager::getHooksManager().createCalloutHandle();
  1522. }
  1523. return (callout_handle);
  1524. }
  1525. void
  1526. Dhcpv6Srv::openActiveSockets(const uint16_t port) {
  1527. IfaceMgr::instance().closeSockets();
  1528. // Get the reference to the collection of interfaces. This reference should be
  1529. // valid as long as the program is run because IfaceMgr is a singleton.
  1530. // Therefore we can safely iterate over instances of all interfaces and modify
  1531. // their flags. Here we modify flags which indicate wheter socket should be
  1532. // open for a particular interface or not.
  1533. const IfaceMgr::IfaceCollection& ifaces = IfaceMgr::instance().getIfaces();
  1534. for (IfaceMgr::IfaceCollection::const_iterator iface = ifaces.begin();
  1535. iface != ifaces.end(); ++iface) {
  1536. Iface* iface_ptr = IfaceMgr::instance().getIface(iface->getName());
  1537. if (iface_ptr == NULL) {
  1538. isc_throw(isc::Unexpected, "Interface Manager returned NULL"
  1539. << " instance of the interface when DHCPv6 server was"
  1540. << " trying to reopen sockets after reconfiguration");
  1541. }
  1542. if (CfgMgr::instance().isActiveIface(iface->getName())) {
  1543. iface_ptr->inactive4_ = false;
  1544. LOG_INFO(dhcp6_logger, DHCP6_ACTIVATE_INTERFACE)
  1545. .arg(iface->getFullName());
  1546. } else {
  1547. // For deactivating interface, it should be sufficient to log it
  1548. // on the debug level because it is more useful to know what
  1549. // interface is activated which is logged on the info level.
  1550. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC,
  1551. DHCP6_DEACTIVATE_INTERFACE).arg(iface->getName());
  1552. iface_ptr->inactive6_ = true;
  1553. }
  1554. }
  1555. // Let's reopen active sockets. openSockets6 will check internally whether
  1556. // sockets are marked active or inactive.
  1557. // @todo Optimization: we should not reopen all sockets but rather select
  1558. // those that have been affected by the new configuration.
  1559. if (!IfaceMgr::instance().openSockets6(port)) {
  1560. LOG_WARN(dhcp6_logger, DHCP6_NO_SOCKETS_OPEN);
  1561. }
  1562. }
  1563. };
  1564. };