dhcp6_srv.cc 98 KB

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