dhcp6_srv.cc 106 KB

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