dhcp6_srv.cc 117 KB

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