dhcp6_srv.cc 105 KB

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