dhcp6_srv.cc 76 KB

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