dhcp6_srv.cc 95 KB

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