dhcp6_srv.cc 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414
  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::sanityCheck(const Pkt6Ptr& pkt, RequirementLevel clientid,
  633. RequirementLevel serverid) {
  634. OptionCollection client_ids = pkt->getOptions(D6O_CLIENTID);
  635. switch (clientid) {
  636. case MANDATORY:
  637. if (client_ids.size() != 1) {
  638. isc_throw(RFCViolation, "Exactly 1 client-id option expected in "
  639. << pkt->getName() << ", but " << client_ids.size()
  640. << " received");
  641. }
  642. break;
  643. case OPTIONAL:
  644. if (client_ids.size() > 1) {
  645. isc_throw(RFCViolation, "Too many (" << client_ids.size()
  646. << ") client-id options received in " << pkt->getName());
  647. }
  648. break;
  649. case FORBIDDEN:
  650. // doesn't make sense - client-id is always allowed
  651. break;
  652. }
  653. OptionCollection server_ids = pkt->getOptions(D6O_SERVERID);
  654. switch (serverid) {
  655. case FORBIDDEN:
  656. if (!server_ids.empty()) {
  657. isc_throw(RFCViolation, "Server-id option was not expected, but "
  658. << server_ids.size() << " received in " << pkt->getName());
  659. }
  660. break;
  661. case MANDATORY:
  662. if (server_ids.size() != 1) {
  663. isc_throw(RFCViolation, "Invalid number of server-id options received ("
  664. << server_ids.size() << "), exactly 1 expected in message "
  665. << pkt->getName());
  666. }
  667. break;
  668. case OPTIONAL:
  669. if (server_ids.size() > 1) {
  670. isc_throw(RFCViolation, "Too many (" << server_ids.size()
  671. << ") server-id options received in " << pkt->getName());
  672. }
  673. }
  674. }
  675. Subnet6Ptr
  676. Dhcpv6Srv::selectSubnet(const Pkt6Ptr& question) {
  677. Subnet6Ptr subnet;
  678. if (question->relay_info_.empty()) {
  679. // This is a direct (non-relayed) message
  680. // Try to find a subnet if received packet from a directly connected client
  681. subnet = CfgMgr::instance().getSubnet6(question->getIface());
  682. if (!subnet) {
  683. // If no subnet was found, try to find it based on remote address
  684. subnet = CfgMgr::instance().getSubnet6(question->getRemoteAddr());
  685. }
  686. } else {
  687. // This is a relayed message
  688. OptionPtr interface_id = question->getAnyRelayOption(D6O_INTERFACE_ID,
  689. Pkt6::RELAY_GET_FIRST);
  690. if (interface_id) {
  691. subnet = CfgMgr::instance().getSubnet6(interface_id);
  692. }
  693. if (!subnet) {
  694. // If no interface-id was specified (or not configured on server), let's
  695. // try address matching
  696. IOAddress link_addr = question->relay_info_.back().linkaddr_;
  697. // if relay filled in link_addr field, then let's use it
  698. if (link_addr != IOAddress("::")) {
  699. subnet = CfgMgr::instance().getSubnet6(link_addr);
  700. }
  701. }
  702. }
  703. // Let's execute all callouts registered for subnet6_receive
  704. if (HooksManager::calloutsPresent(Hooks.hook_index_subnet6_select_)) {
  705. CalloutHandlePtr callout_handle = getCalloutHandle(question);
  706. // We're reusing callout_handle from previous calls
  707. callout_handle->deleteAllArguments();
  708. // Set new arguments
  709. callout_handle->setArgument("query6", question);
  710. callout_handle->setArgument("subnet6", subnet);
  711. // We pass pointer to const collection for performance reasons.
  712. // Otherwise we would get a non-trivial performance penalty each
  713. // time subnet6_select is called.
  714. callout_handle->setArgument("subnet6collection", CfgMgr::instance().getSubnets6());
  715. // Call user (and server-side) callouts
  716. HooksManager::callCallouts(Hooks.hook_index_subnet6_select_, *callout_handle);
  717. // Callouts decided to skip this step. This means that no subnet will be
  718. // selected. Packet processing will continue, but it will be severly limited
  719. // (i.e. only global options will be assigned)
  720. if (callout_handle->getSkip()) {
  721. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_SUBNET6_SELECT_SKIP);
  722. return (Subnet6Ptr());
  723. }
  724. // Use whatever subnet was specified by the callout
  725. callout_handle->getArgument("subnet6", subnet);
  726. }
  727. return (subnet);
  728. }
  729. void
  730. Dhcpv6Srv::assignLeases(const Pkt6Ptr& question, Pkt6Ptr& answer,
  731. const Option6ClientFqdnPtr& fqdn) {
  732. // We need to allocate addresses for all IA_NA options in the client's
  733. // question (i.e. SOLICIT or REQUEST) message.
  734. // @todo add support for IA_TA
  735. // We need to select a subnet the client is connected in.
  736. Subnet6Ptr subnet = selectSubnet(question);
  737. if (!subnet) {
  738. // This particular client is out of luck today. We do not have
  739. // information about the subnet he is connected to. This likely means
  740. // misconfiguration of the server (or some relays). We will continue to
  741. // process this message, but our response will be almost useless: no
  742. // addresses or prefixes, no subnet specific configuration etc. The only
  743. // thing this client can get is some global information (like DNS
  744. // servers).
  745. LOG_WARN(dhcp6_logger, DHCP6_SUBNET_SELECTION_FAILED)
  746. .arg(question->getRemoteAddr().toText())
  747. .arg(question->getName());
  748. } else {
  749. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL_DATA, DHCP6_SUBNET_SELECTED)
  750. .arg(subnet->toText());
  751. }
  752. // @todo: We should implement Option6Duid some day, but we can do without it
  753. // just fine for now
  754. // Let's find client's DUID. Client is supposed to include its client-id
  755. // option almost all the time (the only exception is an anonymous inf-request,
  756. // but that is mostly a theoretical case). Our allocation engine needs DUID
  757. // and will refuse to allocate anything to anonymous clients.
  758. DuidPtr duid;
  759. OptionPtr opt_duid = question->getOption(D6O_CLIENTID);
  760. if (opt_duid) {
  761. duid = DuidPtr(new DUID(opt_duid->getData()));
  762. } else {
  763. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC, DHCP6_CLIENTID_MISSING);
  764. // Let's drop the message. This client is not sane.
  765. isc_throw(RFCViolation, "Mandatory client-id is missing in received message");
  766. }
  767. // Now that we have all information about the client, let's iterate over all
  768. // received options and handle IA_NA options one by one and store our
  769. // responses in answer message (ADVERTISE or REPLY).
  770. //
  771. // @todo: expand this to cover IA_PD and IA_TA once we implement support for
  772. // prefix delegation and temporary addresses.
  773. for (OptionCollection::iterator opt = question->options_.begin();
  774. opt != question->options_.end(); ++opt) {
  775. switch (opt->second->getType()) {
  776. case D6O_IA_NA: {
  777. OptionPtr answer_opt = assignIA_NA(subnet, duid, question,
  778. boost::dynamic_pointer_cast<
  779. Option6IA>(opt->second),
  780. fqdn);
  781. if (answer_opt) {
  782. answer->addOption(answer_opt);
  783. }
  784. break;
  785. }
  786. case D6O_IA_PD: {
  787. OptionPtr answer_opt = assignIA_PD(subnet, duid, question,
  788. boost::dynamic_pointer_cast<
  789. Option6IA>(opt->second));
  790. if (answer_opt) {
  791. answer->addOption(answer_opt);
  792. }
  793. }
  794. default:
  795. break;
  796. }
  797. }
  798. }
  799. Option6ClientFqdnPtr
  800. Dhcpv6Srv::processClientFqdn(const Pkt6Ptr& question) {
  801. // Get Client FQDN Option from the client's message. If this option hasn't
  802. // been included, do nothing.
  803. Option6ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<
  804. Option6ClientFqdn>(question->getOption(D6O_CLIENT_FQDN));
  805. if (!fqdn) {
  806. return (fqdn);
  807. }
  808. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL,
  809. DHCP6_DDNS_RECEIVE_FQDN).arg(fqdn->toText());
  810. // Prepare the FQDN option which will be included in the response to
  811. // the client.
  812. Option6ClientFqdnPtr fqdn_resp(new Option6ClientFqdn(*fqdn));
  813. // RFC 4704, section 6. - all flags set to 0.
  814. fqdn_resp->resetFlags();
  815. // Conditions when N flag has to be set to indicate that server will not
  816. // perform DNS updates:
  817. // 1. Updates are globally disabled,
  818. // 2. Client requested no update and server respects it,
  819. // 3. Client requested that the AAAA update is delegated to the client but
  820. // server neither respects delegation of updates nor it is configured
  821. // to send update on its own when client requested delegation.
  822. if (!FQDN_ENABLE_UPDATE ||
  823. (fqdn->getFlag(Option6ClientFqdn::FLAG_N) &&
  824. !FQDN_OVERRIDE_NO_UPDATE) ||
  825. (!fqdn->getFlag(Option6ClientFqdn::FLAG_S) &&
  826. !FQDN_ALLOW_CLIENT_UPDATE && !FQDN_OVERRIDE_CLIENT_UPDATE)) {
  827. fqdn_resp->setFlag(Option6ClientFqdn::FLAG_N, true);
  828. // Conditions when S flag is set to indicate that server will perform
  829. // DNS update on its own:
  830. // 1. Client requested that server performs DNS update and DNS updates are
  831. // globally enabled
  832. // 2. Client requested that server delegates AAAA update to the client but
  833. // server doesn't respect delegation and it is configured to perform
  834. // an update on its own when client requested delegation.
  835. } else if (fqdn->getFlag(Option6ClientFqdn::FLAG_S) ||
  836. (!fqdn->getFlag(Option6ClientFqdn::FLAG_S) &&
  837. !FQDN_ALLOW_CLIENT_UPDATE && FQDN_OVERRIDE_CLIENT_UPDATE)) {
  838. fqdn_resp->setFlag(Option6ClientFqdn::FLAG_S, true);
  839. }
  840. // Server MUST set the O flag if it has overridden the client's setting
  841. // of S flag.
  842. if (fqdn->getFlag(Option6ClientFqdn::FLAG_S) !=
  843. fqdn_resp->getFlag(Option6ClientFqdn::FLAG_S)) {
  844. fqdn_resp->setFlag(Option6ClientFqdn::FLAG_O, true);
  845. }
  846. // If client supplied partial or empty domain-name, server should
  847. // generate one.
  848. if (fqdn->getDomainNameType() == Option6ClientFqdn::PARTIAL) {
  849. std::ostringstream name;
  850. if (fqdn->getDomainName().empty()) {
  851. name << FQDN_GENERATED_PARTIAL_NAME;
  852. } else {
  853. name << fqdn->getDomainName();
  854. }
  855. name << "." << FQDN_PARTIAL_SUFFIX;
  856. fqdn_resp->setDomainName(name.str(), Option6ClientFqdn::FULL);
  857. // Server may be configured to replace a name supplied by a client,
  858. // even if client supplied fully qualified domain-name.
  859. } else if (FQDN_REPLACE_CLIENT_NAME) {
  860. std::ostringstream name;
  861. name << FQDN_GENERATED_PARTIAL_NAME << "." << FQDN_PARTIAL_SUFFIX;
  862. fqdn_resp->setDomainName(name.str(), Option6ClientFqdn::FULL);
  863. }
  864. // Return the FQDN option which can be included in the server's response.
  865. // Note that it doesn't have to be included, if client didn't request
  866. // it using ORO and server is not configured to always include it.
  867. return (fqdn_resp);
  868. }
  869. void
  870. Dhcpv6Srv::appendClientFqdn(const Pkt6Ptr& question,
  871. Pkt6Ptr& answer,
  872. const Option6ClientFqdnPtr& fqdn) {
  873. // If FQDN is NULL, it means that client did not request DNS Update, plus
  874. // server doesn't force updates.
  875. if (fqdn) {
  876. return;
  877. }
  878. // Server sends back the FQDN option to the client if client has requested
  879. // it using Option Request Option. However, server may be configured to
  880. // send the FQDN option in its response, regardless whether client requested
  881. // it or not.
  882. bool include_fqdn = FQDN_ALWAYS_INCLUDE;
  883. if (!include_fqdn) {
  884. OptionUint16ArrayPtr oro = boost::dynamic_pointer_cast<
  885. OptionUint16Array>(question->getOption(D6O_ORO));
  886. if (oro) {
  887. const std::vector<uint16_t>& values = oro->getValues();
  888. for (int i = 0; i < values.size(); ++i) {
  889. if (values[i] == D6O_CLIENT_FQDN) {
  890. include_fqdn = true;
  891. }
  892. }
  893. }
  894. }
  895. if (include_fqdn) {
  896. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL,
  897. DHCP6_DDNS_SEND_FQDN).arg(fqdn->toText());
  898. answer->addOption(fqdn);
  899. }
  900. }
  901. void
  902. Dhcpv6Srv::createNameChangeRequests(const Pkt6Ptr& answer,
  903. const Option6ClientFqdnPtr& opt_fqdn) {
  904. // It is likely that client haven't included the FQDN option in the message
  905. // and server is not configured to always update DNS. In such cases,
  906. // FQDN option will be NULL. This is valid state, so we simply return.
  907. if (!opt_fqdn) {
  908. return;
  909. }
  910. // The response message instance is always required. For instance it
  911. // holds the Client Identifier. It is a programming error if supplied
  912. // message is NULL.
  913. if (!answer) {
  914. isc_throw(isc::Unexpected, "an instance of the object"
  915. << " encapsulating server's message must not be"
  916. << " NULL when creating DNS NameChangeRequest");
  917. }
  918. // Get the Client Id. It is mandatory and a function creating a response
  919. // would have thrown an exception if it was missing. Thus throwning
  920. // Unexpected if it is missing as it is a programming error.
  921. OptionPtr opt_duid = answer->getOption(D6O_CLIENTID);
  922. if (!opt_duid) {
  923. isc_throw(isc::Unexpected,
  924. "client identifier is required when creating a new"
  925. " DNS NameChangeRequest");
  926. }
  927. DuidPtr duid = DuidPtr(new DUID(opt_duid->getData()));
  928. // Get the FQDN in the on-wire format. It will be needed to compute
  929. // DHCID.
  930. OutputBuffer name_buf(1);
  931. opt_fqdn->packDomainName(name_buf);
  932. const uint8_t* name_data = static_cast<const uint8_t*>(name_buf.getData());
  933. // @todo currently D2Dhcid accepts a vector holding FQDN.
  934. // However, it will be faster if we used a pointer name_data.
  935. std::vector<uint8_t> buf_vec(name_data, name_data + name_buf.getLength());
  936. // Compute DHCID from Client Identifier and FQDN.
  937. isc::dhcp_ddns::D2Dhcid dhcid(*duid, buf_vec);
  938. // Get all IAs from the answer. For each IA, holding an address we will
  939. // create a corresponding NameChangeRequest.
  940. OptionCollection answer_ias = answer->getOptions(D6O_IA_NA);
  941. for (OptionCollection::const_iterator answer_ia =
  942. answer_ias.begin(); answer_ia != answer_ias.end(); ++answer_ia) {
  943. // @todo IA_NA may contain multiple addresses. We should process
  944. // each address individually. Currently we get only one.
  945. Option6IAAddrPtr iaaddr = boost::static_pointer_cast<
  946. Option6IAAddr>(answer_ia->second->getOption(D6O_IAADDR));
  947. // We need an address to create a name-to-address mapping.
  948. // If address is missing for any reason, go to the next IA.
  949. if (!iaaddr) {
  950. continue;
  951. }
  952. // Create new NameChangeRequest. Use the domain name from the FQDN.
  953. // This is an FQDN included in the response to the client, so it
  954. // holds a fully qualified domain-name already (not partial).
  955. // Get the IP address from the lease. Also, use the S flag to determine
  956. // if forward change should be performed. This flag will always be
  957. // set if server has taken responsibility for the forward update.
  958. NameChangeRequest ncr(isc::dhcp_ddns::CHG_ADD,
  959. opt_fqdn->getFlag(Option6ClientFqdn::FLAG_S),
  960. true, opt_fqdn->getDomainName(),
  961. iaaddr->getAddress().toText(),
  962. dhcid, 0, iaaddr->getValid());
  963. // Add the request to the queue. This queue will be read elsewhere in
  964. // the code and all requests from this queue will be sent to the
  965. // D2 module.
  966. name_change_reqs_.push(ncr);
  967. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL,
  968. DHCP6_DDNS_CREATE_ADD_NAME_CHANGE_REQUEST).arg(ncr.toText());
  969. }
  970. }
  971. void
  972. Dhcpv6Srv::createRemovalNameChangeRequest(const Lease6Ptr& lease) {
  973. // If we haven't performed a DNS Update when lease was acquired,
  974. // there is nothing to do here.
  975. if (!lease->fqdn_fwd_ && !lease->fqdn_rev_) {
  976. return;
  977. }
  978. // When lease was added into a database the host name should have
  979. // been added. The hostname can be empty if someone messed up in the
  980. // lease data base and removed the hostname.
  981. if (lease->hostname_.empty()) {
  982. LOG_ERROR(dhcp6_logger, DHCP6_DDNS_REMOVE_EMPTY_HOSTNAME)
  983. .arg(lease->addr_.toText());
  984. return;
  985. }
  986. // If hostname is non-empty, try to convert it to wire format so as
  987. // DHCID can be computed from it. This may throw an exception if hostname
  988. // has invalid format. Again, this should be only possible in case of
  989. // manual intervention in the database. Note that the last parameter
  990. // passed to the writeFqdn function forces conversion of the FQDN
  991. // to lower case. This is required by the RFC4701, section 3.5.
  992. // The DHCID computation is further in this function.
  993. std::vector<uint8_t> hostname_wire;
  994. try {
  995. OptionDataTypeUtil::writeFqdn(lease->hostname_, hostname_wire, true);
  996. } catch (const Exception& ex) {
  997. LOG_ERROR(dhcp6_logger, DHCP6_DDNS_REMOVE_INVALID_HOSTNAME)
  998. .arg(lease->hostname_);
  999. return;
  1000. }
  1001. // DUID must have been checked already by the caller of this function.
  1002. // Let's be on the safe side and make sure it is non-NULL and throw
  1003. // an exception if it is NULL.
  1004. if (!lease->duid_) {
  1005. isc_throw(isc::Unexpected, "DUID must be set when creating"
  1006. << " NameChangeRequest for DNS records removal for "
  1007. << lease->addr_.toText());
  1008. }
  1009. isc::dhcp_ddns::D2Dhcid dhcid(*lease->duid_, hostname_wire);
  1010. // Create a NameChangeRequest to remove the entry.
  1011. NameChangeRequest ncr(isc::dhcp_ddns::CHG_REMOVE,
  1012. lease->fqdn_fwd_, lease->fqdn_rev_,
  1013. lease->hostname_,
  1014. lease->addr_.toText(),
  1015. dhcid, 0, lease->valid_lft_);
  1016. name_change_reqs_.push(ncr);
  1017. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL,
  1018. DHCP6_DDNS_CREATE_REMOVE_NAME_CHANGE_REQUEST).arg(ncr.toText());
  1019. }
  1020. void
  1021. Dhcpv6Srv::sendNameChangeRequests() {
  1022. while (!name_change_reqs_.empty()) {
  1023. // @todo Once next NameChangeRequest is picked from the queue
  1024. // we should send it to the bind10-dhcp_ddns module. Currently we
  1025. // just drop it.
  1026. name_change_reqs_.pop();
  1027. }
  1028. }
  1029. OptionPtr
  1030. Dhcpv6Srv::assignIA_NA(const Subnet6Ptr& subnet, const DuidPtr& duid,
  1031. const Pkt6Ptr& query, boost::shared_ptr<Option6IA> ia,
  1032. const Option6ClientFqdnPtr& fqdn) {
  1033. // If there is no subnet selected for handling this IA_NA, the only thing to do left is
  1034. // to say that we are sorry, but the user won't get an address. As a convenience, we
  1035. // use a different status text to indicate that (compare to the same status code,
  1036. // but different wording below)
  1037. if (!subnet) {
  1038. // Create empty IA_NA option with IAID matching the request.
  1039. // Note that we don't use OptionDefinition class to create this option.
  1040. // This is because we prefer using a constructor of Option6IA that
  1041. // initializes IAID. Otherwise we would have to use setIAID() after
  1042. // creation of the option which has some performance implications.
  1043. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_NA, ia->getIAID()));
  1044. // Insert status code NoAddrsAvail.
  1045. ia_rsp->addOption(createStatusCode(STATUS_NoAddrsAvail, "Sorry, no subnet available."));
  1046. return (ia_rsp);
  1047. }
  1048. // Check if the client sent us a hint in his IA_NA. Clients may send an
  1049. // address in their IA_NA options as a suggestion (e.g. the last address
  1050. // they used before).
  1051. boost::shared_ptr<Option6IAAddr> hintOpt = boost::dynamic_pointer_cast<Option6IAAddr>
  1052. (ia->getOption(D6O_IAADDR));
  1053. IOAddress hint("::");
  1054. if (hintOpt) {
  1055. hint = hintOpt->getAddress();
  1056. }
  1057. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_PROCESS_IA_NA_REQUEST)
  1058. .arg(duid?duid->toText():"(no-duid)").arg(ia->getIAID())
  1059. .arg(hintOpt?hint.toText():"(no hint)");
  1060. // "Fake" allocation is processing of SOLICIT message. We pretend to do an
  1061. // allocation, but we do not put the lease in the database. That is ok,
  1062. // because we do not guarantee that the user will get that exact lease. If
  1063. // the user selects this server to do actual allocation (i.e. sends REQUEST)
  1064. // it should include this hint. That will help us during the actual lease
  1065. // allocation.
  1066. bool fake_allocation = false;
  1067. if (query->getType() == DHCPV6_SOLICIT) {
  1068. /// @todo: Check if we support rapid commit
  1069. fake_allocation = true;
  1070. }
  1071. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  1072. // At this point, we have to make make some decisions with respect to the
  1073. // FQDN option that we have generated as a result of receiving client's
  1074. // FQDN. In particular, we have to get to know if the DNS update will be
  1075. // performed or not. It is possible that option is NULL, which is valid
  1076. // condition if client didn't request DNS updates and server didn't force
  1077. // the update.
  1078. bool do_fwd = false;
  1079. bool do_rev = false;
  1080. if (fqdn) {
  1081. // Flag S must not coexist with flag N being set to 1, so if S=1
  1082. // server takes responsibility for both reverse and forward updates.
  1083. // Otherwise, we have to check N.
  1084. if (fqdn->getFlag(Option6ClientFqdn::FLAG_S)) {
  1085. do_fwd = true;
  1086. do_rev = true;
  1087. } else if (!fqdn->getFlag(Option6ClientFqdn::FLAG_N)) {
  1088. do_rev = true;
  1089. }
  1090. }
  1091. // Set hostname only in case any of the updates is being performed.
  1092. std::string hostname;
  1093. if (do_fwd || do_rev) {
  1094. hostname = fqdn->getDomainName();
  1095. }
  1096. // Use allocation engine to pick a lease for this client. Allocation engine
  1097. // will try to honour the hint, but it is just a hint - some other address
  1098. // may be used instead. If fake_allocation is set to false, the lease will
  1099. // be inserted into the LeaseMgr as well.
  1100. Lease6Collection leases = alloc_engine_->allocateLeases6(subnet, duid,
  1101. ia->getIAID(),
  1102. hint, Lease::TYPE_NA,
  1103. do_fwd, do_rev,
  1104. hostname,
  1105. fake_allocation,
  1106. callout_handle);
  1107. /// @todo: Handle more than one lease
  1108. Lease6Ptr lease;
  1109. if (!leases.empty()) {
  1110. lease = *leases.begin();
  1111. }
  1112. // Create IA_NA that we will put in the response.
  1113. // Do not use OptionDefinition to create option's instance so
  1114. // as we can initialize IAID using a constructor.
  1115. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_NA, ia->getIAID()));
  1116. if (lease) {
  1117. // We have a lease! Let's wrap its content into IA_NA option
  1118. // with IAADDR suboption.
  1119. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, fake_allocation?
  1120. DHCP6_LEASE_ADVERT:DHCP6_LEASE_ALLOC)
  1121. .arg(lease->addr_.toText())
  1122. .arg(duid?duid->toText():"(no-duid)")
  1123. .arg(ia->getIAID());
  1124. ia_rsp->setT1(subnet->getT1());
  1125. ia_rsp->setT2(subnet->getT2());
  1126. boost::shared_ptr<Option6IAAddr>
  1127. addr(new Option6IAAddr(D6O_IAADDR,
  1128. lease->addr_,
  1129. lease->preferred_lft_,
  1130. lease->valid_lft_));
  1131. ia_rsp->addOption(addr);
  1132. // It would be possible to insert status code=0(success) as well,
  1133. // but this is considered waste of bandwidth as absence of status
  1134. // code is considered a success.
  1135. // Allocation engine may have returned an existing lease. If so, we
  1136. // have to check that the FQDN settings we provided are the same
  1137. // that were set. If they aren't, we will have to remove existing
  1138. // DNS records and update the lease with the new settings.
  1139. if ((lease->hostname_ != hostname) || (lease->fqdn_fwd_ != do_fwd) ||
  1140. (lease->fqdn_rev_ != do_rev)) {
  1141. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL,
  1142. DHCP6_DDNS_LEASE_ASSIGN_FQDN_CHANGE)
  1143. .arg(lease->toText())
  1144. .arg(hostname)
  1145. .arg(do_rev ? "true" : "false")
  1146. .arg(do_fwd ? "true" : "false");
  1147. // Schedule removal of the existing lease.
  1148. createRemovalNameChangeRequest(lease);
  1149. // Set the new lease properties and update.
  1150. lease->hostname_ = hostname;
  1151. lease->fqdn_fwd_ = do_fwd;
  1152. lease->fqdn_rev_ = do_rev;
  1153. LeaseMgrFactory::instance().updateLease6(lease);
  1154. }
  1155. } else {
  1156. // Allocation engine did not allocate a lease. The engine logged
  1157. // cause of that failure. The only thing left is to insert
  1158. // status code to pass the sad news to the client.
  1159. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, fake_allocation ?
  1160. DHCP6_LEASE_ADVERT_FAIL : DHCP6_LEASE_ALLOC_FAIL)
  1161. .arg(duid?duid->toText():"(no-duid)")
  1162. .arg(ia->getIAID());
  1163. ia_rsp->addOption(createStatusCode(STATUS_NoAddrsAvail,
  1164. "Sorry, no address could be allocated."));
  1165. }
  1166. return (ia_rsp);
  1167. }
  1168. OptionPtr
  1169. Dhcpv6Srv::assignIA_PD(const Subnet6Ptr& subnet, const DuidPtr& duid,
  1170. const Pkt6Ptr& query, boost::shared_ptr<Option6IA> ia) {
  1171. // Create IA_PD that we will put in the response.
  1172. // Do not use OptionDefinition to create option's instance so
  1173. // as we can initialize IAID using a constructor.
  1174. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_PD, ia->getIAID()));
  1175. // If there is no subnet selected for handling this IA_PD, the only thing to
  1176. // do left is to say that we are sorry, but the user won't get an address.
  1177. // As a convenience, we use a different status text to indicate that
  1178. // (compare to the same status code, but different wording below)
  1179. if (!subnet) {
  1180. // Insert status code NoAddrsAvail.
  1181. ia_rsp->addOption(createStatusCode(STATUS_NoPrefixAvail,
  1182. "Sorry, no subnet available."));
  1183. return (ia_rsp);
  1184. }
  1185. // Check if the client sent us a hint in his IA_PD. Clients may send an
  1186. // address in their IA_NA options as a suggestion (e.g. the last address
  1187. // they used before).
  1188. boost::shared_ptr<Option6IAPrefix> hintOpt =
  1189. boost::dynamic_pointer_cast<Option6IAPrefix>(ia->getOption(D6O_IAPREFIX));
  1190. IOAddress hint("::");
  1191. if (hintOpt) {
  1192. hint = hintOpt->getAddress();
  1193. }
  1194. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_PROCESS_IA_PD_REQUEST)
  1195. .arg(duid ? duid->toText() : "(no-duid)").arg(ia->getIAID())
  1196. .arg(hintOpt ? hint.toText() : "(no hint)");
  1197. // "Fake" allocation is processing of SOLICIT message. We pretend to do an
  1198. // allocation, but we do not put the lease in the database. That is ok,
  1199. // because we do not guarantee that the user will get that exact lease. If
  1200. // the user selects this server to do actual allocation (i.e. sends REQUEST)
  1201. // it should include this hint. That will help us during the actual lease
  1202. // allocation.
  1203. bool fake_allocation = (query->getType() == DHCPV6_SOLICIT);
  1204. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  1205. // Use allocation engine to pick a lease for this client. Allocation engine
  1206. // will try to honour the hint, but it is just a hint - some other address
  1207. // may be used instead. If fake_allocation is set to false, the lease will
  1208. // be inserted into the LeaseMgr as well.
  1209. Lease6Collection leases = alloc_engine_->allocateLeases6(subnet, duid,
  1210. ia->getIAID(),
  1211. hint, Lease::TYPE_PD,
  1212. false, false,
  1213. string(),
  1214. fake_allocation,
  1215. callout_handle);
  1216. if (!leases.empty()) {
  1217. ia_rsp->setT1(subnet->getT1());
  1218. ia_rsp->setT2(subnet->getT2());
  1219. for (Lease6Collection::iterator l = leases.begin();
  1220. l != leases.end(); ++l) {
  1221. // We have a lease! Let's wrap its content into IA_PD option
  1222. // with IAADDR suboption.
  1223. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, fake_allocation ?
  1224. DHCP6_PD_LEASE_ADVERT : DHCP6_PD_LEASE_ALLOC)
  1225. .arg((*l)->addr_.toText())
  1226. .arg(static_cast<int>((*l)->prefixlen_))
  1227. .arg(duid ? duid->toText() : "(no-duid)")
  1228. .arg(ia->getIAID());
  1229. boost::shared_ptr<Option6IAPrefix>
  1230. addr(new Option6IAPrefix(D6O_IAPREFIX, (*l)->addr_,
  1231. (*l)->prefixlen_, (*l)->preferred_lft_,
  1232. (*l)->valid_lft_));
  1233. ia_rsp->addOption(addr);
  1234. }
  1235. // It would be possible to insert status code=0(success) as well,
  1236. // but this is considered waste of bandwidth as absence of status
  1237. // code is considered a success.
  1238. } else {
  1239. // Allocation engine did not allocate a lease. The engine logged
  1240. // cause of that failure. The only thing left is to insert
  1241. // status code to pass the sad news to the client.
  1242. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, fake_allocation ?
  1243. DHCP6_PD_LEASE_ADVERT_FAIL : DHCP6_PD_LEASE_ALLOC_FAIL)
  1244. .arg(duid ? duid->toText() : "(no-duid)")
  1245. .arg(ia->getIAID());
  1246. ia_rsp->addOption(createStatusCode(STATUS_NoPrefixAvail,
  1247. "Sorry, no prefixes could be allocated."));
  1248. }
  1249. return (ia_rsp);
  1250. }
  1251. OptionPtr
  1252. Dhcpv6Srv::renewIA_NA(const Subnet6Ptr& subnet, const DuidPtr& duid,
  1253. const Pkt6Ptr& query, boost::shared_ptr<Option6IA> ia,
  1254. const Option6ClientFqdnPtr& fqdn) {
  1255. if (!subnet) {
  1256. // There's no subnet select for this client. There's nothing to renew.
  1257. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_NA, ia->getIAID()));
  1258. // Insert status code NoAddrsAvail.
  1259. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1260. "Sorry, no known leases for this duid/iaid."));
  1261. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_RENEW_UNKNOWN_SUBNET)
  1262. .arg(duid->toText())
  1263. .arg(ia->getIAID());
  1264. return (ia_rsp);
  1265. }
  1266. Lease6Ptr lease = LeaseMgrFactory::instance().getLease6(Lease::TYPE_NA,
  1267. *duid, ia->getIAID(),
  1268. subnet->getID());
  1269. if (!lease) {
  1270. // client renewing a lease that we don't know about.
  1271. // Create empty IA_NA option with IAID matching the request.
  1272. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_NA, ia->getIAID()));
  1273. // Insert status code NoAddrsAvail.
  1274. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1275. "Sorry, no known leases for this duid/iaid."));
  1276. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_UNKNOWN_RENEW_NA)
  1277. .arg(duid->toText())
  1278. .arg(ia->getIAID())
  1279. .arg(subnet->toText());
  1280. return (ia_rsp);
  1281. }
  1282. // Keep the old data in case the callout tells us to skip update
  1283. Lease6 old_data = *lease;
  1284. // At this point, we have to make make some decisions with respect to the
  1285. // FQDN option that we have generated as a result of receiving client's
  1286. // FQDN. In particular, we have to get to know if the DNS update will be
  1287. // performed or not. It is possible that option is NULL, which is valid
  1288. // condition if client didn't request DNS updates and server didn't force
  1289. // the update.
  1290. bool do_fwd = false;
  1291. bool do_rev = false;
  1292. if (fqdn) {
  1293. if (fqdn->getFlag(Option6ClientFqdn::FLAG_S)) {
  1294. do_fwd = true;
  1295. do_rev = true;
  1296. } else if (!fqdn->getFlag(Option6ClientFqdn::FLAG_N)) {
  1297. do_rev = true;
  1298. }
  1299. }
  1300. std::string hostname;
  1301. if (do_fwd || do_rev) {
  1302. hostname = fqdn->getDomainName();
  1303. }
  1304. // If the new FQDN settings have changed for the lease, we need to
  1305. // delete any existing FQDN records for this lease.
  1306. if ((lease->hostname_ != hostname) || (lease->fqdn_fwd_ != do_fwd) ||
  1307. (lease->fqdn_rev_ != do_rev)) {
  1308. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL,
  1309. DHCP6_DDNS_LEASE_RENEW_FQDN_CHANGE)
  1310. .arg(lease->toText())
  1311. .arg(hostname)
  1312. .arg(do_rev ? "true" : "false")
  1313. .arg(do_fwd ? "true" : "false");
  1314. createRemovalNameChangeRequest(lease);
  1315. }
  1316. lease->preferred_lft_ = subnet->getPreferred();
  1317. lease->valid_lft_ = subnet->getValid();
  1318. lease->t1_ = subnet->getT1();
  1319. lease->t2_ = subnet->getT2();
  1320. lease->cltt_ = time(NULL);
  1321. lease->hostname_ = hostname;
  1322. lease->fqdn_fwd_ = do_fwd;
  1323. lease->fqdn_rev_ = do_rev;
  1324. // Create empty IA_NA option with IAID matching the request.
  1325. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_NA, ia->getIAID()));
  1326. ia_rsp->setT1(subnet->getT1());
  1327. ia_rsp->setT2(subnet->getT2());
  1328. boost::shared_ptr<Option6IAAddr> addr(new Option6IAAddr(D6O_IAADDR,
  1329. lease->addr_, lease->preferred_lft_,
  1330. lease->valid_lft_));
  1331. ia_rsp->addOption(addr);
  1332. bool skip = false;
  1333. // Execute all callouts registered for packet6_send
  1334. if (HooksManager::calloutsPresent(Hooks.hook_index_lease6_renew_)) {
  1335. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  1336. // Delete all previous arguments
  1337. callout_handle->deleteAllArguments();
  1338. // Pass the original packet
  1339. callout_handle->setArgument("query6", query);
  1340. // Pass the lease to be updated
  1341. callout_handle->setArgument("lease6", lease);
  1342. // Pass the IA option to be sent in response
  1343. callout_handle->setArgument("ia_na", ia_rsp);
  1344. // Call all installed callouts
  1345. HooksManager::callCallouts(Hooks.hook_index_lease6_renew_, *callout_handle);
  1346. // Callouts decided to skip the next processing step. The next
  1347. // processing step would to actually renew the lease, so skip at this
  1348. // stage means "keep the old lease as it is".
  1349. if (callout_handle->getSkip()) {
  1350. skip = true;
  1351. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_LEASE6_RENEW_SKIP);
  1352. }
  1353. }
  1354. if (!skip) {
  1355. LeaseMgrFactory::instance().updateLease6(lease);
  1356. } else {
  1357. // Copy back the original date to the lease. For MySQL it doesn't make
  1358. // much sense, but for memfile, the Lease6Ptr points to the actual lease
  1359. // in memfile, so the actual update is performed when we manipulate fields
  1360. // of returned Lease6Ptr, the actual updateLease6() is no-op.
  1361. *lease = old_data;
  1362. }
  1363. return (ia_rsp);
  1364. }
  1365. OptionPtr
  1366. Dhcpv6Srv::renewIA_PD(const Subnet6Ptr& subnet, const DuidPtr& duid,
  1367. const Pkt6Ptr& query, boost::shared_ptr<Option6IA> ia) {
  1368. // Let's create a IA_NA response and fill it in later
  1369. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_PD, ia->getIAID()));
  1370. if (!subnet) {
  1371. // Insert status code NoBinding
  1372. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1373. "Sorry, no known leases for this duid/iaid."));
  1374. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_RENEW_UNKNOWN_SUBNET)
  1375. .arg(duid->toText())
  1376. .arg(ia->getIAID());
  1377. return (ia_rsp);
  1378. }
  1379. Lease6Ptr lease = LeaseMgrFactory::instance().getLease6(Lease::TYPE_PD,
  1380. *duid, ia->getIAID(),
  1381. subnet->getID());
  1382. if (!lease) {
  1383. // Client is renewing a lease that we don't know about.
  1384. // Insert status code NoBinding
  1385. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1386. "Sorry, no known leases for this duid/iaid."));
  1387. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_UNKNOWN_RENEW_PD)
  1388. .arg(duid->toText())
  1389. .arg(ia->getIAID())
  1390. .arg(subnet->toText());
  1391. return (ia_rsp);
  1392. }
  1393. // Keep the old data in case the callout tells us to skip update.
  1394. Lease6 old_data = *lease;
  1395. // Do the actual lease update
  1396. lease->preferred_lft_ = subnet->getPreferred();
  1397. lease->valid_lft_ = subnet->getValid();
  1398. lease->t1_ = subnet->getT1();
  1399. lease->t2_ = subnet->getT2();
  1400. lease->cltt_ = time(NULL);
  1401. // Also update IA_PD container with proper T1, T2 values
  1402. ia_rsp->setT1(subnet->getT1());
  1403. ia_rsp->setT2(subnet->getT2());
  1404. boost::shared_ptr<Option6IAPrefix>
  1405. prefix(new Option6IAPrefix(D6O_IAPREFIX, lease->addr_,
  1406. lease->prefixlen_, lease->preferred_lft_,
  1407. lease->valid_lft_));
  1408. ia_rsp->addOption(prefix);
  1409. bool skip = false;
  1410. // Execute all callouts registered for packet6_send
  1411. if (HooksManager::calloutsPresent(Hooks.hook_index_lease6_renew_)) {
  1412. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  1413. // Delete all previous arguments
  1414. callout_handle->deleteAllArguments();
  1415. // Pass the original packet
  1416. callout_handle->setArgument("query6", query);
  1417. // Pass the lease to be updated
  1418. callout_handle->setArgument("lease6", lease);
  1419. // Pass the IA option to be sent in response
  1420. callout_handle->setArgument("ia_pd", ia_rsp);
  1421. // Call all installed callouts
  1422. HooksManager::callCallouts(Hooks.hook_index_lease6_renew_,
  1423. *callout_handle);
  1424. // Remember hook's instruction whether we want to skip update or not
  1425. skip = callout_handle->getSkip();
  1426. }
  1427. if (!skip) {
  1428. LeaseMgrFactory::instance().updateLease6(lease);
  1429. } else {
  1430. // Callouts decided to skip the next processing step. The next
  1431. // processing step would to actually renew the lease, so skip at this
  1432. // stage means "keep the old lease as it is".
  1433. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_LEASE6_RENEW_SKIP);
  1434. // Copy back the original date to the lease. For MySQL it doesn't make
  1435. // much sense, but for memfile, the Lease6Ptr points to the actual lease
  1436. // in memfile, so the actual update is performed when we manipulate
  1437. // fields of returned Lease6Ptr, the actual updateLease6() is no-op.
  1438. *lease = old_data;
  1439. }
  1440. return (ia_rsp);
  1441. }
  1442. void
  1443. Dhcpv6Srv::renewLeases(const Pkt6Ptr& renew, Pkt6Ptr& reply,
  1444. const Option6ClientFqdnPtr& fqdn) {
  1445. // We need to renew addresses for all IA_NA options in the client's
  1446. // RENEW message.
  1447. // @todo add support for IA_TA
  1448. // @todo add support for IA_PD
  1449. // We need to select a subnet the client is connected in.
  1450. Subnet6Ptr subnet = selectSubnet(renew);
  1451. if (!subnet) {
  1452. // This particular client is out of luck today. We do not have
  1453. // information about the subnet he is connected to. This likely means
  1454. // misconfiguration of the server (or some relays). We will continue to
  1455. // process this message, but our response will be almost useless: no
  1456. // addresses or prefixes, no subnet specific configuration etc. The only
  1457. // thing this client can get is some global information (like DNS
  1458. // servers).
  1459. LOG_WARN(dhcp6_logger, DHCP6_SUBNET_SELECTION_FAILED)
  1460. .arg(renew->getRemoteAddr().toText())
  1461. .arg(renew->getName());
  1462. } else {
  1463. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL_DATA, DHCP6_SUBNET_SELECTED)
  1464. .arg(subnet->toText());
  1465. }
  1466. // Let's find client's DUID. Client is supposed to include its client-id
  1467. // option almost all the time (the only exception is an anonymous inf-request,
  1468. // but that is mostly a theoretical case). Our allocation engine needs DUID
  1469. // and will refuse to allocate anything to anonymous clients.
  1470. OptionPtr opt_duid = renew->getOption(D6O_CLIENTID);
  1471. if (!opt_duid) {
  1472. // This should not happen. We have checked this before.
  1473. reply->addOption(createStatusCode(STATUS_UnspecFail,
  1474. "You did not include mandatory client-id"));
  1475. return;
  1476. }
  1477. DuidPtr duid(new DUID(opt_duid->getData()));
  1478. for (OptionCollection::iterator opt = renew->options_.begin();
  1479. opt != renew->options_.end(); ++opt) {
  1480. switch (opt->second->getType()) {
  1481. case D6O_IA_NA: {
  1482. OptionPtr answer_opt = renewIA_NA(subnet, duid, renew,
  1483. boost::dynamic_pointer_cast<
  1484. Option6IA>(opt->second),
  1485. fqdn);
  1486. if (answer_opt) {
  1487. reply->addOption(answer_opt);
  1488. }
  1489. break;
  1490. }
  1491. case D6O_IA_PD: {
  1492. OptionPtr answer_opt = renewIA_PD(subnet, duid, renew,
  1493. boost::dynamic_pointer_cast<
  1494. Option6IA>(opt->second));
  1495. if (answer_opt) {
  1496. reply->addOption(answer_opt);
  1497. }
  1498. break;
  1499. }
  1500. default:
  1501. break;
  1502. }
  1503. }
  1504. }
  1505. void
  1506. Dhcpv6Srv::releaseLeases(const Pkt6Ptr& release, Pkt6Ptr& reply) {
  1507. // We need to release addresses for all IA_NA options in the client's
  1508. // RELEASE message.
  1509. // @todo Add support for IA_TA
  1510. // @todo Add support for IA_PD
  1511. // @todo Consider supporting more than one address in a single IA_NA.
  1512. // That was envisaged by RFC3315, but it never happened. The only
  1513. // software that supports that is Dibbler, but its author seriously doubts
  1514. // if anyone is really using it. Clients that want more than one address
  1515. // just include more instances of IA_NA options.
  1516. // Let's find client's DUID. Client is supposed to include its client-id
  1517. // option almost all the time (the only exception is an anonymous inf-request,
  1518. // but that is mostly a theoretical case). Our allocation engine needs DUID
  1519. // and will refuse to allocate anything to anonymous clients.
  1520. OptionPtr opt_duid = release->getOption(D6O_CLIENTID);
  1521. if (!opt_duid) {
  1522. // This should not happen. We have checked this before.
  1523. // see sanityCheck() called from processRelease()
  1524. LOG_WARN(dhcp6_logger, DHCP6_RELEASE_MISSING_CLIENTID)
  1525. .arg(release->getRemoteAddr().toText());
  1526. reply->addOption(createStatusCode(STATUS_UnspecFail,
  1527. "You did not include mandatory client-id"));
  1528. return;
  1529. }
  1530. DuidPtr duid(new DUID(opt_duid->getData()));
  1531. // Let's set the status to be success by default. We can override it with
  1532. // error status if needed. The important thing to understand here is that
  1533. // the global status code may be set to success only if all IA options were
  1534. // handled properly. Therefore the releaseIA_NA and releaseIA_PD options
  1535. // may turn the status code to some error, but can't turn it back to success.
  1536. int general_status = STATUS_Success;
  1537. for (OptionCollection::iterator opt = release->options_.begin();
  1538. opt != release->options_.end(); ++opt) {
  1539. switch (opt->second->getType()) {
  1540. case D6O_IA_NA: {
  1541. OptionPtr answer_opt = releaseIA_NA(duid, release, general_status,
  1542. boost::dynamic_pointer_cast<Option6IA>(opt->second));
  1543. if (answer_opt) {
  1544. reply->addOption(answer_opt);
  1545. }
  1546. break;
  1547. }
  1548. case D6O_IA_PD: {
  1549. OptionPtr answer_opt = releaseIA_PD(duid, release, general_status,
  1550. boost::dynamic_pointer_cast<Option6IA>(opt->second));
  1551. if (answer_opt) {
  1552. reply->addOption(answer_opt);
  1553. }
  1554. break;
  1555. }
  1556. // @todo: add support for IA_TA
  1557. default:
  1558. // remaining options are stateless and thus ignored in this context
  1559. ;
  1560. }
  1561. }
  1562. // To be pedantic, we should also include status code in the top-level
  1563. // scope, not just in each IA_NA. See RFC3315, section 18.2.6.
  1564. // This behavior will likely go away in RFC3315bis.
  1565. reply->addOption(createStatusCode(general_status,
  1566. "Summary status for all processed IA_NAs"));
  1567. }
  1568. OptionPtr
  1569. Dhcpv6Srv::releaseIA_NA(const DuidPtr& duid, const Pkt6Ptr& query,
  1570. int& general_status, boost::shared_ptr<Option6IA> ia) {
  1571. // Release can be done in one of two ways:
  1572. // Approach 1: extract address from client's IA_NA and see if it belongs
  1573. // to this particular client.
  1574. // Approach 2: find a subnet for this client, get a lease for
  1575. // this subnet/duid/iaid and check if its content matches to what the
  1576. // client is asking us to release.
  1577. //
  1578. // This method implements approach 1.
  1579. // That's our response
  1580. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_NA, ia->getIAID()));
  1581. boost::shared_ptr<Option6IAAddr> release_addr = boost::dynamic_pointer_cast<Option6IAAddr>
  1582. (ia->getOption(D6O_IAADDR));
  1583. if (!release_addr) {
  1584. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1585. "You did not include an address in your RELEASE"));
  1586. general_status = STATUS_NoBinding;
  1587. return (ia_rsp);
  1588. }
  1589. Lease6Ptr lease = LeaseMgrFactory::instance().getLease6(Lease::TYPE_NA,
  1590. release_addr->getAddress());
  1591. if (!lease) {
  1592. // client releasing a lease that we don't know about.
  1593. // Insert status code NoAddrsAvail.
  1594. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1595. "Sorry, no known leases for this duid/iaid, can't release."));
  1596. general_status = STATUS_NoBinding;
  1597. LOG_INFO(dhcp6_logger, DHCP6_UNKNOWN_RELEASE_NA)
  1598. .arg(duid->toText())
  1599. .arg(ia->getIAID());
  1600. return (ia_rsp);
  1601. }
  1602. if (!lease->duid_) {
  1603. // Something is gravely wrong here. We do have a lease, but it does not
  1604. // have mandatory DUID information attached. Someone was messing with our
  1605. // database.
  1606. LOG_ERROR(dhcp6_logger, DHCP6_LEASE_NA_WITHOUT_DUID)
  1607. .arg(release_addr->getAddress().toText());
  1608. general_status = STATUS_UnspecFail;
  1609. ia_rsp->addOption(createStatusCode(STATUS_UnspecFail,
  1610. "Database consistency check failed when trying to RELEASE"));
  1611. return (ia_rsp);
  1612. }
  1613. if (*duid != *(lease->duid_)) {
  1614. // Sorry, it's not your address. You can't release it.
  1615. LOG_INFO(dhcp6_logger, DHCP6_RELEASE_NA_FAIL_WRONG_DUID)
  1616. .arg(duid->toText())
  1617. .arg(release_addr->getAddress().toText())
  1618. .arg(lease->duid_->toText());
  1619. general_status = STATUS_NoBinding;
  1620. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1621. "This address does not belong to you, you can't release it"));
  1622. return (ia_rsp);
  1623. }
  1624. if (ia->getIAID() != lease->iaid_) {
  1625. // This address belongs to this client, but to a different IA
  1626. LOG_WARN(dhcp6_logger, DHCP6_RELEASE_PD_FAIL_WRONG_IAID)
  1627. .arg(duid->toText())
  1628. .arg(release_addr->getAddress().toText())
  1629. .arg(lease->iaid_)
  1630. .arg(ia->getIAID());
  1631. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1632. "This is your address, but you used wrong IAID"));
  1633. general_status = STATUS_NoBinding;
  1634. return (ia_rsp);
  1635. }
  1636. // It is not necessary to check if the address matches as we used
  1637. // getLease6(addr) method that is supposed to return a proper lease.
  1638. bool skip = false;
  1639. // Execute all callouts registered for packet6_send
  1640. if (HooksManager::calloutsPresent(Hooks.hook_index_lease6_release_)) {
  1641. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  1642. // Delete all previous arguments
  1643. callout_handle->deleteAllArguments();
  1644. // Pass the original packet
  1645. callout_handle->setArgument("query6", query);
  1646. // Pass the lease to be updated
  1647. callout_handle->setArgument("lease6", lease);
  1648. // Call all installed callouts
  1649. HooksManager::callCallouts(Hooks.hook_index_lease6_release_, *callout_handle);
  1650. // Callouts decided to skip the next processing step. The next
  1651. // processing step would to send the packet, so skip at this
  1652. // stage means "drop response".
  1653. if (callout_handle->getSkip()) {
  1654. skip = true;
  1655. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_LEASE6_RELEASE_NA_SKIP);
  1656. }
  1657. }
  1658. // Ok, we've passed all checks. Let's release this address.
  1659. bool success = false; // was the removal operation succeessful?
  1660. if (!skip) {
  1661. success = LeaseMgrFactory::instance().deleteLease(lease->addr_);
  1662. }
  1663. // Here the success should be true if we removed lease successfully
  1664. // and false if skip flag was set or the removal failed for whatever reason
  1665. if (!success) {
  1666. ia_rsp->addOption(createStatusCode(STATUS_UnspecFail,
  1667. "Server failed to release a lease"));
  1668. LOG_ERROR(dhcp6_logger, DHCP6_RELEASE_NA_FAIL)
  1669. .arg(lease->addr_.toText())
  1670. .arg(duid->toText())
  1671. .arg(lease->iaid_);
  1672. general_status = STATUS_UnspecFail;
  1673. return (ia_rsp);
  1674. } else {
  1675. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_RELEASE_NA)
  1676. .arg(lease->addr_.toText())
  1677. .arg(duid->toText())
  1678. .arg(lease->iaid_);
  1679. ia_rsp->addOption(createStatusCode(STATUS_Success,
  1680. "Lease released. Thank you, please come again."));
  1681. // Check if a lease has flags indicating that the FQDN update has
  1682. // been performed. If so, create NameChangeRequest which removes
  1683. // the entries.
  1684. createRemovalNameChangeRequest(lease);
  1685. return (ia_rsp);
  1686. }
  1687. }
  1688. OptionPtr
  1689. Dhcpv6Srv::releaseIA_PD(const DuidPtr& duid, const Pkt6Ptr& query,
  1690. int& general_status, boost::shared_ptr<Option6IA> ia) {
  1691. // Release can be done in one of two ways:
  1692. // Approach 1: extract address from client's IA_NA and see if it belongs
  1693. // to this particular client.
  1694. // Approach 2: find a subnet for this client, get a lease for
  1695. // this subnet/duid/iaid and check if its content matches to what the
  1696. // client is asking us to release.
  1697. //
  1698. // This method implements approach 1.
  1699. // That's our response. We will fill it in as we check the lease to be
  1700. // released.
  1701. boost::shared_ptr<Option6IA> ia_rsp(new Option6IA(D6O_IA_PD, ia->getIAID()));
  1702. boost::shared_ptr<Option6IAPrefix> release_prefix =
  1703. boost::dynamic_pointer_cast<Option6IAPrefix>(ia->getOption(D6O_IAPREFIX));
  1704. if (!release_prefix) {
  1705. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1706. "You did not include a prefix in your RELEASE"));
  1707. general_status = STATUS_NoBinding;
  1708. return (ia_rsp);
  1709. }
  1710. Lease6Ptr lease = LeaseMgrFactory::instance().getLease6(Lease::TYPE_PD,
  1711. release_prefix->getAddress());
  1712. if (!lease) {
  1713. // Client releasing a lease that we don't know about.
  1714. // Insert status code NoBinding.
  1715. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1716. "Sorry, no known leases for this duid/iaid, can't release."));
  1717. general_status = STATUS_NoBinding;
  1718. LOG_INFO(dhcp6_logger, DHCP6_UNKNOWN_RELEASE_PD)
  1719. .arg(duid->toText())
  1720. .arg(ia->getIAID());
  1721. return (ia_rsp);
  1722. }
  1723. if (!lease->duid_) {
  1724. // Something is gravely wrong here. We do have a lease, but it does not
  1725. // have mandatory DUID information attached. Someone was messing with our
  1726. // database.
  1727. LOG_ERROR(dhcp6_logger, DHCP6_LEASE_PD_WITHOUT_DUID)
  1728. .arg(release_prefix->getAddress().toText());
  1729. general_status = STATUS_UnspecFail;
  1730. ia_rsp->addOption(createStatusCode(STATUS_UnspecFail,
  1731. "Database consistency check failed when trying to RELEASE"));
  1732. return (ia_rsp);
  1733. }
  1734. if (*duid != *(lease->duid_)) {
  1735. // Sorry, it's not your address. You can't release it.
  1736. LOG_INFO(dhcp6_logger, DHCP6_RELEASE_PD_FAIL_WRONG_DUID)
  1737. .arg(duid->toText())
  1738. .arg(release_prefix->getAddress().toText())
  1739. .arg(lease->duid_->toText());
  1740. general_status = STATUS_NoBinding;
  1741. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1742. "This address does not belong to you, you can't release it"));
  1743. return (ia_rsp);
  1744. }
  1745. if (ia->getIAID() != lease->iaid_) {
  1746. // This address belongs to this client, but to a different IA
  1747. LOG_WARN(dhcp6_logger, DHCP6_RELEASE_PD_FAIL_WRONG_IAID)
  1748. .arg(duid->toText())
  1749. .arg(release_prefix->getAddress().toText())
  1750. .arg(lease->iaid_)
  1751. .arg(ia->getIAID());
  1752. ia_rsp->addOption(createStatusCode(STATUS_NoBinding,
  1753. "This is your address, but you used wrong IAID"));
  1754. general_status = STATUS_NoBinding;
  1755. return (ia_rsp);
  1756. }
  1757. // It is not necessary to check if the address matches as we used
  1758. // getLease6(addr) method that is supposed to return a proper lease.
  1759. bool skip = false;
  1760. // Execute all callouts registered for packet6_send
  1761. if (HooksManager::calloutsPresent(Hooks.hook_index_lease6_release_)) {
  1762. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  1763. // Delete all previous arguments
  1764. callout_handle->deleteAllArguments();
  1765. // Pass the original packet
  1766. callout_handle->setArgument("query6", query);
  1767. // Pass the lease to be updated
  1768. callout_handle->setArgument("lease6", lease);
  1769. // Call all installed callouts
  1770. HooksManager::callCallouts(Hooks.hook_index_lease6_release_, *callout_handle);
  1771. skip = callout_handle->getSkip();
  1772. }
  1773. // Ok, we've passed all checks. Let's release this prefix.
  1774. bool success = false; // was the removal operation succeessful?
  1775. if (!skip) {
  1776. success = LeaseMgrFactory::instance().deleteLease(lease->addr_);
  1777. } else {
  1778. // Callouts decided to skip the next processing step. The next
  1779. // processing step would to send the packet, so skip at this
  1780. // stage means "drop response".
  1781. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_HOOKS, DHCP6_HOOK_LEASE6_RELEASE_PD_SKIP);
  1782. }
  1783. // Here the success should be true if we removed lease successfully
  1784. // and false if skip flag was set or the removal failed for whatever reason
  1785. if (!success) {
  1786. ia_rsp->addOption(createStatusCode(STATUS_UnspecFail,
  1787. "Server failed to release a lease"));
  1788. LOG_ERROR(dhcp6_logger, DHCP6_RELEASE_PD_FAIL)
  1789. .arg(lease->addr_.toText())
  1790. .arg(duid->toText())
  1791. .arg(lease->iaid_);
  1792. general_status = STATUS_UnspecFail;
  1793. } else {
  1794. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_RELEASE_PD)
  1795. .arg(lease->addr_.toText())
  1796. .arg(duid->toText())
  1797. .arg(lease->iaid_);
  1798. ia_rsp->addOption(createStatusCode(STATUS_Success,
  1799. "Lease released. Thank you, please come again."));
  1800. }
  1801. return (ia_rsp);
  1802. }
  1803. Pkt6Ptr
  1804. Dhcpv6Srv::processSolicit(const Pkt6Ptr& solicit) {
  1805. sanityCheck(solicit, MANDATORY, FORBIDDEN);
  1806. Pkt6Ptr advertise(new Pkt6(DHCPV6_ADVERTISE, solicit->getTransid()));
  1807. copyDefaultOptions(solicit, advertise);
  1808. appendDefaultOptions(solicit, advertise);
  1809. appendRequestedOptions(solicit, advertise);
  1810. appendRequestedVendorOptions(solicit, advertise);
  1811. Option6ClientFqdnPtr fqdn = processClientFqdn(solicit);
  1812. assignLeases(solicit, advertise, fqdn);
  1813. appendClientFqdn(solicit, advertise, fqdn);
  1814. // Note, that we don't create NameChangeRequests here because we don't
  1815. // perform DNS Updates for Solicit. Client must send Request to update
  1816. // DNS.
  1817. return (advertise);
  1818. }
  1819. Pkt6Ptr
  1820. Dhcpv6Srv::processRequest(const Pkt6Ptr& request) {
  1821. sanityCheck(request, MANDATORY, MANDATORY);
  1822. Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, request->getTransid()));
  1823. copyDefaultOptions(request, reply);
  1824. appendDefaultOptions(request, reply);
  1825. appendRequestedOptions(request, reply);
  1826. appendRequestedVendorOptions(request, reply);
  1827. Option6ClientFqdnPtr fqdn = processClientFqdn(request);
  1828. assignLeases(request, reply, fqdn);
  1829. appendClientFqdn(request, reply, fqdn);
  1830. createNameChangeRequests(reply, fqdn);
  1831. return (reply);
  1832. }
  1833. Pkt6Ptr
  1834. Dhcpv6Srv::processRenew(const Pkt6Ptr& renew) {
  1835. sanityCheck(renew, MANDATORY, MANDATORY);
  1836. Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, renew->getTransid()));
  1837. copyDefaultOptions(renew, reply);
  1838. appendDefaultOptions(renew, reply);
  1839. appendRequestedOptions(renew, reply);
  1840. Option6ClientFqdnPtr fqdn = processClientFqdn(renew);
  1841. renewLeases(renew, reply, fqdn);
  1842. appendClientFqdn(renew, reply, fqdn);
  1843. createNameChangeRequests(reply, fqdn);
  1844. return reply;
  1845. }
  1846. Pkt6Ptr
  1847. Dhcpv6Srv::processRebind(const Pkt6Ptr& rebind) {
  1848. /// @todo: Implement this
  1849. Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, rebind->getTransid()));
  1850. return reply;
  1851. }
  1852. Pkt6Ptr
  1853. Dhcpv6Srv::processConfirm(const Pkt6Ptr& confirm) {
  1854. /// @todo: Implement this
  1855. Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, confirm->getTransid()));
  1856. return reply;
  1857. }
  1858. Pkt6Ptr
  1859. Dhcpv6Srv::processRelease(const Pkt6Ptr& release) {
  1860. sanityCheck(release, MANDATORY, MANDATORY);
  1861. Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, release->getTransid()));
  1862. copyDefaultOptions(release, reply);
  1863. appendDefaultOptions(release, reply);
  1864. releaseLeases(release, reply);
  1865. // @todo If client sent a release and we should remove outstanding
  1866. // DNS records.
  1867. return (reply);
  1868. }
  1869. Pkt6Ptr
  1870. Dhcpv6Srv::processDecline(const Pkt6Ptr& decline) {
  1871. /// @todo: Implement this
  1872. Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, decline->getTransid()));
  1873. return reply;
  1874. }
  1875. Pkt6Ptr
  1876. Dhcpv6Srv::processInfRequest(const Pkt6Ptr& infRequest) {
  1877. /// @todo: Implement this
  1878. Pkt6Ptr reply(new Pkt6(DHCPV6_REPLY, infRequest->getTransid()));
  1879. return reply;
  1880. }
  1881. void
  1882. Dhcpv6Srv::openActiveSockets(const uint16_t port) {
  1883. IfaceMgr::instance().closeSockets();
  1884. // Get the reference to the collection of interfaces. This reference should be
  1885. // valid as long as the program is run because IfaceMgr is a singleton.
  1886. // Therefore we can safely iterate over instances of all interfaces and modify
  1887. // their flags. Here we modify flags which indicate wheter socket should be
  1888. // open for a particular interface or not.
  1889. const IfaceMgr::IfaceCollection& ifaces = IfaceMgr::instance().getIfaces();
  1890. for (IfaceMgr::IfaceCollection::const_iterator iface = ifaces.begin();
  1891. iface != ifaces.end(); ++iface) {
  1892. Iface* iface_ptr = IfaceMgr::instance().getIface(iface->getName());
  1893. if (iface_ptr == NULL) {
  1894. isc_throw(isc::Unexpected, "Interface Manager returned NULL"
  1895. << " instance of the interface when DHCPv6 server was"
  1896. << " trying to reopen sockets after reconfiguration");
  1897. }
  1898. if (CfgMgr::instance().isActiveIface(iface->getName())) {
  1899. iface_ptr->inactive6_ = false;
  1900. LOG_INFO(dhcp6_logger, DHCP6_ACTIVATE_INTERFACE)
  1901. .arg(iface->getFullName());
  1902. } else {
  1903. // For deactivating interface, it should be sufficient to log it
  1904. // on the debug level because it is more useful to know what
  1905. // interface is activated which is logged on the info level.
  1906. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_BASIC,
  1907. DHCP6_DEACTIVATE_INTERFACE).arg(iface->getName());
  1908. iface_ptr->inactive6_ = true;
  1909. }
  1910. iface_ptr->clearUnicasts();
  1911. const IOAddress* unicast = CfgMgr::instance().getUnicast(iface->getName());
  1912. if (unicast) {
  1913. LOG_INFO(dhcp6_logger, DHCP6_SOCKET_UNICAST).arg(unicast->toText())
  1914. .arg(iface->getName());
  1915. iface_ptr->addUnicast(*unicast);
  1916. }
  1917. }
  1918. // Let's reopen active sockets. openSockets6 will check internally whether
  1919. // sockets are marked active or inactive.
  1920. // @todo Optimization: we should not reopen all sockets but rather select
  1921. // those that have been affected by the new configuration.
  1922. if (!IfaceMgr::instance().openSockets6(port)) {
  1923. LOG_WARN(dhcp6_logger, DHCP6_NO_SOCKETS_OPEN);
  1924. }
  1925. }
  1926. size_t
  1927. Dhcpv6Srv::unpackOptions(const OptionBuffer& buf,
  1928. const std::string& option_space,
  1929. isc::dhcp::OptionCollection& options,
  1930. size_t* relay_msg_offset,
  1931. size_t* relay_msg_len) {
  1932. size_t offset = 0;
  1933. size_t length = buf.size();
  1934. OptionDefContainer option_defs;
  1935. if (option_space == "dhcp6") {
  1936. // Get the list of stdandard option definitions.
  1937. option_defs = LibDHCP::getOptionDefs(Option::V6);
  1938. } else if (!option_space.empty()) {
  1939. OptionDefContainerPtr option_defs_ptr =
  1940. CfgMgr::instance().getOptionDefs(option_space);
  1941. if (option_defs_ptr != NULL) {
  1942. option_defs = *option_defs_ptr;
  1943. }
  1944. }
  1945. // Get the search index #1. It allows to search for option definitions
  1946. // using option code.
  1947. const OptionDefContainerTypeIndex& idx = option_defs.get<1>();
  1948. // The buffer being read comprises a set of options, each starting with
  1949. // a two-byte type code and a two-byte length field.
  1950. while (offset + 4 <= length) {
  1951. uint16_t opt_type = isc::util::readUint16(&buf[offset]);
  1952. offset += 2;
  1953. uint16_t opt_len = isc::util::readUint16(&buf[offset]);
  1954. offset += 2;
  1955. if (offset + opt_len > length) {
  1956. // @todo: consider throwing exception here.
  1957. return (offset);
  1958. }
  1959. if (opt_type == D6O_RELAY_MSG && relay_msg_offset && relay_msg_len) {
  1960. // remember offset of the beginning of the relay-msg option
  1961. *relay_msg_offset = offset;
  1962. *relay_msg_len = opt_len;
  1963. // do not create that relay-msg option
  1964. offset += opt_len;
  1965. continue;
  1966. }
  1967. // Get all definitions with the particular option code. Note that option
  1968. // code is non-unique within this container however at this point we
  1969. // expect to get one option definition with the particular code. If more
  1970. // are returned we report an error.
  1971. const OptionDefContainerTypeRange& range = idx.equal_range(opt_type);
  1972. // Get the number of returned option definitions for the option code.
  1973. size_t num_defs = distance(range.first, range.second);
  1974. OptionPtr opt;
  1975. if (num_defs > 1) {
  1976. // Multiple options of the same code are not supported right now!
  1977. isc_throw(isc::Unexpected, "Internal error: multiple option definitions"
  1978. " for option type " << opt_type << " returned. Currently it is not"
  1979. " supported to initialize multiple option definitions"
  1980. " for the same option code. This will be supported once"
  1981. " support for option spaces is implemented");
  1982. } else if (num_defs == 0) {
  1983. // @todo Don't crash if definition does not exist because only a few
  1984. // option definitions are initialized right now. In the future
  1985. // we will initialize definitions for all options and we will
  1986. // remove this elseif. For now, return generic option.
  1987. opt = OptionPtr(new Option(Option::V6, opt_type,
  1988. buf.begin() + offset,
  1989. buf.begin() + offset + opt_len));
  1990. opt->setEncapsulatedSpace("dhcp6");
  1991. } else {
  1992. // The option definition has been found. Use it to create
  1993. // the option instance from the provided buffer chunk.
  1994. const OptionDefinitionPtr& def = *(range.first);
  1995. assert(def);
  1996. opt = def->optionFactory(Option::V6, opt_type,
  1997. buf.begin() + offset,
  1998. buf.begin() + offset + opt_len,
  1999. boost::bind(&Dhcpv6Srv::unpackOptions, this, _1, _2,
  2000. _3, _4, _5));
  2001. }
  2002. // add option to options
  2003. options.insert(std::make_pair(opt_type, opt));
  2004. offset += opt_len;
  2005. }
  2006. return (offset);
  2007. }
  2008. };
  2009. };