dhcp6_srv.cc 120 KB

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