dhcp6_srv.cc 111 KB

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