dhcp6_srv.cc 91 KB

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