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