dhcp6_srv.cc 120 KB

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