dhcp6_srv.cc 103 KB

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