dhcp6_srv.cc 110 KB

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