dhcp6_srv.cc 116 KB

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