dhcp6_srv.cc 95 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463
  1. // Copyright (C) 2011-2014 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <config.h>
  15. #include <asiolink/io_address.h>
  16. #include <dhcp_ddns/ncr_msg.h>
  17. #include <dhcp/dhcp6.h>
  18. #include <dhcp/docsis3_option_defs.h>
  19. #include <dhcp/duid.h>
  20. #include <dhcp/iface_mgr.h>
  21. #include <dhcp/libdhcp++.h>
  22. #include <dhcp/option6_addrlst.h>
  23. #include <dhcp/option6_client_fqdn.h>
  24. #include <dhcp/option6_ia.h>
  25. #include <dhcp/option6_iaaddr.h>
  26. #include <dhcp/option6_iaprefix.h>
  27. #include <dhcp/option_custom.h>
  28. #include <dhcp/option_vendor.h>
  29. #include <dhcp/option_int_array.h>
  30. #include <dhcp/pkt6.h>
  31. #include <dhcp6/dhcp6_log.h>
  32. #include <dhcp6/dhcp6_srv.h>
  33. #include <dhcpsrv/callout_handle_store.h>
  34. #include <dhcpsrv/cfgmgr.h>
  35. #include <dhcpsrv/lease_mgr.h>
  36. #include <dhcpsrv/lease_mgr_factory.h>
  37. #include <dhcpsrv/subnet.h>
  38. #include <dhcpsrv/utils.h>
  39. #include <exceptions/exceptions.h>
  40. #include <hooks/callout_handle.h>
  41. #include <hooks/hooks_manager.h>
  42. #include <util/encode/hex.h>
  43. #include <util/io_utilities.h>
  44. #include <util/range_utilities.h>
  45. #include <boost/bind.hpp>
  46. #include <boost/foreach.hpp>
  47. #include <boost/tokenizer.hpp>
  48. #include <boost/algorithm/string/erase.hpp>
  49. #include <stdlib.h>
  50. #include <time.h>
  51. #include <iomanip>
  52. #include <fstream>
  53. using namespace isc;
  54. using namespace isc::asiolink;
  55. using namespace isc::dhcp_ddns;
  56. using namespace isc::dhcp;
  57. using namespace isc::hooks;
  58. using namespace isc::util;
  59. using namespace std;
  60. namespace {
  61. /// Structure that holds registered hook indexes
  62. struct Dhcp6Hooks {
  63. int hook_index_buffer6_receive_;///< index for "buffer6_receive" hook point
  64. int hook_index_pkt6_receive_; ///< index for "pkt6_receive" hook point
  65. int hook_index_subnet6_select_; ///< index for "subnet6_select" hook point
  66. int hook_index_lease6_renew_; ///< index for "lease6_renew" hook point
  67. int hook_index_lease6_release_; ///< index for "lease6_release" hook point
  68. int hook_index_pkt6_send_; ///< index for "pkt6_send" hook point
  69. int hook_index_buffer6_send_; ///< index for "buffer6_send" hook point
  70. /// Constructor that registers hook points for DHCPv6 engine
  71. Dhcp6Hooks() {
  72. hook_index_buffer6_receive_= HooksManager::registerHook("buffer6_receive");
  73. hook_index_pkt6_receive_ = HooksManager::registerHook("pkt6_receive");
  74. hook_index_subnet6_select_ = HooksManager::registerHook("subnet6_select");
  75. hook_index_lease6_renew_ = HooksManager::registerHook("lease6_renew");
  76. hook_index_lease6_release_ = HooksManager::registerHook("lease6_release");
  77. hook_index_pkt6_send_ = HooksManager::registerHook("pkt6_send");
  78. hook_index_buffer6_send_ = HooksManager::registerHook("buffer6_send");
  79. }
  80. };
  81. // Declare a Hooks object. As this is outside any function or method, it
  82. // will be instantiated (and the constructor run) when the module is loaded.
  83. // As a result, the hook indexes will be defined before any method in this
  84. // module is called.
  85. Dhcp6Hooks Hooks;
  86. }; // anonymous namespace
  87. namespace isc {
  88. namespace dhcp {
  89. namespace {
  90. // The following constants describe server's behavior with respect to the
  91. // DHCPv6 Client FQDN Option sent by a client. They will be removed
  92. // when DDNS parameters for DHCPv6 are implemented with the ticket #3034.
  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. // Create error handler. This handler will be called every time
  135. // the socket opening operation fails. We use this handler to
  136. // log a warning.
  137. isc::dhcp::IfaceMgrErrorMsgCallback error_handler =
  138. boost::bind(&Dhcpv6Srv::ifaceMgrSocket6ErrorHandler, _1);
  139. IfaceMgr::instance().openSockets6(port_, error_handler);
  140. }
  141. string duid_file = CfgMgr::instance().getDataDir() + "/" + string(SERVER_DUID_FILE);
  142. if (loadServerID(duid_file)) {
  143. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_START, DHCP6_SERVERID_LOADED)
  144. .arg(duidToString(getServerID()))
  145. .arg(duid_file);
  146. } else {
  147. generateServerID();
  148. LOG_INFO(dhcp6_logger, DHCP6_SERVERID_GENERATED)
  149. .arg(duidToString(getServerID()))
  150. .arg(duid_file);
  151. if (!writeServerID(duid_file)) {
  152. LOG_WARN(dhcp6_logger, DHCP6_SERVERID_WRITE_FAIL)
  153. .arg(duid_file);
  154. }
  155. }
  156. // Instantiate allocation engine
  157. alloc_engine_.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE, 100));
  158. /// @todo call loadLibraries() when handling configuration changes
  159. } catch (const std::exception &e) {
  160. LOG_ERROR(dhcp6_logger, DHCP6_SRV_CONSTRUCT_ERROR).arg(e.what());
  161. return;
  162. }
  163. // All done, so can proceed
  164. shutdown_ = false;
  165. }
  166. Dhcpv6Srv::~Dhcpv6Srv() {
  167. IfaceMgr::instance().closeSockets();
  168. LeaseMgrFactory::destroy();
  169. }
  170. void Dhcpv6Srv::shutdown() {
  171. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_SHUTDOWN_REQUEST);
  172. shutdown_ = true;
  173. }
  174. Pkt6Ptr Dhcpv6Srv::receivePacket(int timeout) {
  175. return (IfaceMgr::instance().receive6(timeout));
  176. }
  177. void Dhcpv6Srv::sendPacket(const Pkt6Ptr& packet) {
  178. IfaceMgr::instance().send(packet);
  179. }
  180. bool Dhcpv6Srv::run() {
  181. while (!shutdown_) {
  182. /// @todo Calculate actual timeout to the next event (e.g. lease
  183. /// expiration) once we have lease database. The idea here is that
  184. /// it is possible to do everything in a single process/thread.
  185. /// For now, we are just calling select for 1000 seconds. There
  186. /// were some issues reported on some systems when calling select()
  187. /// with too large values. Unfortunately, I don't recall the details.
  188. //cppcheck-suppress variableScope This is temporary anyway
  189. const int timeout = 1000;
  190. // client's message and server's response
  191. Pkt6Ptr query;
  192. Pkt6Ptr rsp;
  193. try {
  194. query = receivePacket(timeout);
  195. } catch (const std::exception& e) {
  196. LOG_ERROR(dhcp6_logger, DHCP6_PACKET_RECEIVE_FAIL).arg(e.what());
  197. }
  198. // Timeout may be reached or signal received, which breaks select() with no packet received
  199. if (!query) {
  200. continue;
  201. }
  202. // In order to parse the DHCP options, the server needs to use some
  203. // configuration information such as: existing option spaces, option
  204. // definitions etc. This is the kind of information which is not
  205. // available in the libdhcp, so we need to supply our own implementation
  206. // of the option parsing function here, which would rely on the
  207. // configuration data.
  208. query->setCallback(boost::bind(&Dhcpv6Srv::unpackOptions, this, _1, _2,
  209. _3, _4, _5));
  210. bool skip_unpack = false;
  211. // The packet has just been received so contains the uninterpreted wire
  212. // data; execute callouts registered for buffer6_receive.
  213. if (HooksManager::calloutsPresent(Hooks.hook_index_buffer6_receive_)) {
  214. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  215. // Delete previously set arguments
  216. callout_handle->deleteAllArguments();
  217. // Pass incoming packet as argument
  218. callout_handle->setArgument("query6", query);
  219. // Call callouts
  220. HooksManager::callCallouts(Hooks.hook_index_buffer6_receive_, *callout_handle);
  221. // Callouts decided to skip the next processing step. The next
  222. // processing step would to parse the packet, so skip at this
  223. // stage means that callouts did the parsing already, so server
  224. // should skip parsing.
  225. if (callout_handle->getSkip()) {
  226. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_BUFFER_RCVD_SKIP);
  227. skip_unpack = true;
  228. }
  229. callout_handle->getArgument("query6", query);
  230. }
  231. // Unpack the packet information unless the buffer6_receive callouts
  232. // indicated they did it
  233. if (!skip_unpack) {
  234. if (!query->unpack()) {
  235. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL,
  236. DHCP6_PACKET_PARSE_FAIL);
  237. continue;
  238. }
  239. }
  240. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_PACKET_RECEIVED)
  241. .arg(query->getName());
  242. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL_DATA, DHCP6_QUERY_DATA)
  243. .arg(static_cast<int>(query->getType()))
  244. .arg(query->getBuffer().getLength())
  245. .arg(query->toText());
  246. // At this point the information in the packet has been unpacked into
  247. // the various packet fields and option objects has been cretated.
  248. // Execute callouts registered for packet6_receive.
  249. if (HooksManager::calloutsPresent(Hooks.hook_index_pkt6_receive_)) {
  250. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  251. // Delete previously set arguments
  252. callout_handle->deleteAllArguments();
  253. // Pass incoming packet as argument
  254. callout_handle->setArgument("query6", query);
  255. // Call callouts
  256. HooksManager::callCallouts(Hooks.hook_index_pkt6_receive_, *callout_handle);
  257. // Callouts decided to skip the next processing step. The next
  258. // processing step would to process the packet, so skip at this
  259. // stage means drop.
  260. if (callout_handle->getSkip()) {
  261. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_PACKET_RCVD_SKIP);
  262. continue;
  263. }
  264. callout_handle->getArgument("query6", query);
  265. }
  266. try {
  267. NameChangeRequestPtr ncr;
  268. switch (query->getType()) {
  269. case DHCPV6_SOLICIT:
  270. rsp = processSolicit(query);
  271. break;
  272. case DHCPV6_REQUEST:
  273. rsp = processRequest(query);
  274. break;
  275. case DHCPV6_RENEW:
  276. rsp = processRenew(query);
  277. break;
  278. case DHCPV6_REBIND:
  279. rsp = processRebind(query);
  280. break;
  281. case DHCPV6_CONFIRM:
  282. rsp = processConfirm(query);
  283. break;
  284. case DHCPV6_RELEASE:
  285. rsp = processRelease(query);
  286. break;
  287. case DHCPV6_DECLINE:
  288. rsp = processDecline(query);
  289. break;
  290. case DHCPV6_INFORMATION_REQUEST:
  291. rsp = processInfRequest(query);
  292. break;
  293. default:
  294. // We received a packet type that we do not recognize.
  295. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_UNKNOWN_MSG_RECEIVED)
  296. .arg(static_cast<int>(query->getType()))
  297. .arg(query->getIface());
  298. // Only action is to output a message if debug is enabled,
  299. // and that will be covered by the debug statement before
  300. // the "switch" statement.
  301. ;
  302. }
  303. } catch (const RFCViolation& e) {
  304. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_REQUIRED_OPTIONS_CHECK_FAIL)
  305. .arg(query->getName())
  306. .arg(query->getRemoteAddr().toText())
  307. .arg(e.what());
  308. } catch (const isc::Exception& e) {
  309. // Catch-all exception (at least for ones based on the isc
  310. // Exception class, which covers more or less all that
  311. // are explicitly raised in the BIND 10 code). Just log
  312. // the problem and ignore the packet. (The problem is logged
  313. // as a debug message because debug is disabled by default -
  314. // it prevents a DDOS attack based on the sending of problem
  315. // packets.)
  316. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_PACKET_PROCESS_FAIL)
  317. .arg(query->getName())
  318. .arg(query->getRemoteAddr().toText())
  319. .arg(e.what());
  320. }
  321. if (rsp) {
  322. rsp->setRemoteAddr(query->getRemoteAddr());
  323. rsp->setLocalAddr(query->getLocalAddr());
  324. if (rsp->relay_info_.empty()) {
  325. // Direct traffic, send back to the client directly
  326. rsp->setRemotePort(DHCP6_CLIENT_PORT);
  327. } else {
  328. // Relayed traffic, send back to the relay agent
  329. rsp->setRemotePort(DHCP6_SERVER_PORT);
  330. }
  331. rsp->setLocalPort(DHCP6_SERVER_PORT);
  332. rsp->setIndex(query->getIndex());
  333. rsp->setIface(query->getIface());
  334. // Specifies if server should do the packing
  335. bool skip_pack = false;
  336. // Server's reply packet now has all options and fields set.
  337. // Options are represented by individual objects, but the
  338. // output wire data has not been prepared yet.
  339. // Execute all callouts registered for packet6_send
  340. if (HooksManager::calloutsPresent(Hooks.hook_index_pkt6_send_)) {
  341. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  342. // Delete all previous arguments
  343. callout_handle->deleteAllArguments();
  344. // Set our response
  345. callout_handle->setArgument("response6", rsp);
  346. // Call all installed callouts
  347. HooksManager::callCallouts(Hooks.hook_index_pkt6_send_, *callout_handle);
  348. // Callouts decided to skip the next processing step. The next
  349. // processing step would to pack the packet (create wire data).
  350. // That step will be skipped if any callout sets skip flag.
  351. // It essentially means that the callout already did packing,
  352. // so the server does not have to do it again.
  353. if (callout_handle->getSkip()) {
  354. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_PACKET_SEND_SKIP);
  355. skip_pack = true;
  356. }
  357. }
  358. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL_DATA,
  359. DHCP6_RESPONSE_DATA)
  360. .arg(static_cast<int>(rsp->getType())).arg(rsp->toText());
  361. if (!skip_pack) {
  362. try {
  363. rsp->pack();
  364. } catch (const std::exception& e) {
  365. LOG_ERROR(dhcp6_logger, DHCP6_PACK_FAIL)
  366. .arg(e.what());
  367. continue;
  368. }
  369. }
  370. try {
  371. // Now all fields and options are constructed into output wire buffer.
  372. // Option objects modification does not make sense anymore. Hooks
  373. // can only manipulate wire buffer at this stage.
  374. // Let's execute all callouts registered for buffer6_send
  375. if (HooksManager::calloutsPresent(Hooks.hook_index_buffer6_send_)) {
  376. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  377. // Delete previously set arguments
  378. callout_handle->deleteAllArguments();
  379. // Pass incoming packet as argument
  380. callout_handle->setArgument("response6", rsp);
  381. // Call callouts
  382. HooksManager::callCallouts(Hooks.hook_index_buffer6_send_, *callout_handle);
  383. // Callouts decided to skip the next processing step. The next
  384. // processing step would to parse the packet, so skip at this
  385. // stage means drop.
  386. if (callout_handle->getSkip()) {
  387. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_BUFFER_SEND_SKIP);
  388. continue;
  389. }
  390. callout_handle->getArgument("response6", rsp);
  391. }
  392. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL_DATA,
  393. DHCP6_RESPONSE_DATA)
  394. .arg(static_cast<int>(rsp->getType())).arg(rsp->toText());
  395. sendPacket(rsp);
  396. } catch (const std::exception& e) {
  397. LOG_ERROR(dhcp6_logger, DHCP6_PACKET_SEND_FAIL)
  398. .arg(e.what());
  399. }
  400. // Send NameChangeRequests to the b10-dhcp-ddns module.
  401. sendNameChangeRequests();
  402. }
  403. }
  404. return (true);
  405. }
  406. bool Dhcpv6Srv::loadServerID(const std::string& file_name) {
  407. // load content of the file into a string
  408. fstream f(file_name.c_str(), ios::in);
  409. if (!f.is_open()) {
  410. return (false);
  411. }
  412. string hex_string;
  413. f >> hex_string;
  414. f.close();
  415. // remove any spaces
  416. boost::algorithm::erase_all(hex_string, " ");
  417. // now remove :
  418. /// @todo: We should check first if the format is sane.
  419. /// Otherwise 1:2:3:4 will be converted to 0x12, 0x34
  420. boost::algorithm::erase_all(hex_string, ":");
  421. std::vector<uint8_t> bin;
  422. // Decode the hex string and store it in bin (which happens
  423. // to be OptionBuffer format)
  424. isc::util::encode::decodeHex(hex_string, bin);
  425. // Now create server-id option
  426. serverid_.reset(new Option(Option::V6, D6O_SERVERID, bin));
  427. return (true);
  428. }
  429. std::string
  430. Dhcpv6Srv::duidToString(const OptionPtr& opt) {
  431. stringstream tmp;
  432. OptionBuffer data = opt->getData();
  433. bool colon = false;
  434. for (OptionBufferConstIter it = data.begin(); it != data.end(); ++it) {
  435. if (colon) {
  436. tmp << ":";
  437. }
  438. tmp << hex << setw(2) << setfill('0') << static_cast<uint16_t>(*it);
  439. if (!colon) {
  440. colon = true;
  441. }
  442. }
  443. return tmp.str();
  444. }
  445. bool
  446. Dhcpv6Srv::writeServerID(const std::string& file_name) {
  447. fstream f(file_name.c_str(), ios::out | ios::trunc);
  448. if (!f.good()) {
  449. return (false);
  450. }
  451. f << duidToString(getServerID());
  452. f.close();
  453. return (true);
  454. }
  455. void
  456. Dhcpv6Srv::generateServerID() {
  457. /// @todo: This code implements support for DUID-LLT (the recommended one).
  458. /// We should eventually add support for other DUID types: DUID-LL, DUID-EN
  459. /// and DUID-UUID
  460. const IfaceMgr::IfaceCollection& ifaces = IfaceMgr::instance().getIfaces();
  461. // Let's find suitable interface.
  462. for (IfaceMgr::IfaceCollection::const_iterator iface = ifaces.begin();
  463. iface != ifaces.end(); ++iface) {
  464. // All the following checks could be merged into one multi-condition
  465. // statement, but let's keep them separated as perhaps one day
  466. // we will grow knobs to selectively turn them on or off. Also,
  467. // this code is used only *once* during first start on a new machine
  468. // and then server-id is stored. (or at least it will be once
  469. // DUID storage is implemented)
  470. // I wish there was a this_is_a_real_physical_interface flag...
  471. // MAC address should be at least 6 bytes. Although there is no such
  472. // requirement in any RFC, all decent physical interfaces (Ethernet,
  473. // WiFi, Infiniband, etc.) have 6 bytes long MAC address. We want to
  474. // base our DUID on real hardware address, rather than virtual
  475. // interface that pretends that underlying IP address is its MAC.
  476. if (iface->getMacLen() < MIN_MAC_LEN) {
  477. continue;
  478. }
  479. // Let's don't use loopback.
  480. if (iface->flag_loopback_) {
  481. continue;
  482. }
  483. // Let's skip downed interfaces. It is better to use working ones.
  484. if (!iface->flag_up_) {
  485. continue;
  486. }
  487. // Some interfaces (like lo on Linux) report 6-bytes long
  488. // MAC address 00:00:00:00:00:00. Let's not use such weird interfaces
  489. // to generate DUID.
  490. if (isRangeZero(iface->getMac(), iface->getMac() + iface->getMacLen())) {
  491. continue;
  492. }
  493. // Ok, we have useful MAC. Let's generate DUID-LLT based on
  494. // it. See RFC3315, Section 9.2 for details.
  495. // DUID uses seconds since midnight of 01-01-2000, time() returns
  496. // seconds since 01-01-1970. DUID_TIME_EPOCH substution corrects that.
  497. time_t seconds = time(NULL);
  498. seconds -= DUID_TIME_EPOCH;
  499. OptionBuffer srvid(8 + iface->getMacLen());
  500. writeUint16(DUID::DUID_LLT, &srvid[0]);
  501. writeUint16(HWTYPE_ETHERNET, &srvid[2]);
  502. writeUint32(static_cast<uint32_t>(seconds), &srvid[4]);
  503. memcpy(&srvid[0] + 8, iface->getMac(), iface->getMacLen());
  504. serverid_ = OptionPtr(new Option(Option::V6, D6O_SERVERID,
  505. srvid.begin(), srvid.end()));
  506. return;
  507. }
  508. // If we reached here, there are no suitable interfaces found.
  509. // Either interface detection is not supported on this platform or
  510. // this is really weird box. Let's use DUID-EN instead.
  511. // See Section 9.3 of RFC3315 for details.
  512. OptionBuffer srvid(12);
  513. writeUint16(DUID::DUID_EN, &srvid[0]);
  514. writeUint32(ENTERPRISE_ID_ISC, &srvid[2]);
  515. // Length of the identifier is company specific. I hereby declare
  516. // ISC "standard" of 6 bytes long pseudo-random numbers.
  517. srandom(time(NULL));
  518. fillRandom(&srvid[6], &srvid[12]);
  519. serverid_ = OptionPtr(new Option(Option::V6, D6O_SERVERID,
  520. srvid.begin(), srvid.end()));
  521. }
  522. void
  523. Dhcpv6Srv::copyDefaultOptions(const Pkt6Ptr& question, Pkt6Ptr& answer) {
  524. // Add client-id.
  525. OptionPtr clientid = question->getOption(D6O_CLIENTID);
  526. if (clientid) {
  527. answer->addOption(clientid);
  528. }
  529. /// @todo: Should throw if there is no client-id (except anonymous INF-REQUEST)
  530. // If this is a relayed message, we need to copy relay information
  531. if (!question->relay_info_.empty()) {
  532. answer->copyRelayInfo(question);
  533. }
  534. }
  535. void
  536. Dhcpv6Srv::appendDefaultOptions(const Pkt6Ptr&, Pkt6Ptr& answer) {
  537. // add server-id
  538. answer->addOption(getServerID());
  539. }
  540. void
  541. Dhcpv6Srv::appendRequestedOptions(const Pkt6Ptr& question, Pkt6Ptr& answer) {
  542. // Get the configured subnet suitable for the incoming packet.
  543. Subnet6Ptr subnet = selectSubnet(question);
  544. // Leave if there is no subnet matching the incoming packet.
  545. // There is no need to log the error message here because
  546. // it will be logged in the assignLease() when it fails to
  547. // pick the suitable subnet. We don't want to duplicate
  548. // error messages in such case.
  549. if (!subnet) {
  550. return;
  551. }
  552. // Client requests some options using ORO option. Try to
  553. // get this option from client's message.
  554. boost::shared_ptr<OptionIntArray<uint16_t> > option_oro =
  555. boost::dynamic_pointer_cast<OptionIntArray<uint16_t> >(question->getOption(D6O_ORO));
  556. // Option ORO not found. Don't do anything then.
  557. if (!option_oro) {
  558. return;
  559. }
  560. // Get the list of options that client requested.
  561. const std::vector<uint16_t>& requested_opts = option_oro->getValues();
  562. BOOST_FOREACH(uint16_t opt, requested_opts) {
  563. Subnet::OptionDescriptor desc = subnet->getOptionDescriptor("dhcp6", opt);
  564. if (desc.option) {
  565. answer->addOption(desc.option);
  566. }
  567. }
  568. }
  569. void
  570. Dhcpv6Srv::appendRequestedVendorOptions(const Pkt6Ptr& question, Pkt6Ptr& answer) {
  571. // Get the configured subnet suitable for the incoming packet.
  572. Subnet6Ptr subnet = selectSubnet(question);
  573. // Leave if there is no subnet matching the incoming packet.
  574. // There is no need to log the error message here because
  575. // it will be logged in the assignLease() when it fails to
  576. // pick the suitable subnet. We don't want to duplicate
  577. // error messages in such case.
  578. if (!subnet) {
  579. return;
  580. }
  581. // Try to get the vendor option
  582. boost::shared_ptr<OptionVendor> vendor_req =
  583. boost::dynamic_pointer_cast<OptionVendor>(question->getOption(D6O_VENDOR_OPTS));
  584. if (!vendor_req) {
  585. return;
  586. }
  587. // Let's try to get ORO within that vendor-option
  588. /// @todo This is very specific to vendor-id=4491 (Cable Labs). Other vendors
  589. /// may have different policies.
  590. boost::shared_ptr<OptionUint16Array> oro =
  591. boost::dynamic_pointer_cast<OptionUint16Array>(vendor_req->getOption(DOCSIS3_V6_ORO));
  592. // Option ORO not found. Don't do anything then.
  593. if (!oro) {
  594. return;
  595. }
  596. uint32_t vendor_id = vendor_req->getVendorId();
  597. boost::shared_ptr<OptionVendor> vendor_rsp(new OptionVendor(Option::V6, vendor_id));
  598. // Get the list of options that client requested.
  599. bool added = false;
  600. const std::vector<uint16_t>& requested_opts = oro->getValues();
  601. BOOST_FOREACH(uint16_t opt, requested_opts) {
  602. Subnet::OptionDescriptor desc = subnet->getVendorOptionDescriptor(vendor_id, opt);
  603. if (desc.option) {
  604. vendor_rsp->addOption(desc.option);
  605. added = true;
  606. }
  607. }
  608. if (added) {
  609. answer->addOption(vendor_rsp);
  610. }
  611. }
  612. OptionPtr
  613. Dhcpv6Srv::createStatusCode(uint16_t code, const std::string& text) {
  614. // @todo This function uses OptionCustom class to manage contents
  615. // of the data fields. Since this this option is frequently used
  616. // it may be good to implement dedicated class to avoid performance
  617. // impact.
  618. // Get the definition of the option holding status code.
  619. OptionDefinitionPtr status_code_def =
  620. LibDHCP::getOptionDef(Option::V6, D6O_STATUS_CODE);
  621. // This definition is assumed to be initialized in LibDHCP.
  622. assert(status_code_def);
  623. // As there is no dedicated class to represent Status Code
  624. // the OptionCustom class is used here instead.
  625. OptionCustomPtr option_status =
  626. OptionCustomPtr(new OptionCustom(*status_code_def, Option::V6));
  627. assert(option_status);
  628. // Set status code to 'code' (0 - means data field #0).
  629. option_status->writeInteger(code, 0);
  630. // Set a message (1 - means data field #1).
  631. option_status->writeString(text, 1);
  632. return (option_status);
  633. }
  634. void
  635. Dhcpv6Srv::sanityCheck(const Pkt6Ptr& pkt, RequirementLevel clientid,
  636. RequirementLevel serverid) {
  637. OptionCollection client_ids = pkt->getOptions(D6O_CLIENTID);
  638. switch (clientid) {
  639. case MANDATORY:
  640. if (client_ids.size() != 1) {
  641. isc_throw(RFCViolation, "Exactly 1 client-id option expected in "
  642. << pkt->getName() << ", but " << client_ids.size()
  643. << " received");
  644. }
  645. break;
  646. case OPTIONAL:
  647. if (client_ids.size() > 1) {
  648. isc_throw(RFCViolation, "Too many (" << client_ids.size()
  649. << ") client-id options received in " << pkt->getName());
  650. }
  651. break;
  652. case FORBIDDEN:
  653. // doesn't make sense - client-id is always allowed
  654. break;
  655. }
  656. OptionCollection server_ids = pkt->getOptions(D6O_SERVERID);
  657. switch (serverid) {
  658. case FORBIDDEN:
  659. if (!server_ids.empty()) {
  660. isc_throw(RFCViolation, "Server-id option was not expected, but "
  661. << server_ids.size() << " received in " << pkt->getName());
  662. }
  663. break;
  664. case MANDATORY:
  665. if (server_ids.size() != 1) {
  666. isc_throw(RFCViolation, "Invalid number of server-id options received ("
  667. << server_ids.size() << "), exactly 1 expected in message "
  668. << pkt->getName());
  669. }
  670. break;
  671. case OPTIONAL:
  672. if (server_ids.size() > 1) {
  673. isc_throw(RFCViolation, "Too many (" << server_ids.size()
  674. << ") server-id options received in " << pkt->getName());
  675. }
  676. }
  677. }
  678. Subnet6Ptr
  679. Dhcpv6Srv::selectSubnet(const Pkt6Ptr& question) {
  680. Subnet6Ptr subnet;
  681. if (question->relay_info_.empty()) {
  682. // This is a direct (non-relayed) message
  683. // Try to find a subnet if received packet from a directly connected client
  684. subnet = CfgMgr::instance().getSubnet6(question->getIface());
  685. if (!subnet) {
  686. // If no subnet was found, try to find it based on remote address
  687. subnet = CfgMgr::instance().getSubnet6(question->getRemoteAddr());
  688. }
  689. } else {
  690. // This is a relayed message
  691. OptionPtr interface_id = question->getAnyRelayOption(D6O_INTERFACE_ID,
  692. Pkt6::RELAY_GET_FIRST);
  693. if (interface_id) {
  694. subnet = CfgMgr::instance().getSubnet6(interface_id);
  695. }
  696. if (!subnet) {
  697. // If no interface-id was specified (or not configured on server), let's
  698. // try address matching
  699. IOAddress link_addr = question->relay_info_.back().linkaddr_;
  700. // if relay filled in link_addr field, then let's use it
  701. if (link_addr != IOAddress("::")) {
  702. subnet = CfgMgr::instance().getSubnet6(link_addr);
  703. }
  704. }
  705. }
  706. // Let's execute all callouts registered for subnet6_receive
  707. if (HooksManager::calloutsPresent(Hooks.hook_index_subnet6_select_)) {
  708. CalloutHandlePtr callout_handle = getCalloutHandle(question);
  709. // We're reusing callout_handle from previous calls
  710. callout_handle->deleteAllArguments();
  711. // Set new arguments
  712. callout_handle->setArgument("query6", question);
  713. callout_handle->setArgument("subnet6", subnet);
  714. // We pass pointer to const collection for performance reasons.
  715. // Otherwise we would get a non-trivial performance penalty each
  716. // time subnet6_select is called.
  717. callout_handle->setArgument("subnet6collection", CfgMgr::instance().getSubnets6());
  718. // Call user (and server-side) callouts
  719. HooksManager::callCallouts(Hooks.hook_index_subnet6_select_, *callout_handle);
  720. // Callouts decided to skip this step. This means that no subnet will be
  721. // selected. Packet processing will continue, but it will be severly limited
  722. // (i.e. only global options will be assigned)
  723. if (callout_handle->getSkip()) {
  724. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_SUBNET6_SELECT_SKIP);
  725. return (Subnet6Ptr());
  726. }
  727. // Use whatever subnet was specified by the callout
  728. callout_handle->getArgument("subnet6", subnet);
  729. }
  730. return (subnet);
  731. }
  732. void
  733. Dhcpv6Srv::assignLeases(const Pkt6Ptr& question, Pkt6Ptr& answer) {
  734. // We need to allocate addresses for all IA_NA options in the client's
  735. // question (i.e. SOLICIT or REQUEST) message.
  736. // @todo add support for IA_TA
  737. // We need to select a subnet the client is connected in.
  738. Subnet6Ptr subnet = selectSubnet(question);
  739. if (!subnet) {
  740. // This particular client is out of luck today. We do not have
  741. // information about the subnet he is connected to. This likely means
  742. // misconfiguration of the server (or some relays). We will continue to
  743. // process this message, but our response will be almost useless: no
  744. // addresses or prefixes, no subnet specific configuration etc. The only
  745. // thing this client can get is some global information (like DNS
  746. // servers).
  747. LOG_WARN(dhcp6_logger, DHCP6_SUBNET_SELECTION_FAILED)
  748. .arg(question->getRemoteAddr().toText())
  749. .arg(question->getName());
  750. } else {
  751. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL_DATA, DHCP6_SUBNET_SELECTED)
  752. .arg(subnet->toText());
  753. }
  754. // @todo: We should implement Option6Duid some day, but we can do without it
  755. // just fine for now
  756. // Let's find client's DUID. Client is supposed to include its client-id
  757. // option almost all the time (the only exception is an anonymous inf-request,
  758. // but that is mostly a theoretical case). Our allocation engine needs DUID
  759. // and will refuse to allocate anything to anonymous clients.
  760. DuidPtr duid;
  761. OptionPtr opt_duid = question->getOption(D6O_CLIENTID);
  762. if (opt_duid) {
  763. duid = DuidPtr(new DUID(opt_duid->getData()));
  764. } else {
  765. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_CLIENTID_MISSING);
  766. // Let's drop the message. This client is not sane.
  767. isc_throw(RFCViolation, "Mandatory client-id is missing in received message");
  768. }
  769. // Now that we have all information about the client, let's iterate over all
  770. // received options and handle IA_NA options one by one and store our
  771. // responses in answer message (ADVERTISE or REPLY).
  772. //
  773. // @todo: expand this to cover IA_PD and IA_TA once we implement support for
  774. // prefix delegation and temporary addresses.
  775. for (OptionCollection::iterator opt = question->options_.begin();
  776. opt != question->options_.end(); ++opt) {
  777. switch (opt->second->getType()) {
  778. case D6O_IA_NA: {
  779. OptionPtr answer_opt = assignIA_NA(subnet, duid, question, answer,
  780. boost::dynamic_pointer_cast<
  781. Option6IA>(opt->second));
  782. if (answer_opt) {
  783. answer->addOption(answer_opt);
  784. }
  785. break;
  786. }
  787. case D6O_IA_PD: {
  788. OptionPtr answer_opt = assignIA_PD(subnet, duid, question,
  789. boost::dynamic_pointer_cast<
  790. Option6IA>(opt->second));
  791. if (answer_opt) {
  792. answer->addOption(answer_opt);
  793. }
  794. }
  795. default:
  796. break;
  797. }
  798. }
  799. }
  800. void
  801. Dhcpv6Srv::processClientFqdn(const Pkt6Ptr& question, const Pkt6Ptr& answer) {
  802. // Get Client FQDN Option from the client's message. If this option hasn't
  803. // been included, do nothing.
  804. Option6ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<
  805. Option6ClientFqdn>(question->getOption(D6O_CLIENT_FQDN));
  806. if (!fqdn) {
  807. return;
  808. }
  809. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL,
  810. DHCP6_DDNS_RECEIVE_FQDN).arg(fqdn->toText());
  811. // Prepare the FQDN option which will be included in the response to
  812. // the client.
  813. Option6ClientFqdnPtr fqdn_resp(new Option6ClientFqdn(*fqdn));
  814. // RFC 4704, section 6. - all flags set to 0.
  815. fqdn_resp->resetFlags();
  816. // Conditions when N flag has to be set to indicate that server will not
  817. // perform DNS updates:
  818. // 1. Updates are globally disabled,
  819. // 2. Client requested no update and server respects it,
  820. // 3. Client requested that the AAAA update is delegated to the client but
  821. // server neither respects delegation of updates nor it is configured
  822. // to send update on its own when client requested delegation.
  823. if (!FQDN_ENABLE_UPDATE ||
  824. (fqdn->getFlag(Option6ClientFqdn::FLAG_N) &&
  825. !FQDN_OVERRIDE_NO_UPDATE) ||
  826. (!fqdn->getFlag(Option6ClientFqdn::FLAG_S) &&
  827. !FQDN_ALLOW_CLIENT_UPDATE && !FQDN_OVERRIDE_CLIENT_UPDATE)) {
  828. fqdn_resp->setFlag(Option6ClientFqdn::FLAG_N, true);
  829. // Conditions when S flag is set to indicate that server will perform
  830. // DNS update on its own:
  831. // 1. Client requested that server performs DNS update and DNS updates are
  832. // globally enabled
  833. // 2. Client requested that server delegates AAAA update to the client but
  834. // server doesn't respect delegation and it is configured to perform
  835. // an update on its own when client requested delegation.
  836. } else if (fqdn->getFlag(Option6ClientFqdn::FLAG_S) ||
  837. (!fqdn->getFlag(Option6ClientFqdn::FLAG_S) &&
  838. !FQDN_ALLOW_CLIENT_UPDATE && FQDN_OVERRIDE_CLIENT_UPDATE)) {
  839. fqdn_resp->setFlag(Option6ClientFqdn::FLAG_S, true);
  840. }
  841. // Server MUST set the O flag if it has overridden the client's setting
  842. // of S flag.
  843. if (fqdn->getFlag(Option6ClientFqdn::FLAG_S) !=
  844. fqdn_resp->getFlag(Option6ClientFqdn::FLAG_S)) {
  845. fqdn_resp->setFlag(Option6ClientFqdn::FLAG_O, true);
  846. }
  847. // If client supplied partial or empty domain-name, server should
  848. // generate one.
  849. if (fqdn->getDomainNameType() == Option6ClientFqdn::PARTIAL) {
  850. std::ostringstream name;
  851. if (fqdn->getDomainName().empty() || FQDN_REPLACE_CLIENT_NAME) {
  852. fqdn->setDomainName("", Option6ClientFqdn::PARTIAL);
  853. } else {
  854. name << fqdn->getDomainName();
  855. name << "." << FQDN_PARTIAL_SUFFIX;
  856. fqdn_resp->setDomainName(name.str(), Option6ClientFqdn::FULL);
  857. }
  858. // Server may be configured to replace a name supplied by a client,
  859. // even if client supplied fully qualified domain-name.
  860. } else if (FQDN_REPLACE_CLIENT_NAME) {
  861. std::ostringstream name;
  862. name << FQDN_GENERATED_PARTIAL_NAME << "." << FQDN_PARTIAL_SUFFIX;
  863. fqdn_resp->setDomainName(name.str(), Option6ClientFqdn::FULL);
  864. }
  865. // The FQDN has been processed successfully. Let's append it to the
  866. // response to be sent to a client. Note that the Client FQDN option is
  867. // always sent back to the client if Client FQDN was included in the
  868. // client's message.
  869. answer->addOption(fqdn_resp);
  870. }
  871. void
  872. Dhcpv6Srv::createNameChangeRequests(const Pkt6Ptr& answer) {
  873. // The response message instance is always required. For instance it
  874. // holds the Client Identifier. It is a programming error if supplied
  875. // message is NULL.
  876. if (!answer) {
  877. isc_throw(isc::Unexpected, "an instance of the object"
  878. << " encapsulating server's message must not be"
  879. << " NULL when creating DNS NameChangeRequest");
  880. }
  881. // It is likely that client haven't included the FQDN option. In such case,
  882. // FQDN option will be NULL. This is valid state, so we simply return.
  883. Option6ClientFqdnPtr opt_fqdn = boost::dynamic_pointer_cast<
  884. Option6ClientFqdn>(answer->getOption(D6O_CLIENT_FQDN));
  885. if (!opt_fqdn) {
  886. return;
  887. }
  888. // Get the Client Id. It is mandatory and a function creating a response
  889. // would have thrown an exception if it was missing. Thus throwning
  890. // Unexpected if it is missing as it is a programming error.
  891. OptionPtr opt_duid = answer->getOption(D6O_CLIENTID);
  892. if (!opt_duid) {
  893. isc_throw(isc::Unexpected,
  894. "client identifier is required when creating a new"
  895. " DNS NameChangeRequest");
  896. }
  897. DuidPtr duid = DuidPtr(new DUID(opt_duid->getData()));
  898. // Get the FQDN in the on-wire format. It will be needed to compute
  899. // DHCID.
  900. OutputBuffer name_buf(1);
  901. opt_fqdn->packDomainName(name_buf);
  902. const uint8_t* name_data = static_cast<const uint8_t*>(name_buf.getData());
  903. // @todo currently D2Dhcid accepts a vector holding FQDN.
  904. // However, it will be faster if we used a pointer name_data.
  905. std::vector<uint8_t> buf_vec(name_data, name_data + name_buf.getLength());
  906. // Compute DHCID from Client Identifier and FQDN.
  907. isc::dhcp_ddns::D2Dhcid dhcid(*duid, buf_vec);
  908. // Get all IAs from the answer. For each IA, holding an address we will
  909. // create a corresponding NameChangeRequest.
  910. OptionCollection answer_ias = answer->getOptions(D6O_IA_NA);
  911. for (OptionCollection::const_iterator answer_ia =
  912. answer_ias.begin(); answer_ia != answer_ias.end(); ++answer_ia) {
  913. /// @todo IA_NA may contain multiple addresses. We should process
  914. /// each address individually. Currently we get only one.
  915. Option6IAAddrPtr iaaddr = boost::static_pointer_cast<
  916. Option6IAAddr>(answer_ia->second->getOption(D6O_IAADDR));
  917. // We need an address to create a name-to-address mapping.
  918. // If address is missing for any reason, go to the next IA.
  919. if (!iaaddr) {
  920. continue;
  921. }
  922. // Create new NameChangeRequest. Use the domain name from the FQDN.
  923. // This is an FQDN included in the response to the client, so it
  924. // holds a fully qualified domain-name already (not partial).
  925. // Get the IP address from the lease. Also, use the S flag to determine
  926. // if forward change should be performed. This flag will always be
  927. // set if server has taken responsibility for the forward update.
  928. NameChangeRequest ncr(isc::dhcp_ddns::CHG_ADD,
  929. opt_fqdn->getFlag(Option6ClientFqdn::FLAG_S),
  930. true, opt_fqdn->getDomainName(),
  931. iaaddr->getAddress().toText(),
  932. dhcid, 0, iaaddr->getValid());
  933. // Add the request to the queue. This queue will be read elsewhere in
  934. // the code and all requests from this queue will be sent to the
  935. // D2 module.
  936. name_change_reqs_.push(ncr);
  937. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL,
  938. DHCP6_DDNS_CREATE_ADD_NAME_CHANGE_REQUEST).arg(ncr.toText());
  939. /// @todo Currently we create NCR with the first IPv6 address that
  940. /// is carried in one of the IA_NAs. In the future, the NCR API should
  941. /// be extended to map multiple IPv6 addresses to a single FQDN.
  942. /// In such case, this return statement will be removed.
  943. return;
  944. }
  945. }
  946. void
  947. Dhcpv6Srv::createRemovalNameChangeRequest(const Lease6Ptr& lease) {
  948. // If we haven't performed a DNS Update when lease was acquired,
  949. // there is nothing to do here.
  950. if (!lease->fqdn_fwd_ && !lease->fqdn_rev_) {
  951. return;
  952. }
  953. // When lease was added into a database the host name should have
  954. // been added. The hostname can be empty if someone messed up in the
  955. // lease data base and removed the hostname.
  956. if (lease->hostname_.empty()) {
  957. LOG_ERROR(dhcp6_logger, DHCP6_DDNS_REMOVE_EMPTY_HOSTNAME)
  958. .arg(lease->addr_.toText());
  959. return;
  960. }
  961. // If hostname is non-empty, try to convert it to wire format so as
  962. // DHCID can be computed from it. This may throw an exception if hostname
  963. // has invalid format. Again, this should be only possible in case of
  964. // manual intervention in the database. Note that the last parameter
  965. // passed to the writeFqdn function forces conversion of the FQDN
  966. // to lower case. This is required by the RFC4701, section 3.5.
  967. // The DHCID computation is further in this function.
  968. std::vector<uint8_t> hostname_wire;
  969. try {
  970. OptionDataTypeUtil::writeFqdn(lease->hostname_, hostname_wire, true);
  971. } catch (const Exception& ex) {
  972. LOG_ERROR(dhcp6_logger, DHCP6_DDNS_REMOVE_INVALID_HOSTNAME)
  973. .arg(lease->hostname_);
  974. return;
  975. }
  976. // DUID must have been checked already by the caller of this function.
  977. // Let's be on the safe side and make sure it is non-NULL and throw
  978. // an exception if it is NULL.
  979. if (!lease->duid_) {
  980. isc_throw(isc::Unexpected, "DUID must be set when creating"
  981. << " NameChangeRequest for DNS records removal for "
  982. << lease->addr_);
  983. }
  984. isc::dhcp_ddns::D2Dhcid dhcid(*lease->duid_, hostname_wire);
  985. // Create a NameChangeRequest to remove the entry.
  986. NameChangeRequest ncr(isc::dhcp_ddns::CHG_REMOVE,
  987. lease->fqdn_fwd_, lease->fqdn_rev_,
  988. lease->hostname_,
  989. lease->addr_.toText(),
  990. dhcid, 0, lease->valid_lft_);
  991. name_change_reqs_.push(ncr);
  992. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL,
  993. DHCP6_DDNS_CREATE_REMOVE_NAME_CHANGE_REQUEST).arg(ncr.toText());
  994. }
  995. void
  996. Dhcpv6Srv::sendNameChangeRequests() {
  997. while (!name_change_reqs_.empty()) {
  998. // @todo Once next NameChangeRequest is picked from the queue
  999. // we should send it to the b10-dhcp_ddns module. Currently we
  1000. // just drop it.
  1001. name_change_reqs_.pop();
  1002. }
  1003. }
  1004. OptionPtr
  1005. Dhcpv6Srv::assignIA_NA(const Subnet6Ptr& subnet, const DuidPtr& duid,
  1006. const Pkt6Ptr& query, const Pkt6Ptr& answer,
  1007. boost::shared_ptr<Option6IA> ia) {
  1008. // If there is no subnet selected for handling this IA_NA, the only thing to do left is
  1009. // to say that we are sorry, but the user won't get an address. As a convenience, we
  1010. // use a different status text to indicate that (compare to the same status code,
  1011. // but different wording below)
  1012. if (!subnet) {
  1013. // Creatasse empty IA_NA option with IAID matching the request.
  1014. // Note that we don't use OptionDefinition class to create this option.
  1015. // This is because we prefer using a constructor of Option6IA that
  1016. // initializes IAID. Otherwise we would have to use setIAID() after
  1017. // creation of the option which has some performance implications.
  1018. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_NA, ia->getIAID()));
  1019. // Insert status code NoAddrsAvail.
  1020. ia_rsp->addOption(createStatusCode(STATUS_NoAddrsAvail, "Sorry, no subnet available."));
  1021. return (ia_rsp);
  1022. }
  1023. // Check if the client sent us a hint in his IA_NA. Clients may send an
  1024. // address in their IA_NA options as a suggestion (e.g. the last address
  1025. // they used before).
  1026. boost::shared_ptr<Option6IAAddr> hint_opt =
  1027. boost::dynamic_pointer_cast<Option6IAAddr>(ia->getOption(D6O_IAADDR));
  1028. IOAddress hint("::");
  1029. if (hint_opt) {
  1030. hint = hint_opt->getAddress();
  1031. }
  1032. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_PROCESS_IA_NA_REQUEST)
  1033. .arg(duid ? duid->toText() : "(no-duid)").arg(ia->getIAID())
  1034. .arg(hint_opt ? hint.toText() : "(no hint)");
  1035. // "Fake" allocation is processing of SOLICIT message. We pretend to do an
  1036. // allocation, but we do not put the lease in the database. That is ok,
  1037. // because we do not guarantee that the user will get that exact lease. If
  1038. // the user selects this server to do actual allocation (i.e. sends REQUEST)
  1039. // it should include this hint. That will help us during the actual lease
  1040. // allocation.
  1041. bool fake_allocation = false;
  1042. if (query->getType() == DHCPV6_SOLICIT) {
  1043. /// @todo: Check if we support rapid commit
  1044. fake_allocation = true;
  1045. }
  1046. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  1047. // At this point, we have to make make some decisions with respect to the
  1048. // FQDN option that we have generated as a result of receiving client's
  1049. // FQDN. In particular, we have to get to know if the DNS update will be
  1050. // performed or not. It is possible that option is NULL, which is valid
  1051. // condition if client didn't request DNS updates and server didn't force
  1052. // the update.
  1053. bool do_fwd = false;
  1054. bool do_rev = false;
  1055. Option6ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<
  1056. Option6ClientFqdn>(answer->getOption(D6O_CLIENT_FQDN));
  1057. if (fqdn) {
  1058. // Flag S must not coexist with flag N being set to 1, so if S=1
  1059. // server takes responsibility for both reverse and forward updates.
  1060. // Otherwise, we have to check N.
  1061. if (fqdn->getFlag(Option6ClientFqdn::FLAG_S)) {
  1062. do_fwd = true;
  1063. do_rev = true;
  1064. } else if (!fqdn->getFlag(Option6ClientFqdn::FLAG_N)) {
  1065. do_rev = true;
  1066. }
  1067. }
  1068. // Set hostname only in case any of the updates is being performed.
  1069. std::string hostname;
  1070. if (do_fwd || do_rev) {
  1071. hostname = fqdn->getDomainName();
  1072. }
  1073. // Use allocation engine to pick a lease for this client. Allocation engine
  1074. // will try to honour the hint, but it is just a hint - some other address
  1075. // may be used instead. If fake_allocation is set to false, the lease will
  1076. // be inserted into the LeaseMgr as well.
  1077. Lease6Collection old_leases;
  1078. Lease6Collection leases = alloc_engine_->allocateLeases6(subnet, duid,
  1079. ia->getIAID(),
  1080. hint, Lease::TYPE_NA,
  1081. do_fwd, do_rev,
  1082. hostname,
  1083. fake_allocation,
  1084. callout_handle,
  1085. old_leases);
  1086. /// @todo: Handle more than one lease
  1087. Lease6Ptr lease;
  1088. if (!leases.empty()) {
  1089. lease = *leases.begin();
  1090. }
  1091. // Create IA_NA that we will put in the response.
  1092. // Do not use OptionDefinition to create option's instance so
  1093. // as we can initialize IAID using a constructor.
  1094. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_NA, ia->getIAID()));
  1095. if (lease) {
  1096. // We have a lease! Let's wrap its content into IA_NA option
  1097. // with IAADDR suboption.
  1098. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, fake_allocation?
  1099. DHCP6_LEASE_ADVERT:DHCP6_LEASE_ALLOC)
  1100. .arg(lease->addr_.toText())
  1101. .arg(duid?duid->toText():"(no-duid)")
  1102. .arg(ia->getIAID());
  1103. ia_rsp->setT1(subnet->getT1());
  1104. ia_rsp->setT2(subnet->getT2());
  1105. boost::shared_ptr<Option6IAAddr>
  1106. addr(new Option6IAAddr(D6O_IAADDR,
  1107. lease->addr_,
  1108. lease->preferred_lft_,
  1109. lease->valid_lft_));
  1110. ia_rsp->addOption(addr);
  1111. // It would be possible to insert status code=0(success) as well,
  1112. // but this is considered waste of bandwidth as absence of status
  1113. // code is considered a success.
  1114. Lease6Ptr old_lease;
  1115. if (!old_leases.empty()) {
  1116. old_lease = *old_leases.begin();
  1117. }
  1118. // Allocation engine may have returned an existing lease. If so, we
  1119. // have to check that the FQDN settings we provided are the same
  1120. // that were set. If they aren't, we will have to remove existing
  1121. // DNS records and update the lease with the new settings.
  1122. if (!fake_allocation && old_lease &&
  1123. !lease->hasIdenticalFqdn(*old_lease)) {
  1124. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL,
  1125. DHCP6_DDNS_LEASE_ASSIGN_FQDN_CHANGE)
  1126. .arg(old_lease->toText())
  1127. .arg(hostname)
  1128. .arg(do_rev ? "true" : "false")
  1129. .arg(do_fwd ? "true" : "false");
  1130. // Schedule removal of the existing lease.
  1131. createRemovalNameChangeRequest(old_lease);
  1132. }
  1133. } else {
  1134. // Allocation engine did not allocate a lease. The engine logged
  1135. // cause of that failure. The only thing left is to insert
  1136. // status code to pass the sad news to the client.
  1137. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, fake_allocation ?
  1138. DHCP6_LEASE_ADVERT_FAIL : DHCP6_LEASE_ALLOC_FAIL)
  1139. .arg(duid?duid->toText():"(no-duid)")
  1140. .arg(ia->getIAID());
  1141. ia_rsp->addOption(createStatusCode(STATUS_NoAddrsAvail,
  1142. "Sorry, no address could be allocated."));
  1143. }
  1144. return (ia_rsp);
  1145. }
  1146. OptionPtr
  1147. Dhcpv6Srv::assignIA_PD(const Subnet6Ptr& subnet, const DuidPtr& duid,
  1148. const Pkt6Ptr& query, boost::shared_ptr<Option6IA> ia) {
  1149. // Create IA_PD that we will put in the response.
  1150. // Do not use OptionDefinition to create option's instance so
  1151. // as we can initialize IAID using a constructor.
  1152. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_PD, ia->getIAID()));
  1153. // If there is no subnet selected for handling this IA_PD, the only thing to
  1154. // do left is to say that we are sorry, but the user won't get an address.
  1155. // As a convenience, we use a different status text to indicate that
  1156. // (compare to the same status code, but different wording below)
  1157. if (!subnet) {
  1158. // Insert status code NoAddrsAvail.
  1159. ia_rsp->addOption(createStatusCode(STATUS_NoPrefixAvail,
  1160. "Sorry, no subnet available."));
  1161. return (ia_rsp);
  1162. }
  1163. // Check if the client sent us a hint in his IA_PD. Clients may send an
  1164. // address in their IA_NA options as a suggestion (e.g. the last address
  1165. // they used before).
  1166. boost::shared_ptr<Option6IAPrefix> hintOpt =
  1167. boost::dynamic_pointer_cast<Option6IAPrefix>(ia->getOption(D6O_IAPREFIX));
  1168. IOAddress hint("::");
  1169. if (hintOpt) {
  1170. hint = hintOpt->getAddress();
  1171. }
  1172. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_PROCESS_IA_PD_REQUEST)
  1173. .arg(duid ? duid->toText() : "(no-duid)").arg(ia->getIAID())
  1174. .arg(hintOpt ? hint.toText() : "(no hint)");
  1175. // "Fake" allocation is processing of SOLICIT message. We pretend to do an
  1176. // allocation, but we do not put the lease in the database. That is ok,
  1177. // because we do not guarantee that the user will get that exact lease. If
  1178. // the user selects this server to do actual allocation (i.e. sends REQUEST)
  1179. // it should include this hint. That will help us during the actual lease
  1180. // allocation.
  1181. bool fake_allocation = (query->getType() == DHCPV6_SOLICIT);
  1182. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  1183. // Use allocation engine to pick a lease for this client. Allocation engine
  1184. // will try to honour the hint, but it is just a hint - some other address
  1185. // may be used instead. If fake_allocation is set to false, the lease will
  1186. // be inserted into the LeaseMgr as well.
  1187. Lease6Collection old_leases;
  1188. Lease6Collection leases = alloc_engine_->allocateLeases6(subnet, duid,
  1189. ia->getIAID(),
  1190. hint, Lease::TYPE_PD,
  1191. false, false,
  1192. string(),
  1193. fake_allocation,
  1194. callout_handle,
  1195. old_leases);
  1196. if (!leases.empty()) {
  1197. ia_rsp->setT1(subnet->getT1());
  1198. ia_rsp->setT2(subnet->getT2());
  1199. for (Lease6Collection::iterator l = leases.begin();
  1200. l != leases.end(); ++l) {
  1201. // We have a lease! Let's wrap its content into IA_PD option
  1202. // with IAADDR suboption.
  1203. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, fake_allocation ?
  1204. DHCP6_PD_LEASE_ADVERT : DHCP6_PD_LEASE_ALLOC)
  1205. .arg((*l)->addr_.toText())
  1206. .arg(static_cast<int>((*l)->prefixlen_))
  1207. .arg(duid ? duid->toText() : "(no-duid)")
  1208. .arg(ia->getIAID());
  1209. boost::shared_ptr<Option6IAPrefix>
  1210. addr(new Option6IAPrefix(D6O_IAPREFIX, (*l)->addr_,
  1211. (*l)->prefixlen_, (*l)->preferred_lft_,
  1212. (*l)->valid_lft_));
  1213. ia_rsp->addOption(addr);
  1214. }
  1215. // It would be possible to insert status code=0(success) as well,
  1216. // but this is considered waste of bandwidth as absence of status
  1217. // code is considered a success.
  1218. } else {
  1219. // Allocation engine did not allocate a lease. The engine logged
  1220. // cause of that failure. The only thing left is to insert
  1221. // status code to pass the sad news to the client.
  1222. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, fake_allocation ?
  1223. DHCP6_PD_LEASE_ADVERT_FAIL : DHCP6_PD_LEASE_ALLOC_FAIL)
  1224. .arg(duid ? duid->toText() : "(no-duid)")
  1225. .arg(ia->getIAID());
  1226. ia_rsp->addOption(createStatusCode(STATUS_NoPrefixAvail,
  1227. "Sorry, no prefixes could be allocated."));
  1228. }
  1229. return (ia_rsp);
  1230. }
  1231. OptionPtr
  1232. Dhcpv6Srv::renewIA_NA(const Subnet6Ptr& subnet, const DuidPtr& duid,
  1233. const Pkt6Ptr& query, const Pkt6Ptr& answer,
  1234. boost::shared_ptr<Option6IA> ia) {
  1235. if (!subnet) {
  1236. // There's no subnet select for this client. There's nothing to renew.
  1237. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_NA, ia->getIAID()));
  1238. // Insert status code NoAddrsAvail.
  1239. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1240. "Sorry, no known leases for this duid/iaid."));
  1241. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_RENEW_UNKNOWN_SUBNET)
  1242. .arg(duid->toText())
  1243. .arg(ia->getIAID());
  1244. return (ia_rsp);
  1245. }
  1246. Lease6Ptr lease = LeaseMgrFactory::instance().getLease6(Lease::TYPE_NA,
  1247. *duid, ia->getIAID(),
  1248. subnet->getID());
  1249. if (!lease) {
  1250. // client renewing a lease that we don't know about.
  1251. // Create empty IA_NA option with IAID matching the request.
  1252. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_NA, ia->getIAID()));
  1253. // Insert status code NoAddrsAvail.
  1254. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1255. "Sorry, no known leases for this duid/iaid."));
  1256. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_UNKNOWN_RENEW_NA)
  1257. .arg(duid->toText())
  1258. .arg(ia->getIAID())
  1259. .arg(subnet->toText());
  1260. return (ia_rsp);
  1261. }
  1262. // Keep the old data in case the callout tells us to skip update
  1263. Lease6 old_data = *lease;
  1264. // At this point, we have to make make some decisions with respect to the
  1265. // FQDN option that we have generated as a result of receiving client's
  1266. // FQDN. In particular, we have to get to know if the DNS update will be
  1267. // performed or not. It is possible that option is NULL, which is valid
  1268. // condition if client didn't request DNS updates and server didn't force
  1269. // the update.
  1270. bool do_fwd = false;
  1271. bool do_rev = false;
  1272. Option6ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<
  1273. Option6ClientFqdn>(answer->getOption(D6O_CLIENT_FQDN));
  1274. if (fqdn) {
  1275. if (fqdn->getFlag(Option6ClientFqdn::FLAG_S)) {
  1276. do_fwd = true;
  1277. do_rev = true;
  1278. } else if (!fqdn->getFlag(Option6ClientFqdn::FLAG_N)) {
  1279. do_rev = true;
  1280. }
  1281. }
  1282. std::string hostname;
  1283. if (do_fwd || do_rev) {
  1284. hostname = fqdn->getDomainName();
  1285. }
  1286. // If the new FQDN settings have changed for the lease, we need to
  1287. // delete any existing FQDN records for this lease.
  1288. if ((lease->hostname_ != hostname) || (lease->fqdn_fwd_ != do_fwd) ||
  1289. (lease->fqdn_rev_ != do_rev)) {
  1290. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL,
  1291. DHCP6_DDNS_LEASE_RENEW_FQDN_CHANGE)
  1292. .arg(lease->toText())
  1293. .arg(hostname)
  1294. .arg(do_rev ? "true" : "false")
  1295. .arg(do_fwd ? "true" : "false");
  1296. createRemovalNameChangeRequest(lease);
  1297. }
  1298. lease->preferred_lft_ = subnet->getPreferred();
  1299. lease->valid_lft_ = subnet->getValid();
  1300. lease->t1_ = subnet->getT1();
  1301. lease->t2_ = subnet->getT2();
  1302. lease->cltt_ = time(NULL);
  1303. lease->hostname_ = hostname;
  1304. lease->fqdn_fwd_ = do_fwd;
  1305. lease->fqdn_rev_ = do_rev;
  1306. // Create empty IA_NA option with IAID matching the request.
  1307. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_NA, ia->getIAID()));
  1308. ia_rsp->setT1(subnet->getT1());
  1309. ia_rsp->setT2(subnet->getT2());
  1310. boost::shared_ptr<Option6IAAddr> addr(new Option6IAAddr(D6O_IAADDR,
  1311. lease->addr_, lease->preferred_lft_,
  1312. lease->valid_lft_));
  1313. ia_rsp->addOption(addr);
  1314. bool skip = false;
  1315. // Execute all callouts registered for packet6_send
  1316. if (HooksManager::calloutsPresent(Hooks.hook_index_lease6_renew_)) {
  1317. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  1318. // Delete all previous arguments
  1319. callout_handle->deleteAllArguments();
  1320. // Pass the original packet
  1321. callout_handle->setArgument("query6", query);
  1322. // Pass the lease to be updated
  1323. callout_handle->setArgument("lease6", lease);
  1324. // Pass the IA option to be sent in response
  1325. callout_handle->setArgument("ia_na", ia_rsp);
  1326. // Call all installed callouts
  1327. HooksManager::callCallouts(Hooks.hook_index_lease6_renew_, *callout_handle);
  1328. // Callouts decided to skip the next processing step. The next
  1329. // processing step would to actually renew the lease, so skip at this
  1330. // stage means "keep the old lease as it is".
  1331. if (callout_handle->getSkip()) {
  1332. skip = true;
  1333. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_LEASE6_RENEW_SKIP);
  1334. }
  1335. }
  1336. if (!skip) {
  1337. LeaseMgrFactory::instance().updateLease6(lease);
  1338. } else {
  1339. // Copy back the original date to the lease. For MySQL it doesn't make
  1340. // much sense, but for memfile, the Lease6Ptr points to the actual lease
  1341. // in memfile, so the actual update is performed when we manipulate fields
  1342. // of returned Lease6Ptr, the actual updateLease6() is no-op.
  1343. *lease = old_data;
  1344. }
  1345. return (ia_rsp);
  1346. }
  1347. OptionPtr
  1348. Dhcpv6Srv::renewIA_PD(const Subnet6Ptr& subnet, const DuidPtr& duid,
  1349. const Pkt6Ptr& query, boost::shared_ptr<Option6IA> ia) {
  1350. // Let's create a IA_NA response and fill it in later
  1351. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_PD, ia->getIAID()));
  1352. if (!subnet) {
  1353. // Insert status code NoBinding
  1354. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1355. "Sorry, no known leases for this duid/iaid."));
  1356. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_RENEW_UNKNOWN_SUBNET)
  1357. .arg(duid->toText())
  1358. .arg(ia->getIAID());
  1359. return (ia_rsp);
  1360. }
  1361. Lease6Ptr lease = LeaseMgrFactory::instance().getLease6(Lease::TYPE_PD,
  1362. *duid, ia->getIAID(),
  1363. subnet->getID());
  1364. if (!lease) {
  1365. // Client is renewing a lease that we don't know about.
  1366. // Insert status code NoBinding
  1367. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1368. "Sorry, no known leases for this duid/iaid."));
  1369. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_UNKNOWN_RENEW_PD)
  1370. .arg(duid->toText())
  1371. .arg(ia->getIAID())
  1372. .arg(subnet->toText());
  1373. return (ia_rsp);
  1374. }
  1375. // Keep the old data in case the callout tells us to skip update.
  1376. Lease6 old_data = *lease;
  1377. // Do the actual lease update
  1378. lease->preferred_lft_ = subnet->getPreferred();
  1379. lease->valid_lft_ = subnet->getValid();
  1380. lease->t1_ = subnet->getT1();
  1381. lease->t2_ = subnet->getT2();
  1382. lease->cltt_ = time(NULL);
  1383. // Also update IA_PD container with proper T1, T2 values
  1384. ia_rsp->setT1(subnet->getT1());
  1385. ia_rsp->setT2(subnet->getT2());
  1386. boost::shared_ptr<Option6IAPrefix>
  1387. prefix(new Option6IAPrefix(D6O_IAPREFIX, lease->addr_,
  1388. lease->prefixlen_, lease->preferred_lft_,
  1389. lease->valid_lft_));
  1390. ia_rsp->addOption(prefix);
  1391. bool skip = false;
  1392. // Execute all callouts registered for packet6_send
  1393. if (HooksManager::calloutsPresent(Hooks.hook_index_lease6_renew_)) {
  1394. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  1395. // Delete all previous arguments
  1396. callout_handle->deleteAllArguments();
  1397. // Pass the original packet
  1398. callout_handle->setArgument("query6", query);
  1399. // Pass the lease to be updated
  1400. callout_handle->setArgument("lease6", lease);
  1401. // Pass the IA option to be sent in response
  1402. callout_handle->setArgument("ia_pd", ia_rsp);
  1403. // Call all installed callouts
  1404. HooksManager::callCallouts(Hooks.hook_index_lease6_renew_,
  1405. *callout_handle);
  1406. // Remember hook's instruction whether we want to skip update or not
  1407. skip = callout_handle->getSkip();
  1408. }
  1409. if (!skip) {
  1410. LeaseMgrFactory::instance().updateLease6(lease);
  1411. } else {
  1412. // Callouts decided to skip the next processing step. The next
  1413. // processing step would to actually renew the lease, so skip at this
  1414. // stage means "keep the old lease as it is".
  1415. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_LEASE6_RENEW_SKIP);
  1416. // Copy back the original date to the lease. For MySQL it doesn't make
  1417. // much sense, but for memfile, the Lease6Ptr points to the actual lease
  1418. // in memfile, so the actual update is performed when we manipulate
  1419. // fields of returned Lease6Ptr, the actual updateLease6() is no-op.
  1420. *lease = old_data;
  1421. }
  1422. return (ia_rsp);
  1423. }
  1424. void
  1425. Dhcpv6Srv::renewLeases(const Pkt6Ptr& renew, Pkt6Ptr& reply) {
  1426. // We need to renew addresses for all IA_NA options in the client's
  1427. // RENEW message.
  1428. // @todo add support for IA_TA
  1429. // @todo add support for IA_PD
  1430. // We need to select a subnet the client is connected in.
  1431. Subnet6Ptr subnet = selectSubnet(renew);
  1432. if (!subnet) {
  1433. // This particular client is out of luck today. We do not have
  1434. // information about the subnet he is connected to. This likely means
  1435. // misconfiguration of the server (or some relays). We will continue to
  1436. // process this message, but our response will be almost useless: no
  1437. // addresses or prefixes, no subnet specific configuration etc. The only
  1438. // thing this client can get is some global information (like DNS
  1439. // servers).
  1440. LOG_WARN(dhcp6_logger, DHCP6_SUBNET_SELECTION_FAILED)
  1441. .arg(renew->getRemoteAddr().toText())
  1442. .arg(renew->getName());
  1443. } else {
  1444. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL_DATA, DHCP6_SUBNET_SELECTED)
  1445. .arg(subnet->toText());
  1446. }
  1447. // Let's find client's DUID. Client is supposed to include its client-id
  1448. // option almost all the time (the only exception is an anonymous inf-request,
  1449. // but that is mostly a theoretical case). Our allocation engine needs DUID
  1450. // and will refuse to allocate anything to anonymous clients.
  1451. OptionPtr opt_duid = renew->getOption(D6O_CLIENTID);
  1452. if (!opt_duid) {
  1453. // This should not happen. We have checked this before.
  1454. reply->addOption(createStatusCode(STATUS_UnspecFail,
  1455. "You did not include mandatory client-id"));
  1456. return;
  1457. }
  1458. DuidPtr duid(new DUID(opt_duid->getData()));
  1459. for (OptionCollection::iterator opt = renew->options_.begin();
  1460. opt != renew->options_.end(); ++opt) {
  1461. switch (opt->second->getType()) {
  1462. case D6O_IA_NA: {
  1463. OptionPtr answer_opt = renewIA_NA(subnet, duid, renew, reply,
  1464. boost::dynamic_pointer_cast<
  1465. Option6IA>(opt->second));
  1466. if (answer_opt) {
  1467. reply->addOption(answer_opt);
  1468. }
  1469. break;
  1470. }
  1471. case D6O_IA_PD: {
  1472. OptionPtr answer_opt = renewIA_PD(subnet, duid, renew,
  1473. boost::dynamic_pointer_cast<
  1474. Option6IA>(opt->second));
  1475. if (answer_opt) {
  1476. reply->addOption(answer_opt);
  1477. }
  1478. break;
  1479. }
  1480. default:
  1481. break;
  1482. }
  1483. }
  1484. }
  1485. void
  1486. Dhcpv6Srv::releaseLeases(const Pkt6Ptr& release, Pkt6Ptr& reply) {
  1487. // We need to release addresses for all IA_NA options in the client's
  1488. // RELEASE message.
  1489. // @todo Add support for IA_TA
  1490. // @todo Add support for IA_PD
  1491. // @todo Consider supporting more than one address in a single IA_NA.
  1492. // That was envisaged by RFC3315, but it never happened. The only
  1493. // software that supports that is Dibbler, but its author seriously doubts
  1494. // if anyone is really using it. Clients that want more than one address
  1495. // just include more instances of IA_NA options.
  1496. // Let's find client's DUID. Client is supposed to include its client-id
  1497. // option almost all the time (the only exception is an anonymous inf-request,
  1498. // but that is mostly a theoretical case). Our allocation engine needs DUID
  1499. // and will refuse to allocate anything to anonymous clients.
  1500. OptionPtr opt_duid = release->getOption(D6O_CLIENTID);
  1501. if (!opt_duid) {
  1502. // This should not happen. We have checked this before.
  1503. // see sanityCheck() called from processRelease()
  1504. LOG_WARN(dhcp6_logger, DHCP6_RELEASE_MISSING_CLIENTID)
  1505. .arg(release->getRemoteAddr().toText());
  1506. reply->addOption(createStatusCode(STATUS_UnspecFail,
  1507. "You did not include mandatory client-id"));
  1508. return;
  1509. }
  1510. DuidPtr duid(new DUID(opt_duid->getData()));
  1511. // Let's set the status to be success by default. We can override it with
  1512. // error status if needed. The important thing to understand here is that
  1513. // the global status code may be set to success only if all IA options were
  1514. // handled properly. Therefore the releaseIA_NA and releaseIA_PD options
  1515. // may turn the status code to some error, but can't turn it back to success.
  1516. int general_status = STATUS_Success;
  1517. for (OptionCollection::iterator opt = release->options_.begin();
  1518. opt != release->options_.end(); ++opt) {
  1519. switch (opt->second->getType()) {
  1520. case D6O_IA_NA: {
  1521. OptionPtr answer_opt = releaseIA_NA(duid, release, general_status,
  1522. boost::dynamic_pointer_cast<Option6IA>(opt->second));
  1523. if (answer_opt) {
  1524. reply->addOption(answer_opt);
  1525. }
  1526. break;
  1527. }
  1528. case D6O_IA_PD: {
  1529. OptionPtr answer_opt = releaseIA_PD(duid, release, general_status,
  1530. boost::dynamic_pointer_cast<Option6IA>(opt->second));
  1531. if (answer_opt) {
  1532. reply->addOption(answer_opt);
  1533. }
  1534. break;
  1535. }
  1536. // @todo: add support for IA_TA
  1537. default:
  1538. // remaining options are stateless and thus ignored in this context
  1539. ;
  1540. }
  1541. }
  1542. // To be pedantic, we should also include status code in the top-level
  1543. // scope, not just in each IA_NA. See RFC3315, section 18.2.6.
  1544. // This behavior will likely go away in RFC3315bis.
  1545. reply->addOption(createStatusCode(general_status,
  1546. "Summary status for all processed IA_NAs"));
  1547. }
  1548. OptionPtr
  1549. Dhcpv6Srv::releaseIA_NA(const DuidPtr& duid, const Pkt6Ptr& query,
  1550. int& general_status, boost::shared_ptr<Option6IA> ia) {
  1551. // Release can be done in one of two ways:
  1552. // Approach 1: extract address from client's IA_NA and see if it belongs
  1553. // to this particular client.
  1554. // Approach 2: find a subnet for this client, get a lease for
  1555. // this subnet/duid/iaid and check if its content matches to what the
  1556. // client is asking us to release.
  1557. //
  1558. // This method implements approach 1.
  1559. // That's our response
  1560. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_NA, ia->getIAID()));
  1561. boost::shared_ptr<Option6IAAddr> release_addr = boost::dynamic_pointer_cast<Option6IAAddr>
  1562. (ia->getOption(D6O_IAADDR));
  1563. if (!release_addr) {
  1564. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1565. "You did not include an address in your RELEASE"));
  1566. general_status = STATUS_NoBinding;
  1567. return (ia_rsp);
  1568. }
  1569. Lease6Ptr lease = LeaseMgrFactory::instance().getLease6(Lease::TYPE_NA,
  1570. release_addr->getAddress());
  1571. if (!lease) {
  1572. // client releasing a lease that we don't know about.
  1573. // Insert status code NoAddrsAvail.
  1574. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1575. "Sorry, no known leases for this duid/iaid, can't release."));
  1576. general_status = STATUS_NoBinding;
  1577. LOG_INFO(dhcp6_logger, DHCP6_UNKNOWN_RELEASE_NA)
  1578. .arg(duid->toText())
  1579. .arg(ia->getIAID());
  1580. return (ia_rsp);
  1581. }
  1582. if (!lease->duid_) {
  1583. // Something is gravely wrong here. We do have a lease, but it does not
  1584. // have mandatory DUID information attached. Someone was messing with our
  1585. // database.
  1586. LOG_ERROR(dhcp6_logger, DHCP6_LEASE_NA_WITHOUT_DUID)
  1587. .arg(release_addr->getAddress().toText());
  1588. general_status = STATUS_UnspecFail;
  1589. ia_rsp->addOption(createStatusCode(STATUS_UnspecFail,
  1590. "Database consistency check failed when trying to RELEASE"));
  1591. return (ia_rsp);
  1592. }
  1593. if (*duid != *(lease->duid_)) {
  1594. // Sorry, it's not your address. You can't release it.
  1595. LOG_INFO(dhcp6_logger, DHCP6_RELEASE_NA_FAIL_WRONG_DUID)
  1596. .arg(duid->toText())
  1597. .arg(release_addr->getAddress().toText())
  1598. .arg(lease->duid_->toText());
  1599. general_status = STATUS_NoBinding;
  1600. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1601. "This address does not belong to you, you can't release it"));
  1602. return (ia_rsp);
  1603. }
  1604. if (ia->getIAID() != lease->iaid_) {
  1605. // This address belongs to this client, but to a different IA
  1606. LOG_WARN(dhcp6_logger, DHCP6_RELEASE_PD_FAIL_WRONG_IAID)
  1607. .arg(duid->toText())
  1608. .arg(release_addr->getAddress().toText())
  1609. .arg(lease->iaid_)
  1610. .arg(ia->getIAID());
  1611. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1612. "This is your address, but you used wrong IAID"));
  1613. general_status = STATUS_NoBinding;
  1614. return (ia_rsp);
  1615. }
  1616. // It is not necessary to check if the address matches as we used
  1617. // getLease6(addr) method that is supposed to return a proper lease.
  1618. bool skip = false;
  1619. // Execute all callouts registered for packet6_send
  1620. if (HooksManager::calloutsPresent(Hooks.hook_index_lease6_release_)) {
  1621. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  1622. // Delete all previous arguments
  1623. callout_handle->deleteAllArguments();
  1624. // Pass the original packet
  1625. callout_handle->setArgument("query6", query);
  1626. // Pass the lease to be updated
  1627. callout_handle->setArgument("lease6", lease);
  1628. // Call all installed callouts
  1629. HooksManager::callCallouts(Hooks.hook_index_lease6_release_, *callout_handle);
  1630. // Callouts decided to skip the next processing step. The next
  1631. // processing step would to send the packet, so skip at this
  1632. // stage means "drop response".
  1633. if (callout_handle->getSkip()) {
  1634. skip = true;
  1635. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_LEASE6_RELEASE_NA_SKIP);
  1636. }
  1637. }
  1638. // Ok, we've passed all checks. Let's release this address.
  1639. bool success = false; // was the removal operation succeessful?
  1640. if (!skip) {
  1641. success = LeaseMgrFactory::instance().deleteLease(lease->addr_);
  1642. }
  1643. // Here the success should be true if we removed lease successfully
  1644. // and false if skip flag was set or the removal failed for whatever reason
  1645. if (!success) {
  1646. ia_rsp->addOption(createStatusCode(STATUS_UnspecFail,
  1647. "Server failed to release a lease"));
  1648. LOG_ERROR(dhcp6_logger, DHCP6_RELEASE_NA_FAIL)
  1649. .arg(lease->addr_.toText())
  1650. .arg(duid->toText())
  1651. .arg(lease->iaid_);
  1652. general_status = STATUS_UnspecFail;
  1653. return (ia_rsp);
  1654. } else {
  1655. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_RELEASE_NA)
  1656. .arg(lease->addr_.toText())
  1657. .arg(duid->toText())
  1658. .arg(lease->iaid_);
  1659. ia_rsp->addOption(createStatusCode(STATUS_Success,
  1660. "Lease released. Thank you, please come again."));
  1661. // Check if a lease has flags indicating that the FQDN update has
  1662. // been performed. If so, create NameChangeRequest which removes
  1663. // the entries.
  1664. createRemovalNameChangeRequest(lease);
  1665. return (ia_rsp);
  1666. }
  1667. }
  1668. OptionPtr
  1669. Dhcpv6Srv::releaseIA_PD(const DuidPtr& duid, const Pkt6Ptr& query,
  1670. int& general_status, boost::shared_ptr<Option6IA> ia) {
  1671. // Release can be done in one of two ways:
  1672. // Approach 1: extract address from client's IA_NA and see if it belongs
  1673. // to this particular client.
  1674. // Approach 2: find a subnet for this client, get a lease for
  1675. // this subnet/duid/iaid and check if its content matches to what the
  1676. // client is asking us to release.
  1677. //
  1678. // This method implements approach 1.
  1679. // That's our response. We will fill it in as we check the lease to be
  1680. // released.
  1681. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_PD, ia->getIAID()));
  1682. boost::shared_ptr<Option6IAPrefix> release_prefix =
  1683. boost::dynamic_pointer_cast<Option6IAPrefix>(ia->getOption(D6O_IAPREFIX));
  1684. if (!release_prefix) {
  1685. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1686. "You did not include a prefix in your RELEASE"));
  1687. general_status = STATUS_NoBinding;
  1688. return (ia_rsp);
  1689. }
  1690. Lease6Ptr lease = LeaseMgrFactory::instance().getLease6(Lease::TYPE_PD,
  1691. release_prefix->getAddress());
  1692. if (!lease) {
  1693. // Client releasing a lease that we don't know about.
  1694. // Insert status code NoBinding.
  1695. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1696. "Sorry, no known leases for this duid/iaid, can't release."));
  1697. general_status = STATUS_NoBinding;
  1698. LOG_INFO(dhcp6_logger, DHCP6_UNKNOWN_RELEASE_PD)
  1699. .arg(duid->toText())
  1700. .arg(ia->getIAID());
  1701. return (ia_rsp);
  1702. }
  1703. if (!lease->duid_) {
  1704. // Something is gravely wrong here. We do have a lease, but it does not
  1705. // have mandatory DUID information attached. Someone was messing with our
  1706. // database.
  1707. LOG_ERROR(dhcp6_logger, DHCP6_LEASE_PD_WITHOUT_DUID)
  1708. .arg(release_prefix->getAddress().toText());
  1709. general_status = STATUS_UnspecFail;
  1710. ia_rsp->addOption(createStatusCode(STATUS_UnspecFail,
  1711. "Database consistency check failed when trying to RELEASE"));
  1712. return (ia_rsp);
  1713. }
  1714. if (*duid != *(lease->duid_)) {
  1715. // Sorry, it's not your address. You can't release it.
  1716. LOG_INFO(dhcp6_logger, DHCP6_RELEASE_PD_FAIL_WRONG_DUID)
  1717. .arg(duid->toText())
  1718. .arg(release_prefix->getAddress().toText())
  1719. .arg(lease->duid_->toText());
  1720. general_status = STATUS_NoBinding;
  1721. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1722. "This address does not belong to you, you can't release it"));
  1723. return (ia_rsp);
  1724. }
  1725. if (ia->getIAID() != lease->iaid_) {
  1726. // This address belongs to this client, but to a different IA
  1727. LOG_WARN(dhcp6_logger, DHCP6_RELEASE_PD_FAIL_WRONG_IAID)
  1728. .arg(duid->toText())
  1729. .arg(release_prefix->getAddress().toText())
  1730. .arg(lease->iaid_)
  1731. .arg(ia->getIAID());
  1732. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1733. "This is your address, but you used wrong IAID"));
  1734. general_status = STATUS_NoBinding;
  1735. return (ia_rsp);
  1736. }
  1737. // It is not necessary to check if the address matches as we used
  1738. // getLease6(addr) method that is supposed to return a proper lease.
  1739. bool skip = false;
  1740. // Execute all callouts registered for packet6_send
  1741. if (HooksManager::calloutsPresent(Hooks.hook_index_lease6_release_)) {
  1742. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  1743. // Delete all previous arguments
  1744. callout_handle->deleteAllArguments();
  1745. // Pass the original packet
  1746. callout_handle->setArgument("query6", query);
  1747. // Pass the lease to be updated
  1748. callout_handle->setArgument("lease6", lease);
  1749. // Call all installed callouts
  1750. HooksManager::callCallouts(Hooks.hook_index_lease6_release_, *callout_handle);
  1751. skip = callout_handle->getSkip();
  1752. }
  1753. // Ok, we've passed all checks. Let's release this prefix.
  1754. bool success = false; // was the removal operation succeessful?
  1755. if (!skip) {
  1756. success = LeaseMgrFactory::instance().deleteLease(lease->addr_);
  1757. } else {
  1758. // Callouts decided to skip the next processing step. The next
  1759. // processing step would to send the packet, so skip at this
  1760. // stage means "drop response".
  1761. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_LEASE6_RELEASE_PD_SKIP);
  1762. }
  1763. // Here the success should be true if we removed lease successfully
  1764. // and false if skip flag was set or the removal failed for whatever reason
  1765. if (!success) {
  1766. ia_rsp->addOption(createStatusCode(STATUS_UnspecFail,
  1767. "Server failed to release a lease"));
  1768. LOG_ERROR(dhcp6_logger, DHCP6_RELEASE_PD_FAIL)
  1769. .arg(lease->addr_.toText())
  1770. .arg(duid->toText())
  1771. .arg(lease->iaid_);
  1772. general_status = STATUS_UnspecFail;
  1773. } else {
  1774. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_RELEASE_PD)
  1775. .arg(lease->addr_.toText())
  1776. .arg(duid->toText())
  1777. .arg(lease->iaid_);
  1778. ia_rsp->addOption(createStatusCode(STATUS_Success,
  1779. "Lease released. Thank you, please come again."));
  1780. }
  1781. return (ia_rsp);
  1782. }
  1783. Pkt6Ptr
  1784. Dhcpv6Srv::processSolicit(const Pkt6Ptr& solicit) {
  1785. sanityCheck(solicit, MANDATORY, FORBIDDEN);
  1786. Pkt6Ptr advertise(new Pkt6(DHCPV6_ADVERTISE, solicit->getTransid()));
  1787. copyDefaultOptions(solicit, advertise);
  1788. appendDefaultOptions(solicit, advertise);
  1789. appendRequestedOptions(solicit, advertise);
  1790. appendRequestedVendorOptions(solicit, advertise);
  1791. processClientFqdn(solicit, advertise);
  1792. assignLeases(solicit, advertise);
  1793. // Note, that we don't create NameChangeRequests here because we don't
  1794. // perform DNS Updates for Solicit. Client must send Request to update
  1795. // DNS.
  1796. generateFqdn(advertise);
  1797. return (advertise);
  1798. }
  1799. Pkt6Ptr
  1800. Dhcpv6Srv::processRequest(const Pkt6Ptr& request) {
  1801. sanityCheck(request, MANDATORY, MANDATORY);
  1802. Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, request->getTransid()));
  1803. copyDefaultOptions(request, reply);
  1804. appendDefaultOptions(request, reply);
  1805. appendRequestedOptions(request, reply);
  1806. appendRequestedVendorOptions(request, reply);
  1807. processClientFqdn(request, reply);
  1808. assignLeases(request, reply);
  1809. generateFqdn(reply);
  1810. createNameChangeRequests(reply);
  1811. return (reply);
  1812. }
  1813. Pkt6Ptr
  1814. Dhcpv6Srv::processRenew(const Pkt6Ptr& renew) {
  1815. sanityCheck(renew, MANDATORY, MANDATORY);
  1816. Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, renew->getTransid()));
  1817. copyDefaultOptions(renew, reply);
  1818. appendDefaultOptions(renew, reply);
  1819. appendRequestedOptions(renew, reply);
  1820. processClientFqdn(renew, reply);
  1821. renewLeases(renew, reply);
  1822. generateFqdn(reply);
  1823. createNameChangeRequests(reply);
  1824. return (reply);
  1825. }
  1826. Pkt6Ptr
  1827. Dhcpv6Srv::processRebind(const Pkt6Ptr& rebind) {
  1828. /// @todo: Implement this
  1829. Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, rebind->getTransid()));
  1830. return reply;
  1831. }
  1832. Pkt6Ptr
  1833. Dhcpv6Srv::processConfirm(const Pkt6Ptr& confirm) {
  1834. /// @todo: Implement this
  1835. Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, confirm->getTransid()));
  1836. return reply;
  1837. }
  1838. Pkt6Ptr
  1839. Dhcpv6Srv::processRelease(const Pkt6Ptr& release) {
  1840. sanityCheck(release, MANDATORY, MANDATORY);
  1841. Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, release->getTransid()));
  1842. copyDefaultOptions(release, reply);
  1843. appendDefaultOptions(release, reply);
  1844. releaseLeases(release, reply);
  1845. // @todo If client sent a release and we should remove outstanding
  1846. // DNS records.
  1847. return (reply);
  1848. }
  1849. Pkt6Ptr
  1850. Dhcpv6Srv::processDecline(const Pkt6Ptr& decline) {
  1851. /// @todo: Implement this
  1852. Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, decline->getTransid()));
  1853. return reply;
  1854. }
  1855. Pkt6Ptr
  1856. Dhcpv6Srv::processInfRequest(const Pkt6Ptr& infRequest) {
  1857. /// @todo: Implement this
  1858. Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, infRequest->getTransid()));
  1859. return reply;
  1860. }
  1861. void
  1862. Dhcpv6Srv::openActiveSockets(const uint16_t port) {
  1863. IfaceMgr::instance().closeSockets();
  1864. // Get the reference to the collection of interfaces. This reference should be
  1865. // valid as long as the program is run because IfaceMgr is a singleton.
  1866. // Therefore we can safely iterate over instances of all interfaces and modify
  1867. // their flags. Here we modify flags which indicate wheter socket should be
  1868. // open for a particular interface or not.
  1869. const IfaceMgr::IfaceCollection& ifaces = IfaceMgr::instance().getIfaces();
  1870. for (IfaceMgr::IfaceCollection::const_iterator iface = ifaces.begin();
  1871. iface != ifaces.end(); ++iface) {
  1872. Iface* iface_ptr = IfaceMgr::instance().getIface(iface->getName());
  1873. if (iface_ptr == NULL) {
  1874. isc_throw(isc::Unexpected, "Interface Manager returned NULL"
  1875. << " instance of the interface when DHCPv6 server was"
  1876. << " trying to reopen sockets after reconfiguration");
  1877. }
  1878. if (CfgMgr::instance().isActiveIface(iface->getName())) {
  1879. iface_ptr->inactive6_ = false;
  1880. LOG_INFO(dhcp6_logger, DHCP6_ACTIVATE_INTERFACE)
  1881. .arg(iface->getFullName());
  1882. } else {
  1883. // For deactivating interface, it should be sufficient to log it
  1884. // on the debug level because it is more useful to know what
  1885. // interface is activated which is logged on the info level.
  1886. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC,
  1887. DHCP6_DEACTIVATE_INTERFACE).arg(iface->getName());
  1888. iface_ptr->inactive6_ = true;
  1889. }
  1890. iface_ptr->clearUnicasts();
  1891. const IOAddress* unicast = CfgMgr::instance().getUnicast(iface->getName());
  1892. if (unicast) {
  1893. LOG_INFO(dhcp6_logger, DHCP6_SOCKET_UNICAST).arg(unicast->toText())
  1894. .arg(iface->getName());
  1895. iface_ptr->addUnicast(*unicast);
  1896. }
  1897. }
  1898. // Let's reopen active sockets. openSockets6 will check internally whether
  1899. // sockets are marked active or inactive.
  1900. // @todo Optimization: we should not reopen all sockets but rather select
  1901. // those that have been affected by the new configuration.
  1902. isc::dhcp::IfaceMgrErrorMsgCallback error_handler =
  1903. boost::bind(&Dhcpv6Srv::ifaceMgrSocket6ErrorHandler, _1);
  1904. if (!IfaceMgr::instance().openSockets6(port, error_handler)) {
  1905. LOG_WARN(dhcp6_logger, DHCP6_NO_SOCKETS_OPEN);
  1906. }
  1907. }
  1908. size_t
  1909. Dhcpv6Srv::unpackOptions(const OptionBuffer& buf,
  1910. const std::string& option_space,
  1911. isc::dhcp::OptionCollection& options,
  1912. size_t* relay_msg_offset,
  1913. size_t* relay_msg_len) {
  1914. size_t offset = 0;
  1915. size_t length = buf.size();
  1916. OptionDefContainer option_defs;
  1917. if (option_space == "dhcp6") {
  1918. // Get the list of stdandard option definitions.
  1919. option_defs = LibDHCP::getOptionDefs(Option::V6);
  1920. } else if (!option_space.empty()) {
  1921. OptionDefContainerPtr option_defs_ptr =
  1922. CfgMgr::instance().getOptionDefs(option_space);
  1923. if (option_defs_ptr != NULL) {
  1924. option_defs = *option_defs_ptr;
  1925. }
  1926. }
  1927. // Get the search index #1. It allows to search for option definitions
  1928. // using option code.
  1929. const OptionDefContainerTypeIndex& idx = option_defs.get<1>();
  1930. // The buffer being read comprises a set of options, each starting with
  1931. // a two-byte type code and a two-byte length field.
  1932. while (offset + 4 <= length) {
  1933. uint16_t opt_type = isc::util::readUint16(&buf[offset]);
  1934. offset += 2;
  1935. uint16_t opt_len = isc::util::readUint16(&buf[offset]);
  1936. offset += 2;
  1937. if (offset + opt_len > length) {
  1938. // @todo: consider throwing exception here.
  1939. return (offset);
  1940. }
  1941. if (opt_type == D6O_RELAY_MSG && relay_msg_offset && relay_msg_len) {
  1942. // remember offset of the beginning of the relay-msg option
  1943. *relay_msg_offset = offset;
  1944. *relay_msg_len = opt_len;
  1945. // do not create that relay-msg option
  1946. offset += opt_len;
  1947. continue;
  1948. }
  1949. // Get all definitions with the particular option code. Note that option
  1950. // code is non-unique within this container however at this point we
  1951. // expect to get one option definition with the particular code. If more
  1952. // are returned we report an error.
  1953. const OptionDefContainerTypeRange& range = idx.equal_range(opt_type);
  1954. // Get the number of returned option definitions for the option code.
  1955. size_t num_defs = distance(range.first, range.second);
  1956. OptionPtr opt;
  1957. if (num_defs > 1) {
  1958. // Multiple options of the same code are not supported right now!
  1959. isc_throw(isc::Unexpected, "Internal error: multiple option definitions"
  1960. " for option type " << opt_type << " returned. Currently it is not"
  1961. " supported to initialize multiple option definitions"
  1962. " for the same option code. This will be supported once"
  1963. " support for option spaces is implemented");
  1964. } else if (num_defs == 0) {
  1965. // @todo Don't crash if definition does not exist because only a few
  1966. // option definitions are initialized right now. In the future
  1967. // we will initialize definitions for all options and we will
  1968. // remove this elseif. For now, return generic option.
  1969. opt = OptionPtr(new Option(Option::V6, opt_type,
  1970. buf.begin() + offset,
  1971. buf.begin() + offset + opt_len));
  1972. opt->setEncapsulatedSpace("dhcp6");
  1973. } else {
  1974. // The option definition has been found. Use it to create
  1975. // the option instance from the provided buffer chunk.
  1976. const OptionDefinitionPtr& def = *(range.first);
  1977. assert(def);
  1978. opt = def->optionFactory(Option::V6, opt_type,
  1979. buf.begin() + offset,
  1980. buf.begin() + offset + opt_len,
  1981. boost::bind(&Dhcpv6Srv::unpackOptions, this, _1, _2,
  1982. _3, _4, _5));
  1983. }
  1984. // add option to options
  1985. options.insert(std::make_pair(opt_type, opt));
  1986. offset += opt_len;
  1987. }
  1988. return (offset);
  1989. }
  1990. void
  1991. Dhcpv6Srv::ifaceMgrSocket6ErrorHandler(const std::string& errmsg) {
  1992. // Log the reason for socket opening failure and return.
  1993. LOG_WARN(dhcp6_logger, DHCP6_OPEN_SOCKET_FAIL).arg(errmsg);
  1994. }
  1995. void
  1996. Dhcpv6Srv::generateFqdn(const Pkt6Ptr& answer) {
  1997. if (!answer) {
  1998. isc_throw(isc::Unexpected, "an instance of the object encapsulating"
  1999. " a message must not be NULL when generating FQDN");
  2000. }
  2001. // It is likely that client haven't included the FQDN option. In such case,
  2002. // FQDN option will be NULL. Also, there is nothing to do if the option
  2003. // is present and conveys the non-empty FQDN.
  2004. Option6ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<
  2005. Option6ClientFqdn>(answer->getOption(D6O_CLIENT_FQDN));
  2006. if (!fqdn || !fqdn->getDomainName().empty()) {
  2007. return;
  2008. }
  2009. // Get the first IA_NA acquired for the client.
  2010. OptionPtr ia = answer->getOption(D6O_IA_NA);
  2011. if (!ia) {
  2012. return;
  2013. }
  2014. // If it has any IAAddr, use the first one to generate unique FQDN.
  2015. Option6IAAddrPtr iaaddr = boost::dynamic_pointer_cast<
  2016. Option6IAAddr>(ia->getOption(D6O_IAADDR));
  2017. if (!iaaddr) {
  2018. return;
  2019. }
  2020. // Get the IPv6 address acquired by the client.
  2021. IOAddress addr = iaaddr->getAddress();
  2022. std::string hostname = addr.toText();
  2023. // Colons may not be ok for FQDNs so let's replace them with hyphens.
  2024. std::replace(hostname.begin(), hostname.end(), ':', '-');
  2025. std::ostringstream stream;
  2026. // The final FQDN consists of the partial domain name and the suffix.
  2027. // For example, if the acquired address is 2001:db8:1::2, the generated
  2028. // FQDN may be:
  2029. // host-2001-db8:1--2.example.com.
  2030. // where prefix 'host' should be configurable. The domain name suffix
  2031. // should also be configurable.
  2032. stream << "host-" << hostname << "." << FQDN_PARTIAL_SUFFIX << ".";
  2033. try {
  2034. // The lease has been acquired but the FQDN for this lease hasn't
  2035. // been updated in the lease database. We now have new FQDN
  2036. // generated, so the lease database has to be updated here.
  2037. // However, never update lease database for Advertise, just send
  2038. // our notion of client's FQDN in the Client FQDN option.
  2039. if (answer->getType() != DHCPV6_ADVERTISE) {
  2040. Lease6Ptr lease =
  2041. LeaseMgrFactory::instance().getLease6(Lease::TYPE_NA, addr);
  2042. if (lease) {
  2043. lease->hostname_ = stream.str();
  2044. }
  2045. LeaseMgrFactory::instance().updateLease6(lease);
  2046. }
  2047. // Set the generated FQDN in the Client FQDN option.
  2048. fqdn->setDomainName(stream.str(), Option6ClientFqdn::FULL);
  2049. } catch (const Exception& ex) {
  2050. LOG_ERROR(dhcp6_logger, DHCP6_NAME_GEN_UPDATE_FAIL)
  2051. .arg(hostname)
  2052. .arg(ex.what());
  2053. }
  2054. }
  2055. };
  2056. };