dhcp6_srv.cc 118 KB

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