dhcp6_srv.cc 131 KB

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