dhcp6_srv.cc 94 KB

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