dhcp6_srv.cc 103 KB

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