dhcp6_srv.cc 92 KB

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