dhcp6_srv.cc 124 KB

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