dhcp6_srv.cc 114 KB

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