dhcp4_srv.cc 110 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895
  1. // Copyright (C) 2011-2016 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this
  5. // file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. #include <config.h>
  7. #include <asiolink/io_address.h>
  8. #include <dhcp/dhcp4.h>
  9. #include <dhcp/duid.h>
  10. #include <dhcp/hwaddr.h>
  11. #include <dhcp/iface_mgr.h>
  12. #include <dhcp/option4_addrlst.h>
  13. #include <dhcp/option_int.h>
  14. #include <dhcp/option_int_array.h>
  15. #include <dhcp/option_vendor.h>
  16. #include <dhcp/option_string.h>
  17. #include <dhcp/pkt4.h>
  18. #include <dhcp/pkt4o6.h>
  19. #include <dhcp/pkt6.h>
  20. #include <dhcp/docsis3_option_defs.h>
  21. #include <dhcp4/dhcp4to6_ipc.h>
  22. #include <dhcp4/dhcp4_log.h>
  23. #include <dhcp4/dhcp4_srv.h>
  24. #include <dhcpsrv/addr_utilities.h>
  25. #include <dhcpsrv/callout_handle_store.h>
  26. #include <dhcpsrv/cfgmgr.h>
  27. #include <dhcpsrv/cfg_host_operations.h>
  28. #include <dhcpsrv/cfg_subnets4.h>
  29. #include <dhcpsrv/lease_mgr.h>
  30. #include <dhcpsrv/lease_mgr_factory.h>
  31. #include <dhcpsrv/ncr_generator.h>
  32. #include <dhcpsrv/subnet.h>
  33. #include <dhcpsrv/subnet_selector.h>
  34. #include <dhcpsrv/utils.h>
  35. #include <dhcpsrv/utils.h>
  36. #include <eval/evaluate.h>
  37. #include <eval/eval_messages.h>
  38. #include <hooks/callout_handle.h>
  39. #include <hooks/hooks_log.h>
  40. #include <hooks/hooks_manager.h>
  41. #include <stats/stats_mgr.h>
  42. #include <util/strutil.h>
  43. #include <stats/stats_mgr.h>
  44. #include <log/logger.h>
  45. #include <cryptolink/cryptolink.h>
  46. #include <cfgrpt/config_report.h>
  47. #ifdef HAVE_MYSQL
  48. #include <dhcpsrv/mysql_lease_mgr.h>
  49. #endif
  50. #ifdef HAVE_PGSQL
  51. #include <dhcpsrv/pgsql_lease_mgr.h>
  52. #endif
  53. #ifdef HAVE_CQL
  54. #include <dhcpsrv/cql_lease_mgr.h>
  55. #endif
  56. #include <dhcpsrv/memfile_lease_mgr.h>
  57. #include <boost/bind.hpp>
  58. #include <boost/foreach.hpp>
  59. #include <boost/shared_ptr.hpp>
  60. #include <iomanip>
  61. using namespace isc;
  62. using namespace isc::asiolink;
  63. using namespace isc::cryptolink;
  64. using namespace isc::dhcp;
  65. using namespace isc::dhcp_ddns;
  66. using namespace isc::hooks;
  67. using namespace isc::log;
  68. using namespace isc::stats;
  69. using namespace std;
  70. /// Structure that holds registered hook indexes
  71. struct Dhcp4Hooks {
  72. int hook_index_buffer4_receive_;///< index for "buffer4_receive" hook point
  73. int hook_index_pkt4_receive_; ///< index for "pkt4_receive" hook point
  74. int hook_index_subnet4_select_; ///< index for "subnet4_select" hook point
  75. int hook_index_lease4_release_; ///< index for "lease4_release" hook point
  76. int hook_index_pkt4_send_; ///< index for "pkt4_send" hook point
  77. int hook_index_buffer4_send_; ///< index for "buffer4_send" hook point
  78. int hook_index_lease4_decline_; ///< index for "lease4_decline" hook point
  79. /// Constructor that registers hook points for DHCPv4 engine
  80. Dhcp4Hooks() {
  81. hook_index_buffer4_receive_= HooksManager::registerHook("buffer4_receive");
  82. hook_index_pkt4_receive_ = HooksManager::registerHook("pkt4_receive");
  83. hook_index_subnet4_select_ = HooksManager::registerHook("subnet4_select");
  84. hook_index_pkt4_send_ = HooksManager::registerHook("pkt4_send");
  85. hook_index_lease4_release_ = HooksManager::registerHook("lease4_release");
  86. hook_index_buffer4_send_ = HooksManager::registerHook("buffer4_send");
  87. hook_index_lease4_decline_ = HooksManager::registerHook("lease4_decline");
  88. }
  89. };
  90. // Declare a Hooks object. As this is outside any function or method, it
  91. // will be instantiated (and the constructor run) when the module is loaded.
  92. // As a result, the hook indexes will be defined before any method in this
  93. // module is called.
  94. Dhcp4Hooks Hooks;
  95. namespace isc {
  96. namespace dhcp {
  97. Dhcpv4Exchange::Dhcpv4Exchange(const AllocEnginePtr& alloc_engine,
  98. const Pkt4Ptr& query,
  99. const Subnet4Ptr& subnet)
  100. : alloc_engine_(alloc_engine), query_(query), resp_(),
  101. context_(new AllocEngine::ClientContext4()) {
  102. if (!alloc_engine_) {
  103. isc_throw(BadValue, "alloc_engine value must not be NULL"
  104. " when creating an instance of the Dhcpv4Exchange");
  105. }
  106. if (!query_) {
  107. isc_throw(BadValue, "query value must not be NULL when"
  108. " creating an instance of the Dhcpv4Exchange");
  109. }
  110. // Create response message.
  111. initResponse();
  112. // Select subnet for the query message.
  113. context_->subnet_ = subnet;
  114. // Hardware address.
  115. context_->hwaddr_ = query->getHWAddr();
  116. // Pointer to client's query.
  117. context_->query_ = query;
  118. // Set client identifier if the match-client-id flag is enabled (default).
  119. // If the subnet wasn't found it doesn't matter because we will not be
  120. // able to allocate a lease anyway so this context will not be used.
  121. if (subnet) {
  122. if (subnet->getMatchClientId()) {
  123. OptionPtr opt_clientid = query->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  124. if (opt_clientid) {
  125. context_->clientid_.reset(new ClientId(opt_clientid->getData()));
  126. }
  127. } else {
  128. /// @todo When merging with #3806 use different logger.
  129. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_CLIENTID_IGNORED_FOR_LEASES)
  130. .arg(query->getLabel())
  131. .arg(subnet->getID());
  132. }
  133. // Find static reservations if not disabled for our subnet.
  134. if (subnet->getHostReservationMode() != Subnet::HR_DISABLED) {
  135. // Before we can check for static reservations, we need to prepare a set
  136. // of identifiers to be used for this.
  137. setHostIdentifiers();
  138. // Check for static reservations.
  139. alloc_engine->findReservation(*context_);
  140. }
  141. }
  142. };
  143. void
  144. Dhcpv4Exchange::initResponse() {
  145. uint8_t resp_type = 0;
  146. switch (getQuery()->getType()) {
  147. case DHCPDISCOVER:
  148. resp_type = DHCPOFFER;
  149. break;
  150. case DHCPREQUEST:
  151. case DHCPINFORM:
  152. resp_type = DHCPACK;
  153. break;
  154. default:
  155. ;
  156. }
  157. // Only create a response if one is required.
  158. if (resp_type > 0) {
  159. resp_.reset(new Pkt4(resp_type, getQuery()->getTransid()));
  160. copyDefaultFields();
  161. copyDefaultOptions();
  162. if (getQuery()->isDhcp4o6()) {
  163. initResponse4o6();
  164. }
  165. }
  166. }
  167. void
  168. Dhcpv4Exchange::initResponse4o6() {
  169. Pkt4o6Ptr query = boost::dynamic_pointer_cast<Pkt4o6>(getQuery());
  170. if (!query) {
  171. return;
  172. }
  173. const Pkt6Ptr& query6 = query->getPkt6();
  174. Pkt6Ptr resp6(new Pkt6(DHCPV6_DHCPV4_RESPONSE, query6->getTransid()));
  175. // Don't add client-id or server-id
  176. // But copy relay info
  177. if (!query6->relay_info_.empty()) {
  178. resp6->copyRelayInfo(query6);
  179. }
  180. // Copy interface and remote address
  181. resp6->setIface(query6->getIface());
  182. resp6->setIndex(query6->getIndex());
  183. resp6->setRemoteAddr(query6->getRemoteAddr());
  184. resp_.reset(new Pkt4o6(resp_, resp6));
  185. }
  186. void
  187. Dhcpv4Exchange::copyDefaultFields() {
  188. resp_->setIface(query_->getIface());
  189. resp_->setIndex(query_->getIndex());
  190. // explicitly set this to 0
  191. resp_->setSiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  192. // ciaddr is always 0, except for the Renew/Rebind state when it may
  193. // be set to the ciaddr sent by the client.
  194. resp_->setCiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  195. resp_->setHops(query_->getHops());
  196. // copy MAC address
  197. resp_->setHWAddr(query_->getHWAddr());
  198. // relay address
  199. resp_->setGiaddr(query_->getGiaddr());
  200. // If src/dest HW addresses are used by the packet filtering class
  201. // we need to copy them as well. There is a need to check that the
  202. // address being set is not-NULL because an attempt to set the NULL
  203. // HW would result in exception. If these values are not set, the
  204. // the default HW addresses (zeroed) should be generated by the
  205. // packet filtering class when creating Ethernet header for
  206. // outgoing packet.
  207. HWAddrPtr src_hw_addr = query_->getLocalHWAddr();
  208. if (src_hw_addr) {
  209. resp_->setLocalHWAddr(src_hw_addr);
  210. }
  211. HWAddrPtr dst_hw_addr = query_->getRemoteHWAddr();
  212. if (dst_hw_addr) {
  213. resp_->setRemoteHWAddr(dst_hw_addr);
  214. }
  215. // Copy flags from the request to the response per RFC 2131
  216. resp_->setFlags(query_->getFlags());
  217. }
  218. void
  219. Dhcpv4Exchange::copyDefaultOptions() {
  220. // Let's copy client-id to response. See RFC6842.
  221. // It is possible to disable RFC6842 to keep backward compatibility
  222. bool echo = CfgMgr::instance().echoClientId();
  223. OptionPtr client_id = query_->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  224. if (client_id && echo) {
  225. resp_->addOption(client_id);
  226. }
  227. // If this packet is relayed, we want to copy Relay Agent Info option
  228. OptionPtr rai = query_->getOption(DHO_DHCP_AGENT_OPTIONS);
  229. if (rai) {
  230. resp_->addOption(rai);
  231. }
  232. // RFC 3011 states about the Subnet Selection Option
  233. // "Servers configured to support this option MUST return an
  234. // identical copy of the option to any client that sends it,
  235. // regardless of whether or not the client requests the option in
  236. // a parameter request list. Clients using this option MUST
  237. // discard DHCPOFFER or DHCPACK packets that do not contain this
  238. // option."
  239. OptionPtr subnet_sel = query_->getOption(DHO_SUBNET_SELECTION);
  240. if (subnet_sel) {
  241. resp_->addOption(subnet_sel);
  242. }
  243. }
  244. void
  245. Dhcpv4Exchange::setHostIdentifiers() {
  246. const ConstCfgHostOperationsPtr cfg =
  247. CfgMgr::instance().getCurrentCfg()->getCfgHostOperations4();
  248. // Collect host identifiers. The identifiers are stored in order of preference.
  249. // The server will use them in that order to search for host reservations.
  250. BOOST_FOREACH(const Host::IdentifierType& id_type,
  251. cfg->getIdentifierTypes()) {
  252. switch (id_type) {
  253. case Host::IDENT_HWADDR:
  254. if (context_->hwaddr_ && !context_->hwaddr_->hwaddr_.empty()) {
  255. context_->addHostIdentifier(id_type, context_->hwaddr_->hwaddr_);
  256. }
  257. break;
  258. case Host::IDENT_DUID:
  259. if (context_->clientid_) {
  260. const std::vector<uint8_t>& vec = context_->clientid_->getDuid();
  261. if (!vec.empty()) {
  262. // Client identifier type = DUID? Client identifier holding a DUID
  263. // comprises Type (1 byte), IAID (4 bytes), followed by the actual
  264. // DUID. Thus, the minimal length is 6.
  265. if ((vec[0] == CLIENT_ID_OPTION_TYPE_DUID) && (vec.size() > 5)) {
  266. // Extract DUID, skip IAID.
  267. context_->addHostIdentifier(id_type,
  268. std::vector<uint8_t>(vec.begin() + 5,
  269. vec.end()));
  270. }
  271. }
  272. }
  273. break;
  274. case Host::IDENT_CIRCUIT_ID:
  275. {
  276. OptionPtr rai = query_->getOption(DHO_DHCP_AGENT_OPTIONS);
  277. if (rai) {
  278. OptionPtr circuit_id_opt = rai->getOption(RAI_OPTION_AGENT_CIRCUIT_ID);
  279. if (circuit_id_opt) {
  280. const OptionBuffer& circuit_id_vec = circuit_id_opt->getData();
  281. if (!circuit_id_vec.empty()) {
  282. context_->addHostIdentifier(id_type, circuit_id_vec);
  283. }
  284. }
  285. }
  286. }
  287. break;
  288. case Host::IDENT_CLIENT_ID:
  289. if (context_->clientid_) {
  290. const std::vector<uint8_t>& vec = context_->clientid_->getDuid();
  291. if (!vec.empty()) {
  292. context_->addHostIdentifier(id_type, vec);
  293. }
  294. }
  295. break;
  296. default:
  297. ;
  298. }
  299. }
  300. }
  301. void
  302. Dhcpv4Exchange::setReservedMessageFields() {
  303. ConstHostPtr host = context_->host_;
  304. // Nothing to do if host reservations not specified for this client.
  305. if (host) {
  306. if (!host->getNextServer().isV4Zero()) {
  307. resp_->setSiaddr(host->getNextServer());
  308. }
  309. if (!host->getServerHostname().empty()) {
  310. resp_->setSname(reinterpret_cast<
  311. const uint8_t*>(host->getServerHostname().c_str()));
  312. }
  313. if (!host->getBootFileName().empty()) {
  314. resp_->setFile(reinterpret_cast<
  315. const uint8_t*>(host->getBootFileName().c_str()));
  316. }
  317. }
  318. }
  319. const std::string Dhcpv4Srv::VENDOR_CLASS_PREFIX("VENDOR_CLASS_");
  320. Dhcpv4Srv::Dhcpv4Srv(uint16_t port, const bool use_bcast,
  321. const bool direct_response_desired)
  322. : shutdown_(true), alloc_engine_(), port_(port),
  323. use_bcast_(use_bcast) {
  324. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_START, DHCP4_OPEN_SOCKET).arg(port);
  325. try {
  326. // Port 0 is used for testing purposes where we don't open broadcast
  327. // capable sockets. So, set the packet filter handling direct traffic
  328. // only if we are in non-test mode.
  329. if (port) {
  330. // First call to instance() will create IfaceMgr (it's a singleton)
  331. // it may throw something if things go wrong.
  332. // The 'true' value of the call to setMatchingPacketFilter imposes
  333. // that IfaceMgr will try to use the mechanism to respond directly
  334. // to the client which doesn't have address assigned. This capability
  335. // may be lacking on some OSes, so there is no guarantee that server
  336. // will be able to respond directly.
  337. IfaceMgr::instance().setMatchingPacketFilter(direct_response_desired);
  338. }
  339. // Instantiate allocation engine. The number of allocation attempts equal
  340. // to zero indicates that the allocation engine will use the number of
  341. // attempts depending on the pool size.
  342. alloc_engine_.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE, 0,
  343. false /* false = IPv4 */));
  344. /// @todo call loadLibraries() when handling configuration changes
  345. } catch (const std::exception &e) {
  346. LOG_ERROR(dhcp4_logger, DHCP4_SRV_CONSTRUCT_ERROR).arg(e.what());
  347. shutdown_ = true;
  348. return;
  349. }
  350. shutdown_ = false;
  351. }
  352. Dhcpv4Srv::~Dhcpv4Srv() {
  353. try {
  354. stopD2();
  355. } catch(const std::exception& ex) {
  356. // Highly unlikely, but lets Report it but go on
  357. LOG_ERROR(dhcp4_logger, DHCP4_SRV_D2STOP_ERROR).arg(ex.what());
  358. }
  359. try {
  360. Dhcp4to6Ipc::instance().close();
  361. } catch(const std::exception& ex) {
  362. // Highly unlikely, but lets Report it but go on
  363. LOG_ERROR(dhcp4_logger, DHCP4_SRV_DHCP4O6_ERROR).arg(ex.what());
  364. }
  365. IfaceMgr::instance().closeSockets();
  366. // The lease manager was instantiated during DHCPv4Srv configuration,
  367. // so we should clean up after ourselves.
  368. LeaseMgrFactory::destroy();
  369. // Explicitly unload hooks
  370. HooksManager::getHooksManager().unloadLibraries();
  371. }
  372. void
  373. Dhcpv4Srv::shutdown() {
  374. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_BASIC, DHCP4_SHUTDOWN_REQUEST);
  375. shutdown_ = true;
  376. }
  377. isc::dhcp::Subnet4Ptr
  378. Dhcpv4Srv::selectSubnet(const Pkt4Ptr& query) const {
  379. // DHCPv4-over-DHCPv6 is a special (and complex) case
  380. if (query->isDhcp4o6()) {
  381. return (selectSubnet4o6(query));
  382. }
  383. Subnet4Ptr subnet;
  384. SubnetSelector selector;
  385. selector.ciaddr_ = query->getCiaddr();
  386. selector.giaddr_ = query->getGiaddr();
  387. selector.local_address_ = query->getLocalAddr();
  388. selector.remote_address_ = query->getRemoteAddr();
  389. selector.client_classes_ = query->classes_;
  390. selector.iface_name_ = query->getIface();
  391. // If the link-selection sub-option is present, extract its value.
  392. // "The link-selection sub-option is used by any DHCP relay agent
  393. // that desires to specify a subnet/link for a DHCP client request
  394. // that it is relaying but needs the subnet/link specification to
  395. // be different from the IP address the DHCP server should use
  396. // when communicating with the relay agent." (RFC 3257)
  397. //
  398. // Try first Relay Agent Link Selection sub-option
  399. OptionPtr rai = query->getOption(DHO_DHCP_AGENT_OPTIONS);
  400. if (rai) {
  401. OptionCustomPtr rai_custom =
  402. boost::dynamic_pointer_cast<OptionCustom>(rai);
  403. if (rai_custom) {
  404. OptionPtr link_select =
  405. rai_custom->getOption(RAI_OPTION_LINK_SELECTION);
  406. if (link_select) {
  407. OptionBuffer link_select_buf = link_select->getData();
  408. if (link_select_buf.size() == sizeof(uint32_t)) {
  409. selector.option_select_ =
  410. IOAddress::fromBytes(AF_INET, &link_select_buf[0]);
  411. }
  412. }
  413. }
  414. } else {
  415. // Or Subnet Selection option
  416. OptionPtr sbnsel = query->getOption(DHO_SUBNET_SELECTION);
  417. if (sbnsel) {
  418. OptionCustomPtr oc =
  419. boost::dynamic_pointer_cast<OptionCustom>(sbnsel);
  420. if (oc) {
  421. selector.option_select_ = oc->readAddress();
  422. }
  423. }
  424. }
  425. CfgMgr& cfgmgr = CfgMgr::instance();
  426. subnet = cfgmgr.getCurrentCfg()->getCfgSubnets4()->selectSubnet(selector);
  427. // Let's execute all callouts registered for subnet4_select
  428. if (HooksManager::calloutsPresent(Hooks.hook_index_subnet4_select_)) {
  429. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  430. // We're reusing callout_handle from previous calls
  431. callout_handle->deleteAllArguments();
  432. // Enable copying options from the packet within hook library.
  433. ScopedEnableOptionsCopy<Pkt4> query4_options_copy(query);
  434. // Set new arguments
  435. callout_handle->setArgument("query4", query);
  436. callout_handle->setArgument("subnet4", subnet);
  437. callout_handle->setArgument("subnet4collection",
  438. cfgmgr.getCurrentCfg()->
  439. getCfgSubnets4()->getAll());
  440. // Call user (and server-side) callouts
  441. HooksManager::callCallouts(Hooks.hook_index_subnet4_select_,
  442. *callout_handle);
  443. // Callouts decided to skip this step. This means that no subnet
  444. // will be selected. Packet processing will continue, but it will
  445. // be severely limited (i.e. only global options will be assigned)
  446. if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  447. LOG_DEBUG(hooks_logger, DBG_DHCP4_HOOKS,
  448. DHCP4_HOOK_SUBNET4_SELECT_SKIP)
  449. .arg(query->getLabel());
  450. return (Subnet4Ptr());
  451. }
  452. /// @todo: Add support for DROP status
  453. // Use whatever subnet was specified by the callout
  454. callout_handle->getArgument("subnet4", subnet);
  455. }
  456. if (subnet) {
  457. // Log at higher debug level that subnet has been found.
  458. LOG_DEBUG(packet4_logger, DBG_DHCP4_BASIC_DATA, DHCP4_SUBNET_SELECTED)
  459. .arg(query->getLabel())
  460. .arg(subnet->getID());
  461. // Log detailed information about the selected subnet at the
  462. // lower debug level.
  463. LOG_DEBUG(packet4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_SUBNET_DATA)
  464. .arg(query->getLabel())
  465. .arg(subnet->toText());
  466. } else {
  467. LOG_DEBUG(packet4_logger, DBG_DHCP4_DETAIL,
  468. DHCP4_SUBNET_SELECTION_FAILED)
  469. .arg(query->getLabel());
  470. }
  471. return (subnet);
  472. }
  473. isc::dhcp::Subnet4Ptr
  474. Dhcpv4Srv::selectSubnet4o6(const Pkt4Ptr& query) const {
  475. Subnet4Ptr subnet;
  476. SubnetSelector selector;
  477. selector.ciaddr_ = query->getCiaddr();
  478. selector.giaddr_ = query->getGiaddr();
  479. selector.local_address_ = query->getLocalAddr();
  480. selector.client_classes_ = query->classes_;
  481. selector.iface_name_ = query->getIface();
  482. // Mark it as DHCPv4-over-DHCPv6
  483. selector.dhcp4o6_ = true;
  484. // Now the DHCPv6 part
  485. selector.remote_address_ = query->getRemoteAddr();
  486. selector.first_relay_linkaddr_ = IOAddress("::");
  487. // Handle a DHCPv6 relayed query
  488. Pkt4o6Ptr query4o6 = boost::dynamic_pointer_cast<Pkt4o6>(query);
  489. if (!query4o6) {
  490. isc_throw(Unexpected, "Can't get DHCP4o6 message");
  491. }
  492. const Pkt6Ptr& query6 = query4o6->getPkt6();
  493. // Initialize fields specific to relayed messages.
  494. if (query6 && !query6->relay_info_.empty()) {
  495. BOOST_REVERSE_FOREACH(Pkt6::RelayInfo relay, query6->relay_info_) {
  496. if (!relay.linkaddr_.isV6Zero() &&
  497. !relay.linkaddr_.isV6LinkLocal()) {
  498. selector.first_relay_linkaddr_ = relay.linkaddr_;
  499. break;
  500. }
  501. }
  502. selector.interface_id_ =
  503. query6->getAnyRelayOption(D6O_INTERFACE_ID,
  504. Pkt6::RELAY_GET_FIRST);
  505. }
  506. // If the Subnet Selection option is present, extract its value.
  507. OptionPtr sbnsel = query->getOption(DHO_SUBNET_SELECTION);
  508. if (sbnsel) {
  509. OptionCustomPtr oc = boost::dynamic_pointer_cast<OptionCustom>(sbnsel);
  510. if (oc) {
  511. selector.option_select_ = oc->readAddress();
  512. }
  513. }
  514. CfgMgr& cfgmgr = CfgMgr::instance();
  515. subnet = cfgmgr.getCurrentCfg()->getCfgSubnets4()->selectSubnet4o6(selector);
  516. // Let's execute all callouts registered for subnet4_select
  517. if (HooksManager::calloutsPresent(Hooks.hook_index_subnet4_select_)) {
  518. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  519. // We're reusing callout_handle from previous calls
  520. callout_handle->deleteAllArguments();
  521. // Set new arguments
  522. callout_handle->setArgument("query4", query);
  523. callout_handle->setArgument("subnet4", subnet);
  524. callout_handle->setArgument("subnet4collection",
  525. cfgmgr.getCurrentCfg()->
  526. getCfgSubnets4()->getAll());
  527. // Call user (and server-side) callouts
  528. HooksManager::callCallouts(Hooks.hook_index_subnet4_select_,
  529. *callout_handle);
  530. // Callouts decided to skip this step. This means that no subnet
  531. // will be selected. Packet processing will continue, but it will
  532. // be severely limited (i.e. only global options will be assigned)
  533. if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  534. LOG_DEBUG(hooks_logger, DBG_DHCP4_HOOKS,
  535. DHCP4_HOOK_SUBNET4_SELECT_SKIP)
  536. .arg(query->getLabel());
  537. return (Subnet4Ptr());
  538. }
  539. /// @todo: Add support for DROP status
  540. // Use whatever subnet was specified by the callout
  541. callout_handle->getArgument("subnet4", subnet);
  542. }
  543. if (subnet) {
  544. // Log at higher debug level that subnet has been found.
  545. LOG_DEBUG(packet4_logger, DBG_DHCP4_BASIC_DATA, DHCP4_SUBNET_SELECTED)
  546. .arg(query->getLabel())
  547. .arg(subnet->getID());
  548. // Log detailed information about the selected subnet at the
  549. // lower debug level.
  550. LOG_DEBUG(packet4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_SUBNET_DATA)
  551. .arg(query->getLabel())
  552. .arg(subnet->toText());
  553. } else {
  554. LOG_DEBUG(packet4_logger, DBG_DHCP4_DETAIL,
  555. DHCP4_SUBNET_SELECTION_FAILED)
  556. .arg(query->getLabel());
  557. }
  558. return (subnet);
  559. }
  560. Pkt4Ptr
  561. Dhcpv4Srv::receivePacket(int timeout) {
  562. return (IfaceMgr::instance().receive4(timeout));
  563. }
  564. void
  565. Dhcpv4Srv::sendPacket(const Pkt4Ptr& packet) {
  566. IfaceMgr::instance().send(packet);
  567. }
  568. bool
  569. Dhcpv4Srv::run() {
  570. while (!shutdown_) {
  571. try {
  572. run_one();
  573. } catch (const std::exception& e) {
  574. // General catch-all exception that are not caught by more specific
  575. // catches. This one is for exceptions derived from std::exception.
  576. LOG_ERROR(packet4_logger, DHCP4_PACKET_PROCESS_STD_EXCEPTION)
  577. .arg(e.what());
  578. } catch (...) {
  579. // General catch-all exception that are not caught by more specific
  580. // catches. This one is for other exceptions, not derived from
  581. // std::exception.
  582. LOG_ERROR(packet4_logger, DHCP4_PACKET_PROCESS_EXCEPTION);
  583. }
  584. }
  585. return (true);
  586. }
  587. void
  588. Dhcpv4Srv::run_one() {
  589. // client's message and server's response
  590. Pkt4Ptr query;
  591. Pkt4Ptr rsp;
  592. try {
  593. uint32_t timeout = 1000;
  594. LOG_DEBUG(packet4_logger, DBG_DHCP4_DETAIL, DHCP4_BUFFER_WAIT).arg(timeout);
  595. query = receivePacket(timeout);
  596. // Log if packet has arrived. We can't log the detailed information
  597. // about the DHCP message because it hasn't been unpacked/parsed
  598. // yet, and it can't be parsed at this point because hooks will
  599. // have to process it first. The only information available at this
  600. // point are: the interface, source address and destination addresses
  601. // and ports.
  602. if (query) {
  603. LOG_DEBUG(packet4_logger, DBG_DHCP4_BASIC, DHCP4_BUFFER_RECEIVED)
  604. .arg(query->getRemoteAddr().toText())
  605. .arg(query->getRemotePort())
  606. .arg(query->getLocalAddr().toText())
  607. .arg(query->getLocalPort())
  608. .arg(query->getIface());
  609. } else {
  610. LOG_DEBUG(packet4_logger, DBG_DHCP4_DETAIL, DHCP4_BUFFER_WAIT_INTERRUPTED)
  611. .arg(timeout);
  612. }
  613. } catch (const SignalInterruptOnSelect) {
  614. // Packet reception interrupted because a signal has been received.
  615. // This is not an error because we might have received a SIGTERM,
  616. // SIGINT, SIGHUP or SIGCHILD which are handled by the server. For
  617. // signals that are not handled by the server we rely on the default
  618. // behavior of the system.
  619. LOG_DEBUG(packet4_logger, DBG_DHCP4_DETAIL, DHCP4_BUFFER_WAIT_SIGNAL)
  620. .arg(signal_set_->getNext());
  621. } catch (const std::exception& e) {
  622. // Log all other errors.
  623. LOG_ERROR(packet4_logger, DHCP4_BUFFER_RECEIVE_FAIL).arg(e.what());
  624. }
  625. // Handle next signal received by the process. It must be called after
  626. // an attempt to receive a packet to properly handle server shut down.
  627. // The SIGTERM or SIGINT will be received prior to, or during execution
  628. // of select() (select is invoked by receivePacket()). When that
  629. // happens, select will be interrupted. The signal handler will be
  630. // invoked immediately after select(). The handler will set the
  631. // shutdown flag and cause the process to terminate before the next
  632. // select() function is called. If the function was called before
  633. // receivePacket the process could wait up to the duration of timeout
  634. // of select() to terminate.
  635. try {
  636. handleSignal();
  637. } catch (const std::exception& e) {
  638. // Standard exception occurred. Let's be on the safe side to
  639. // catch std::exception.
  640. LOG_ERROR(dhcp4_logger, DHCP4_HANDLE_SIGNAL_EXCEPTION)
  641. .arg(e.what());
  642. }
  643. // Timeout may be reached or signal received, which breaks select()
  644. // with no reception occurred. No need to log anything here because
  645. // we have logged right after the call to receivePacket().
  646. if (!query) {
  647. return;
  648. }
  649. processPacket(query, rsp);
  650. if (!rsp) {
  651. return;
  652. }
  653. try {
  654. // Now all fields and options are constructed into output wire buffer.
  655. // Option objects modification does not make sense anymore. Hooks
  656. // can only manipulate wire buffer at this stage.
  657. // Let's execute all callouts registered for buffer4_send
  658. if (HooksManager::calloutsPresent(Hooks.hook_index_buffer4_send_)) {
  659. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  660. // Delete previously set arguments
  661. callout_handle->deleteAllArguments();
  662. // Enable copying options from the packet within hook library.
  663. ScopedEnableOptionsCopy<Pkt4> resp4_options_copy(rsp);
  664. // Pass incoming packet as argument
  665. callout_handle->setArgument("response4", rsp);
  666. // Call callouts
  667. HooksManager::callCallouts(Hooks.hook_index_buffer4_send_,
  668. *callout_handle);
  669. // Callouts decided to skip the next processing step. The next
  670. // processing step would to parse the packet, so skip at this
  671. // stage means drop.
  672. if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  673. LOG_DEBUG(hooks_logger, DBG_DHCP4_HOOKS,
  674. DHCP4_HOOK_BUFFER_SEND_SKIP)
  675. .arg(rsp->getLabel());
  676. return;
  677. }
  678. /// @todo: Add support for DROP status.
  679. callout_handle->getArgument("response4", rsp);
  680. }
  681. LOG_DEBUG(packet4_logger, DBG_DHCP4_BASIC, DHCP4_PACKET_SEND)
  682. .arg(rsp->getLabel())
  683. .arg(rsp->getName())
  684. .arg(static_cast<int>(rsp->getType()))
  685. .arg(rsp->getLocalAddr())
  686. .arg(rsp->getLocalPort())
  687. .arg(rsp->getRemoteAddr())
  688. .arg(rsp->getRemotePort())
  689. .arg(rsp->getIface());
  690. LOG_DEBUG(packet4_logger, DBG_DHCP4_DETAIL_DATA,
  691. DHCP4_RESPONSE_DATA)
  692. .arg(rsp->getLabel())
  693. .arg(rsp->getName())
  694. .arg(static_cast<int>(rsp->getType()))
  695. .arg(rsp->toText());
  696. sendPacket(rsp);
  697. // Update statistics accordingly for sent packet.
  698. processStatsSent(rsp);
  699. } catch (const std::exception& e) {
  700. LOG_ERROR(packet4_logger, DHCP4_PACKET_SEND_FAIL)
  701. .arg(rsp->getLabel())
  702. .arg(e.what());
  703. }
  704. }
  705. void
  706. Dhcpv4Srv::processPacket(Pkt4Ptr& query, Pkt4Ptr& rsp) {
  707. // Log reception of the packet. We need to increase it early, as any
  708. // failures in unpacking will cause the packet to be dropped. We
  709. // will increase type specific statistic further down the road.
  710. // See processStatsReceived().
  711. isc::stats::StatsMgr::instance().addValue("pkt4-received",
  712. static_cast<int64_t>(1));
  713. bool skip_unpack = false;
  714. // The packet has just been received so contains the uninterpreted wire
  715. // data; execute callouts registered for buffer4_receive.
  716. if (HooksManager::calloutsPresent(Hooks.hook_index_buffer4_receive_)) {
  717. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  718. // Delete previously set arguments
  719. callout_handle->deleteAllArguments();
  720. // Enable copying options from the packet within hook library.
  721. ScopedEnableOptionsCopy<Pkt4> query4_options_copy(query);
  722. // Pass incoming packet as argument
  723. callout_handle->setArgument("query4", query);
  724. // Call callouts
  725. HooksManager::callCallouts(Hooks.hook_index_buffer4_receive_,
  726. *callout_handle);
  727. // Callouts decided to skip the next processing step. The next
  728. // processing step would to parse the packet, so skip at this
  729. // stage means that callouts did the parsing already, so server
  730. // should skip parsing.
  731. if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  732. LOG_DEBUG(hooks_logger, DBG_DHCP4_DETAIL,
  733. DHCP4_HOOK_BUFFER_RCVD_SKIP)
  734. .arg(query->getRemoteAddr().toText())
  735. .arg(query->getLocalAddr().toText())
  736. .arg(query->getIface());
  737. skip_unpack = true;
  738. }
  739. callout_handle->getArgument("query4", query);
  740. /// @todo: add support for DROP status
  741. }
  742. // Unpack the packet information unless the buffer4_receive callouts
  743. // indicated they did it
  744. if (!skip_unpack) {
  745. try {
  746. LOG_DEBUG(options4_logger, DBG_DHCP4_DETAIL, DHCP4_BUFFER_UNPACK)
  747. .arg(query->getRemoteAddr().toText())
  748. .arg(query->getLocalAddr().toText())
  749. .arg(query->getIface());
  750. query->unpack();
  751. } catch (const std::exception& e) {
  752. // Failed to parse the packet.
  753. LOG_DEBUG(bad_packet4_logger, DBG_DHCP4_DETAIL,
  754. DHCP4_PACKET_DROP_0001)
  755. .arg(query->getRemoteAddr().toText())
  756. .arg(query->getLocalAddr().toText())
  757. .arg(query->getIface())
  758. .arg(e.what());
  759. // Increase the statistics of parse failues and dropped packets.
  760. isc::stats::StatsMgr::instance().addValue("pkt4-parse-failed",
  761. static_cast<int64_t>(1));
  762. isc::stats::StatsMgr::instance().addValue("pkt4-receive-drop",
  763. static_cast<int64_t>(1));
  764. return;
  765. }
  766. }
  767. // Update statistics accordingly for received packet.
  768. processStatsReceived(query);
  769. // Assign this packet to one or more classes if needed. We need to do
  770. // this before calling accept(), because getSubnet4() may need client
  771. // class information.
  772. classifyPacket(query);
  773. // Check whether the message should be further processed or discarded.
  774. // There is no need to log anything here. This function logs by itself.
  775. if (!accept(query)) {
  776. // Increase the statistic of dropped packets.
  777. isc::stats::StatsMgr::instance().addValue("pkt4-receive-drop",
  778. static_cast<int64_t>(1));
  779. return;
  780. }
  781. // We have sanity checked (in accept() that the Message Type option
  782. // exists, so we can safely get it here.
  783. int type = query->getType();
  784. LOG_DEBUG(packet4_logger, DBG_DHCP4_BASIC_DATA, DHCP4_PACKET_RECEIVED)
  785. .arg(query->getLabel())
  786. .arg(query->getName())
  787. .arg(type)
  788. .arg(query->getRemoteAddr())
  789. .arg(query->getLocalAddr())
  790. .arg(query->getIface());
  791. LOG_DEBUG(packet4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_QUERY_DATA)
  792. .arg(query->getLabel())
  793. .arg(query->toText());
  794. // Let's execute all callouts registered for pkt4_receive
  795. if (HooksManager::calloutsPresent(Hooks.hook_index_pkt4_receive_)) {
  796. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  797. // Delete previously set arguments
  798. callout_handle->deleteAllArguments();
  799. // Enable copying options from the packet within hook library.
  800. ScopedEnableOptionsCopy<Pkt4> query4_options_copy(query);
  801. // Pass incoming packet as argument
  802. callout_handle->setArgument("query4", query);
  803. // Call callouts
  804. HooksManager::callCallouts(Hooks.hook_index_pkt4_receive_,
  805. *callout_handle);
  806. // Callouts decided to skip the next processing step. The next
  807. // processing step would to process the packet, so skip at this
  808. // stage means drop.
  809. if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  810. LOG_DEBUG(hooks_logger, DBG_DHCP4_HOOKS,
  811. DHCP4_HOOK_PACKET_RCVD_SKIP)
  812. .arg(query->getLabel());
  813. return;
  814. }
  815. /// @todo: Add support for DROP status
  816. callout_handle->getArgument("query4", query);
  817. }
  818. try {
  819. switch (query->getType()) {
  820. case DHCPDISCOVER:
  821. rsp = processDiscover(query);
  822. break;
  823. case DHCPREQUEST:
  824. // Note that REQUEST is used for many things in DHCPv4: for
  825. // requesting new leases, renewing existing ones and even
  826. // for rebinding.
  827. rsp = processRequest(query);
  828. break;
  829. case DHCPRELEASE:
  830. processRelease(query);
  831. break;
  832. case DHCPDECLINE:
  833. processDecline(query);
  834. break;
  835. case DHCPINFORM:
  836. rsp = processInform(query);
  837. break;
  838. default:
  839. // Only action is to output a message if debug is enabled,
  840. // and that is covered by the debug statement before the
  841. // "switch" statement.
  842. ;
  843. }
  844. } catch (const std::exception& e) {
  845. // Catch-all exception (we used to call only isc::Exception, but
  846. // std::exception could potentially be raised and if we don't catch
  847. // it here, it would be caught in main() and the process would
  848. // terminate). Just log the problem and ignore the packet.
  849. // (The problem is logged as a debug message because debug is
  850. // disabled by default - it prevents a DDOS attack based on the
  851. // sending of problem packets.)
  852. LOG_DEBUG(bad_packet4_logger, DBG_DHCP4_BASIC,
  853. DHCP4_PACKET_DROP_0007)
  854. .arg(query->getLabel())
  855. .arg(e.what());
  856. // Increase the statistic of dropped packets.
  857. isc::stats::StatsMgr::instance().addValue("pkt4-receive-drop",
  858. static_cast<int64_t>(1));
  859. }
  860. if (!rsp) {
  861. return;
  862. }
  863. // Specifies if server should do the packing
  864. bool skip_pack = false;
  865. // Execute all callouts registered for pkt4_send
  866. if (HooksManager::calloutsPresent(Hooks.hook_index_pkt4_send_)) {
  867. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  868. // Delete all previous arguments
  869. callout_handle->deleteAllArguments();
  870. // Clear skip flag if it was set in previous callouts
  871. callout_handle->setStatus(CalloutHandle::NEXT_STEP_CONTINUE);
  872. // Enable copying options from the query and response packets within
  873. // hook library.
  874. ScopedEnableOptionsCopy<Pkt4> query_resp_options_copy(query, rsp);
  875. // Set our response
  876. callout_handle->setArgument("response4", rsp);
  877. // Also pass the corresponding query packet as argument
  878. callout_handle->setArgument("query4", query);
  879. // Call all installed callouts
  880. HooksManager::callCallouts(Hooks.hook_index_pkt4_send_,
  881. *callout_handle);
  882. // Callouts decided to skip the next processing step. The next
  883. // processing step would to send the packet, so skip at this
  884. // stage means "drop response".
  885. if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  886. LOG_DEBUG(hooks_logger, DBG_DHCP4_HOOKS,
  887. DHCP4_HOOK_PACKET_SEND_SKIP)
  888. .arg(query->getLabel());
  889. skip_pack = true;
  890. }
  891. /// @todo: Add support for DROP status
  892. }
  893. if (!skip_pack) {
  894. try {
  895. LOG_DEBUG(options4_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_PACK)
  896. .arg(rsp->getLabel());
  897. rsp->pack();
  898. } catch (const std::exception& e) {
  899. LOG_ERROR(options4_logger, DHCP4_PACKET_PACK_FAIL)
  900. .arg(rsp->getLabel())
  901. .arg(e.what());
  902. }
  903. }
  904. }
  905. string
  906. Dhcpv4Srv::srvidToString(const OptionPtr& srvid) {
  907. if (!srvid) {
  908. isc_throw(BadValue, "NULL pointer passed to srvidToString()");
  909. }
  910. boost::shared_ptr<Option4AddrLst> generated =
  911. boost::dynamic_pointer_cast<Option4AddrLst>(srvid);
  912. if (!srvid) {
  913. isc_throw(BadValue, "Pointer to invalid option passed to srvidToString()");
  914. }
  915. Option4AddrLst::AddressContainer addrs = generated->getAddresses();
  916. if (addrs.size() != 1) {
  917. isc_throw(BadValue, "Malformed option passed to srvidToString(). "
  918. << "Expected to contain a single IPv4 address.");
  919. }
  920. return (addrs[0].toText());
  921. }
  922. void
  923. Dhcpv4Srv::appendServerID(Dhcpv4Exchange& ex) {
  924. // The source address for the outbound message should have been set already.
  925. // This is the address that to the best of the server's knowledge will be
  926. // available from the client.
  927. /// @todo: perhaps we should consider some more sophisticated server id
  928. /// generation, but for the current use cases, it should be ok.
  929. OptionPtr opt_srvid(new Option4AddrLst(DHO_DHCP_SERVER_IDENTIFIER,
  930. ex.getResponse()->getLocalAddr()));
  931. ex.getResponse()->addOption(opt_srvid);
  932. }
  933. void
  934. Dhcpv4Srv::buildCfgOptionList(Dhcpv4Exchange& ex) {
  935. CfgOptionList& co_list = ex.getCfgOptionList();
  936. // Retrieve subnet.
  937. Subnet4Ptr subnet = ex.getContext()->subnet_;
  938. if (!subnet) {
  939. // All methods using the CfgOptionList object return soon when
  940. // there is no subnet so do the same
  941. return;
  942. }
  943. // Firstly, host specific options.
  944. const ConstHostPtr& host = ex.getContext()->host_;
  945. if (host && !host->getCfgOption4()->empty()) {
  946. co_list.push_back(host->getCfgOption4());
  947. }
  948. // Secondly, subnet configured options.
  949. if (!subnet->getCfgOption()->empty()) {
  950. co_list.push_back(subnet->getCfgOption());
  951. }
  952. // Each class in the incoming packet
  953. const ClientClasses& classes = ex.getQuery()->getClasses();
  954. for (ClientClasses::const_iterator cclass = classes.begin();
  955. cclass != classes.end(); ++cclass) {
  956. // Find the client class definition for this class
  957. const ClientClassDefPtr& ccdef = CfgMgr::instance().getCurrentCfg()->
  958. getClientClassDictionary()->findClass(*cclass);
  959. if (!ccdef) {
  960. // Not found: the class is not configured
  961. if (((*cclass).size() <= VENDOR_CLASS_PREFIX.size()) ||
  962. ((*cclass).compare(0, VENDOR_CLASS_PREFIX.size(), VENDOR_CLASS_PREFIX) != 0)) {
  963. // Not a VENDOR_CLASS_* so should be configured
  964. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_BASIC, DHCP4_CLASS_UNCONFIGURED)
  965. .arg(ex.getQuery()->getLabel())
  966. .arg(*cclass);
  967. }
  968. // Skip it
  969. continue;
  970. }
  971. if (ccdef->getCfgOption()->empty()) {
  972. // Skip classes which don't configure options
  973. continue;
  974. }
  975. co_list.push_back(ccdef->getCfgOption());
  976. }
  977. // Last global options
  978. if (!CfgMgr::instance().getCurrentCfg()->getCfgOption()->empty()) {
  979. co_list.push_back(CfgMgr::instance().getCurrentCfg()->getCfgOption());
  980. }
  981. }
  982. void
  983. Dhcpv4Srv::appendRequestedOptions(Dhcpv4Exchange& ex) {
  984. // Get the subnet relevant for the client. We will need it
  985. // to get the options associated with it.
  986. Subnet4Ptr subnet = ex.getContext()->subnet_;
  987. // If we can't find the subnet for the client there is no way
  988. // to get the options to be sent to a client. We don't log an
  989. // error because it will be logged by the assignLease method
  990. // anyway.
  991. if (!subnet) {
  992. return;
  993. }
  994. // Unlikely short cut
  995. const CfgOptionList& co_list = ex.getCfgOptionList();
  996. if (co_list.empty()) {
  997. return;
  998. }
  999. Pkt4Ptr query = ex.getQuery();
  1000. // try to get the 'Parameter Request List' option which holds the
  1001. // codes of requested options.
  1002. OptionUint8ArrayPtr option_prl = boost::dynamic_pointer_cast<
  1003. OptionUint8Array>(query->getOption(DHO_DHCP_PARAMETER_REQUEST_LIST));
  1004. // If there is no PRL option in the message from the client then
  1005. // there is nothing to do.
  1006. if (!option_prl) {
  1007. return;
  1008. }
  1009. Pkt4Ptr resp = ex.getResponse();
  1010. // Get the codes of requested options.
  1011. const std::vector<uint8_t>& requested_opts = option_prl->getValues();
  1012. // For each requested option code get the instance of the option
  1013. // to be returned to the client.
  1014. for (std::vector<uint8_t>::const_iterator opt = requested_opts.begin();
  1015. opt != requested_opts.end(); ++opt) {
  1016. // Add nothing when it is already there
  1017. if (!resp->getOption(*opt)) {
  1018. // Iterate on the configured option list
  1019. for (CfgOptionList::const_iterator copts = co_list.begin();
  1020. copts != co_list.end(); ++copts) {
  1021. OptionDescriptor desc = (*copts)->get("dhcp4", *opt);
  1022. // Got it: add it and jump to the outer loop
  1023. if (desc.option_) {
  1024. resp->addOption(desc.option_);
  1025. break;
  1026. }
  1027. }
  1028. }
  1029. }
  1030. }
  1031. void
  1032. Dhcpv4Srv::appendRequestedVendorOptions(Dhcpv4Exchange& ex) {
  1033. // Get the configured subnet suitable for the incoming packet.
  1034. Subnet4Ptr subnet = ex.getContext()->subnet_;
  1035. // Leave if there is no subnet matching the incoming packet.
  1036. // There is no need to log the error message here because
  1037. // it will be logged in the assignLease() when it fails to
  1038. // pick the suitable subnet. We don't want to duplicate
  1039. // error messages in such case.
  1040. if (!subnet) {
  1041. return;
  1042. }
  1043. // Unlikely short cut
  1044. const CfgOptionList& co_list = ex.getCfgOptionList();
  1045. if (co_list.empty()) {
  1046. return;
  1047. }
  1048. // Try to get the vendor option
  1049. boost::shared_ptr<OptionVendor> vendor_req = boost::dynamic_pointer_cast<
  1050. OptionVendor>(ex.getQuery()->getOption(DHO_VIVSO_SUBOPTIONS));
  1051. if (!vendor_req) {
  1052. return;
  1053. }
  1054. uint32_t vendor_id = vendor_req->getVendorId();
  1055. // Let's try to get ORO within that vendor-option
  1056. /// @todo This is very specific to vendor-id=4491 (Cable Labs). Other
  1057. /// vendors may have different policies.
  1058. OptionUint8ArrayPtr oro =
  1059. boost::dynamic_pointer_cast<OptionUint8Array>(vendor_req->getOption(DOCSIS3_V4_ORO));
  1060. // Option ORO not found. Don't do anything then.
  1061. if (!oro) {
  1062. return;
  1063. }
  1064. boost::shared_ptr<OptionVendor> vendor_rsp(new OptionVendor(Option::V4, vendor_id));
  1065. // Get the list of options that client requested.
  1066. bool added = false;
  1067. const std::vector<uint8_t>& requested_opts = oro->getValues();
  1068. for (std::vector<uint8_t>::const_iterator code = requested_opts.begin();
  1069. code != requested_opts.end(); ++code) {
  1070. if (!vendor_rsp->getOption(*code)) {
  1071. for (CfgOptionList::const_iterator copts = co_list.begin();
  1072. copts != co_list.end(); ++copts) {
  1073. OptionDescriptor desc = (*copts)->get(vendor_id, *code);
  1074. if (desc.option_) {
  1075. vendor_rsp->addOption(desc.option_);
  1076. added = true;
  1077. break;
  1078. }
  1079. }
  1080. }
  1081. if (added) {
  1082. ex.getResponse()->addOption(vendor_rsp);
  1083. }
  1084. }
  1085. }
  1086. void
  1087. Dhcpv4Srv::appendBasicOptions(Dhcpv4Exchange& ex) {
  1088. // Identify options that we always want to send to the
  1089. // client (if they are configured).
  1090. static const uint16_t required_options[] = {
  1091. DHO_ROUTERS,
  1092. DHO_DOMAIN_NAME_SERVERS,
  1093. DHO_DOMAIN_NAME };
  1094. static size_t required_options_size =
  1095. sizeof(required_options) / sizeof(required_options[0]);
  1096. // Get the subnet.
  1097. Subnet4Ptr subnet = ex.getContext()->subnet_;
  1098. if (!subnet) {
  1099. return;
  1100. }
  1101. // Unlikely short cut
  1102. const CfgOptionList& co_list = ex.getCfgOptionList();
  1103. if (co_list.empty()) {
  1104. return;
  1105. }
  1106. Pkt4Ptr resp = ex.getResponse();
  1107. // Try to find all 'required' options in the outgoing
  1108. // message. Those that are not present will be added.
  1109. for (int i = 0; i < required_options_size; ++i) {
  1110. OptionPtr opt = resp->getOption(required_options[i]);
  1111. if (!opt) {
  1112. // Check whether option has been configured.
  1113. for (CfgOptionList::const_iterator copts = co_list.begin();
  1114. copts != co_list.end(); ++copts) {
  1115. OptionDescriptor desc = (*copts)->get("dhcp4", required_options[i]);
  1116. if (desc.option_) {
  1117. resp->addOption(desc.option_);
  1118. break;
  1119. }
  1120. }
  1121. }
  1122. }
  1123. }
  1124. void
  1125. Dhcpv4Srv::processClientName(Dhcpv4Exchange& ex) {
  1126. // It is possible that client has sent both Client FQDN and Hostname
  1127. // option. In such case, server should prefer Client FQDN option and
  1128. // ignore the Hostname option.
  1129. try {
  1130. Pkt4Ptr resp = ex.getResponse();
  1131. Option4ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<Option4ClientFqdn>
  1132. (ex.getQuery()->getOption(DHO_FQDN));
  1133. if (fqdn) {
  1134. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL, DHCP4_CLIENT_FQDN_PROCESS)
  1135. .arg(ex.getQuery()->getLabel());
  1136. processClientFqdnOption(ex);
  1137. } else {
  1138. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL,
  1139. DHCP4_CLIENT_HOSTNAME_PROCESS)
  1140. .arg(ex.getQuery()->getLabel());
  1141. processHostnameOption(ex);
  1142. }
  1143. } catch (const Exception& e) {
  1144. // In some rare cases it is possible that the client's name processing
  1145. // fails. For example, the Hostname option may be malformed, or there
  1146. // may be an error in the server's logic which would cause multiple
  1147. // attempts to add the same option to the response message. This
  1148. // error message aggregates all these errors so they can be diagnosed
  1149. // from the log. We don't want to throw an exception here because,
  1150. // it will impact the processing of the whole packet. We rather want
  1151. // the processing to continue, even if the client's name is wrong.
  1152. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_CLIENT_NAME_PROC_FAIL)
  1153. .arg(ex.getQuery()->getLabel())
  1154. .arg(e.what());
  1155. }
  1156. }
  1157. void
  1158. Dhcpv4Srv::processClientFqdnOption(Dhcpv4Exchange& ex) {
  1159. // Obtain the FQDN option from the client's message.
  1160. Option4ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<
  1161. Option4ClientFqdn>(ex.getQuery()->getOption(DHO_FQDN));
  1162. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_CLIENT_FQDN_DATA)
  1163. .arg(ex.getQuery()->getLabel())
  1164. .arg(fqdn->toText());
  1165. // Create the DHCPv4 Client FQDN Option to be included in the server's
  1166. // response to a client.
  1167. Option4ClientFqdnPtr fqdn_resp(new Option4ClientFqdn(*fqdn));
  1168. // Set the server S, N, and O flags based on client's flags and
  1169. // current configuration.
  1170. D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
  1171. d2_mgr.adjustFqdnFlags<Option4ClientFqdn>(*fqdn, *fqdn_resp);
  1172. // Carry over the client's E flag.
  1173. fqdn_resp->setFlag(Option4ClientFqdn::FLAG_E,
  1174. fqdn->getFlag(Option4ClientFqdn::FLAG_E));
  1175. if (ex.getContext()->host_ && !ex.getContext()->host_->getHostname().empty()) {
  1176. D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
  1177. fqdn_resp->setDomainName(d2_mgr.qualifyName(ex.getContext()->host_->getHostname(),
  1178. true), Option4ClientFqdn::FULL);
  1179. } else {
  1180. // Adjust the domain name based on domain name value and type sent by the
  1181. // client and current configuration.
  1182. d2_mgr.adjustDomainName<Option4ClientFqdn>(*fqdn, *fqdn_resp);
  1183. }
  1184. // Add FQDN option to the response message. Note that, there may be some
  1185. // cases when server may choose not to include the FQDN option in a
  1186. // response to a client. In such cases, the FQDN should be removed from the
  1187. // outgoing message. In theory we could cease to include the FQDN option
  1188. // in this function until it is confirmed that it should be included.
  1189. // However, we include it here for simplicity. Functions used to acquire
  1190. // lease for a client will scan the response message for FQDN and if it
  1191. // is found they will take necessary actions to store the FQDN information
  1192. // in the lease database as well as to generate NameChangeRequests to DNS.
  1193. // If we don't store the option in the response message, we will have to
  1194. // propagate it in the different way to the functions which acquire the
  1195. // lease. This would require modifications to the API of this class.
  1196. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_RESPONSE_FQDN_DATA)
  1197. .arg(ex.getQuery()->getLabel())
  1198. .arg(fqdn_resp->toText());
  1199. ex.getResponse()->addOption(fqdn_resp);
  1200. }
  1201. void
  1202. Dhcpv4Srv::processHostnameOption(Dhcpv4Exchange& ex) {
  1203. // Fetch D2 configuration.
  1204. D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
  1205. // Obtain the Hostname option from the client's message.
  1206. OptionStringPtr opt_hostname = boost::dynamic_pointer_cast<OptionString>
  1207. (ex.getQuery()->getOption(DHO_HOST_NAME));
  1208. if (opt_hostname) {
  1209. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_CLIENT_HOSTNAME_DATA)
  1210. .arg(ex.getQuery()->getLabel())
  1211. .arg(opt_hostname->getValue());
  1212. }
  1213. AllocEngine::ClientContext4Ptr ctx = ex.getContext();
  1214. // Hostname reservations take precedence over any other configuration,
  1215. // i.e. DDNS configuration.
  1216. if (ctx->host_ && !ctx->host_->getHostname().empty()) {
  1217. // In order to send a reserved hostname value we expect that at least
  1218. // one of the following is the case: the client has sent us a hostname
  1219. // option, or the client has sent Parameter Request List option with
  1220. // the hostname option code included.
  1221. // It is going to be less expensive to first check the presence of the
  1222. // hostname option.
  1223. bool should_send_hostname = static_cast<bool>(opt_hostname);
  1224. // Hostname option is not present, so we have to check PRL option.
  1225. if (!should_send_hostname) {
  1226. OptionUint8ArrayPtr
  1227. option_prl = boost::dynamic_pointer_cast<OptionUint8Array>
  1228. (ex.getQuery()->getOption(DHO_DHCP_PARAMETER_REQUEST_LIST));
  1229. if (option_prl) {
  1230. // PRL option exists, so check if the hostname option code is
  1231. // included in it.
  1232. const std::vector<uint8_t>&
  1233. requested_opts = option_prl->getValues();
  1234. if (std::find(requested_opts.begin(), requested_opts.end(),
  1235. DHO_HOST_NAME) != requested_opts.end()) {
  1236. // Client has requested hostname via Parameter Request
  1237. // List option.
  1238. should_send_hostname = true;
  1239. }
  1240. }
  1241. }
  1242. // If the hostname or PRL option indicates that the server should
  1243. // send back a hostname option, send this option with a reserved
  1244. // name for this client.
  1245. if (should_send_hostname) {
  1246. const std::string& hostname = d2_mgr.qualifyName(ctx->host_->getHostname(),
  1247. false);
  1248. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL_DATA,
  1249. DHCP4_RESERVED_HOSTNAME_ASSIGNED)
  1250. .arg(ex.getQuery()->getLabel())
  1251. .arg(hostname);
  1252. OptionStringPtr opt_hostname_resp(new OptionString(Option::V4,
  1253. DHO_HOST_NAME,
  1254. hostname));
  1255. ex.getResponse()->addOption(opt_hostname_resp);
  1256. // We're done here.
  1257. return;
  1258. }
  1259. }
  1260. // There is no reservation for this client or the client hasn't requested
  1261. // hostname option. There is still a possibility that we'll have to send
  1262. // hostname option to this client if the client has included hostname option
  1263. // but there is no reservation, or the configuration of the server requires
  1264. // that we send the option regardless.
  1265. D2ClientConfig::ReplaceClientNameMode replace_name_mode =
  1266. d2_mgr.getD2ClientConfig()->getReplaceClientNameMode();
  1267. // If we don't have a hostname then either we'll supply it or do nothing.
  1268. if (!opt_hostname) {
  1269. // If we're configured to supply it then add it to the response.
  1270. // Use the root domain to signal later on that we should replace it.
  1271. if (replace_name_mode == D2ClientConfig::RCM_ALWAYS ||
  1272. replace_name_mode == D2ClientConfig::RCM_WHEN_NOT_PRESENT) {
  1273. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL_DATA,
  1274. DHCP4_GENERATE_FQDN)
  1275. .arg(ex.getQuery()->getLabel());
  1276. OptionStringPtr opt_hostname_resp(new OptionString(Option::V4,
  1277. DHO_HOST_NAME,
  1278. "."));
  1279. ex.getResponse()->addOption(opt_hostname_resp);
  1280. }
  1281. return;
  1282. }
  1283. // Client sent us a hostname option so figure out what to do with it.
  1284. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_CLIENT_HOSTNAME_DATA)
  1285. .arg(ex.getQuery()->getLabel())
  1286. .arg(opt_hostname->getValue());
  1287. std::string hostname = isc::util::str::trim(opt_hostname->getValue());
  1288. unsigned int label_count = OptionDataTypeUtil::getLabelCount(hostname);
  1289. // The hostname option sent by the client should be at least 1 octet long.
  1290. // If it isn't we ignore this option. (Per RFC 2131, section 3.14)
  1291. /// @todo It would be more liberal to accept this and let it fall into
  1292. /// the case of replace or less than two below.
  1293. if (label_count == 0) {
  1294. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_EMPTY_HOSTNAME)
  1295. .arg(ex.getQuery()->getLabel());
  1296. return;
  1297. }
  1298. // Copy construct the hostname provided by the client. It is entirely
  1299. // possible that we will use the hostname option provided by the client
  1300. // to perform the DNS update and we will send the same option to him to
  1301. // indicate that we accepted this hostname.
  1302. OptionStringPtr opt_hostname_resp(new OptionString(*opt_hostname));
  1303. // The hostname option may be unqualified or fully qualified. The lab_count
  1304. // holds the number of labels for the name. The number of 1 means that
  1305. // there is only root label "." (even for unqualified names, as the
  1306. // getLabelCount function treats each name as a fully qualified one).
  1307. // By checking the number of labels present in the hostname we may infer
  1308. // whether client has sent the fully qualified or unqualified hostname.
  1309. if ((replace_name_mode == D2ClientConfig::RCM_ALWAYS ||
  1310. replace_name_mode == D2ClientConfig::RCM_WHEN_PRESENT)
  1311. || label_count < 2) {
  1312. // Set to root domain to signal later on that we should replace it.
  1313. // DHO_HOST_NAME is a string option which cannot be empty.
  1314. /// @todo We may want to reconsider whether it is appropriate for the
  1315. /// client to send a root domain name as a Hostname. There are
  1316. /// also extensions to the auto generation of the client's name,
  1317. /// e.g. conversion to the puny code which may be considered at some
  1318. /// point.
  1319. /// For now, we just remain liberal and expect that the DNS will handle
  1320. /// conversion if needed and possible.
  1321. opt_hostname_resp->setValue(".");
  1322. } else if (label_count == 2) {
  1323. // If there are two labels, it means that the client has specified
  1324. // the unqualified name. We have to concatenate the unqualified name
  1325. // with the domain name. The false value passed as a second argument
  1326. // indicates that the trailing dot should not be appended to the
  1327. // hostname. We don't want to append the trailing dot because
  1328. // we don't know whether the hostname is partial or not and some
  1329. // clients do not handle the hostnames with the trailing dot.
  1330. opt_hostname_resp->setValue(d2_mgr.qualifyName(hostname, false));
  1331. }
  1332. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_RESPONSE_HOSTNAME_DATA)
  1333. .arg(ex.getQuery()->getLabel())
  1334. .arg(opt_hostname_resp->getValue());
  1335. ex.getResponse()->addOption(opt_hostname_resp);
  1336. }
  1337. void
  1338. Dhcpv4Srv::createNameChangeRequests(const Lease4Ptr& lease,
  1339. const Lease4Ptr& old_lease) {
  1340. if (!lease) {
  1341. isc_throw(isc::Unexpected,
  1342. "NULL lease specified when creating NameChangeRequest");
  1343. } else if (!old_lease || (old_lease && !lease->hasIdenticalFqdn(*old_lease))) {
  1344. // We may need to generate the NameChangeRequest for the new lease. It
  1345. // will be generated only if hostname is set and if forward or reverse
  1346. // update has been requested.
  1347. queueNCR(CHG_ADD, lease);
  1348. }
  1349. }
  1350. void
  1351. Dhcpv4Srv::assignLease(Dhcpv4Exchange& ex) {
  1352. // Get the pointers to the query and the response messages.
  1353. Pkt4Ptr query = ex.getQuery();
  1354. Pkt4Ptr resp = ex.getResponse();
  1355. // Get the context.
  1356. AllocEngine::ClientContext4Ptr ctx = ex.getContext();
  1357. // Subnet should have been already selected when the context was created.
  1358. Subnet4Ptr subnet = ctx->subnet_;
  1359. if (!subnet) {
  1360. // This particular client is out of luck today. We do not have
  1361. // information about the subnet he is connected to. This likely means
  1362. // misconfiguration of the server (or some relays).
  1363. // Perhaps this should be logged on some higher level?
  1364. LOG_ERROR(bad_packet4_logger, DHCP4_PACKET_NAK_0001)
  1365. .arg(query->getLabel())
  1366. .arg(query->getRemoteAddr().toText())
  1367. .arg(query->getName());
  1368. resp->setType(DHCPNAK);
  1369. resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  1370. return;
  1371. }
  1372. // Get the server identifier. It will be used to determine the state
  1373. // of the client.
  1374. OptionCustomPtr opt_serverid = boost::dynamic_pointer_cast<
  1375. OptionCustom>(query->getOption(DHO_DHCP_SERVER_IDENTIFIER));
  1376. // Check if the client has sent a requested IP address option or
  1377. // ciaddr.
  1378. OptionCustomPtr opt_requested_address = boost::dynamic_pointer_cast<
  1379. OptionCustom>(query->getOption(DHO_DHCP_REQUESTED_ADDRESS));
  1380. IOAddress hint(IOAddress::IPV4_ZERO_ADDRESS());
  1381. if (opt_requested_address) {
  1382. hint = opt_requested_address->readAddress();
  1383. } else if (!query->getCiaddr().isV4Zero()) {
  1384. hint = query->getCiaddr();
  1385. }
  1386. HWAddrPtr hwaddr = query->getHWAddr();
  1387. // "Fake" allocation is processing of DISCOVER message. We pretend to do an
  1388. // allocation, but we do not put the lease in the database. That is ok,
  1389. // because we do not guarantee that the user will get that exact lease. If
  1390. // the user selects this server to do actual allocation (i.e. sends REQUEST)
  1391. // it should include this hint. That will help us during the actual lease
  1392. // allocation.
  1393. bool fake_allocation = (query->getType() == DHCPDISCOVER);
  1394. // Get client-id. It is not mandatory in DHCPv4.
  1395. ClientIdPtr client_id = ex.getContext()->clientid_;
  1396. // If there is no server id and there is a Requested IP Address option
  1397. // the client is in the INIT-REBOOT state in which the server has to
  1398. // determine whether the client's notion of the address is correct
  1399. // and whether the client is known, i.e., has a lease.
  1400. if (!fake_allocation && !opt_serverid && opt_requested_address) {
  1401. LOG_INFO(lease4_logger, DHCP4_INIT_REBOOT)
  1402. .arg(query->getLabel())
  1403. .arg(hint.toText());
  1404. Lease4Ptr lease;
  1405. if (client_id) {
  1406. lease = LeaseMgrFactory::instance().getLease4(*client_id, subnet->getID());
  1407. }
  1408. if (!lease && hwaddr) {
  1409. lease = LeaseMgrFactory::instance().getLease4(*hwaddr, subnet->getID());
  1410. }
  1411. // Check the first error case: unknown client. We check this before
  1412. // validating the address sent because we don't want to respond if
  1413. // we don't know this client.
  1414. if (!lease || !lease->belongsToClient(hwaddr, client_id)) {
  1415. LOG_DEBUG(bad_packet4_logger, DBG_DHCP4_DETAIL,
  1416. DHCP4_NO_LEASE_INIT_REBOOT)
  1417. .arg(query->getLabel())
  1418. .arg(hint.toText());
  1419. ex.deleteResponse();
  1420. return;
  1421. }
  1422. // We know this client so we can now check if his notion of the
  1423. // IP address is correct.
  1424. if (lease && (lease->addr_ != hint)) {
  1425. LOG_DEBUG(bad_packet4_logger, DBG_DHCP4_DETAIL,
  1426. DHCP4_PACKET_NAK_0002)
  1427. .arg(query->getLabel())
  1428. .arg(hint.toText());
  1429. resp->setType(DHCPNAK);
  1430. resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  1431. return;
  1432. }
  1433. }
  1434. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  1435. std::string hostname;
  1436. bool fqdn_fwd = false;
  1437. bool fqdn_rev = false;
  1438. OptionStringPtr opt_hostname;
  1439. Option4ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<
  1440. Option4ClientFqdn>(resp->getOption(DHO_FQDN));
  1441. if (fqdn) {
  1442. hostname = fqdn->getDomainName();
  1443. CfgMgr::instance().getD2ClientMgr().getUpdateDirections(*fqdn,
  1444. fqdn_fwd,
  1445. fqdn_rev);
  1446. } else {
  1447. opt_hostname = boost::dynamic_pointer_cast<OptionString>
  1448. (resp->getOption(DHO_HOST_NAME));
  1449. if (opt_hostname) {
  1450. hostname = opt_hostname->getValue();
  1451. // DHO_HOST_NAME is string option which cannot be blank,
  1452. // we use "." to know we should replace it with a fully
  1453. // generated name. The local string variable needs to be
  1454. // blank in logic below.
  1455. if (hostname == ".") {
  1456. hostname = "";
  1457. }
  1458. /// @todo It could be configurable what sort of updates the
  1459. /// server is doing when Hostname option was sent.
  1460. fqdn_fwd = true;
  1461. fqdn_rev = true;
  1462. }
  1463. }
  1464. // We need to set these values in the context as they haven't been set yet.
  1465. ctx->requested_address_ = hint;
  1466. ctx->fwd_dns_update_ = fqdn_fwd;
  1467. ctx->rev_dns_update_ = fqdn_rev;
  1468. ctx->hostname_ = hostname;
  1469. ctx->fake_allocation_ = fake_allocation;
  1470. ctx->callout_handle_ = callout_handle;
  1471. Lease4Ptr lease = alloc_engine_->allocateLease4(*ctx);
  1472. if (lease) {
  1473. // We have a lease! Let's set it in the packet and send it back to
  1474. // the client.
  1475. LOG_INFO(lease4_logger, fake_allocation ? DHCP4_LEASE_ADVERT : DHCP4_LEASE_ALLOC)
  1476. .arg(query->getLabel())
  1477. .arg(lease->addr_.toText());
  1478. resp->setYiaddr(lease->addr_);
  1479. /// @todo The server should check what ciaddr the client has supplied
  1480. /// in ciaddr. Currently the ciaddr is ignored except for the subnet
  1481. /// selection. If the client supplied an invalid address, the server
  1482. /// will also return an invalid address here.
  1483. if (!fake_allocation) {
  1484. // If this is a renewing client it will set a ciaddr which the
  1485. // server may include in the response. If this is a new allocation
  1486. // the client will set ciaddr to 0 and this will also be propagated
  1487. // to the server's resp.
  1488. resp->setCiaddr(query->getCiaddr());
  1489. }
  1490. // If there has been Client FQDN or Hostname option sent, but the
  1491. // hostname is empty, it means that server is responsible for
  1492. // generating the entire hostname for the client. The example of the
  1493. // client's name, generated from the IP address is: host-192-0-2-3.
  1494. if ((fqdn || opt_hostname) && lease->hostname_.empty()) {
  1495. // Note that if we have received the hostname option, rather than
  1496. // Client FQDN the trailing dot is not appended to the generated
  1497. // hostname because some clients don't handle the trailing dot in
  1498. // the hostname. Whether the trailing dot is appended or not is
  1499. // controlled by the second argument to the generateFqdn().
  1500. lease->hostname_ = CfgMgr::instance().getD2ClientMgr()
  1501. .generateFqdn(lease->addr_, static_cast<bool>(fqdn));
  1502. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL, DHCP4_RESPONSE_HOSTNAME_GENERATE)
  1503. .arg(query->getLabel())
  1504. .arg(lease->hostname_);
  1505. // The operations below are rather safe, but we want to catch
  1506. // any potential exceptions (e.g. invalid lease database backend
  1507. // implementation) and log an error.
  1508. try {
  1509. if (!fake_allocation) {
  1510. // The lease update should be safe, because the lease should
  1511. // be already in the database. In most cases the exception
  1512. // would be thrown if the lease was missing.
  1513. LeaseMgrFactory::instance().updateLease4(lease);
  1514. }
  1515. // The name update in the option should be also safe,
  1516. // because the generated name is well formed.
  1517. if (fqdn) {
  1518. fqdn->setDomainName(lease->hostname_,
  1519. Option4ClientFqdn::FULL);
  1520. } else if (opt_hostname) {
  1521. opt_hostname->setValue(lease->hostname_);
  1522. }
  1523. } catch (const Exception& ex) {
  1524. LOG_ERROR(ddns4_logger, DHCP4_NAME_GEN_UPDATE_FAIL)
  1525. .arg(query->getLabel())
  1526. .arg(lease->hostname_)
  1527. .arg(ex.what());
  1528. }
  1529. }
  1530. // IP Address Lease time (type 51)
  1531. OptionPtr opt(new OptionUint32(Option::V4, DHO_DHCP_LEASE_TIME,
  1532. lease->valid_lft_));
  1533. resp->addOption(opt);
  1534. // Subnet mask (type 1)
  1535. resp->addOption(getNetmaskOption(subnet));
  1536. // renewal-timer (type 58)
  1537. if (!subnet->getT1().unspecified()) {
  1538. OptionUint32Ptr t1(new OptionUint32(Option::V4,
  1539. DHO_DHCP_RENEWAL_TIME,
  1540. subnet->getT1()));
  1541. resp->addOption(t1);
  1542. }
  1543. // rebind timer (type 59)
  1544. if (!subnet->getT2().unspecified()) {
  1545. OptionUint32Ptr t2(new OptionUint32(Option::V4,
  1546. DHO_DHCP_REBINDING_TIME,
  1547. subnet->getT2()));
  1548. resp->addOption(t2);
  1549. }
  1550. // Create NameChangeRequests if DDNS is enabled and this is a
  1551. // real allocation.
  1552. if (!fake_allocation && CfgMgr::instance().ddnsEnabled()) {
  1553. try {
  1554. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL, DHCP4_NCR_CREATE)
  1555. .arg(query->getLabel());
  1556. createNameChangeRequests(lease, ctx->old_lease_);
  1557. } catch (const Exception& ex) {
  1558. LOG_ERROR(ddns4_logger, DHCP4_NCR_CREATION_FAILED)
  1559. .arg(query->getLabel())
  1560. .arg(ex.what());
  1561. }
  1562. }
  1563. } else {
  1564. // Allocation engine did not allocate a lease. The engine logged
  1565. // cause of that failure.
  1566. LOG_DEBUG(bad_packet4_logger, DBG_DHCP4_DETAIL, fake_allocation ?
  1567. DHCP4_PACKET_NAK_0003 : DHCP4_PACKET_NAK_0004)
  1568. .arg(query->getLabel())
  1569. .arg(query->getCiaddr().toText())
  1570. .arg(opt_requested_address ?
  1571. opt_requested_address->readAddress().toText() : "(no address)");
  1572. resp->setType(DHCPNAK);
  1573. resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  1574. resp->delOption(DHO_FQDN);
  1575. resp->delOption(DHO_HOST_NAME);
  1576. }
  1577. }
  1578. void
  1579. Dhcpv4Srv::adjustIfaceData(Dhcpv4Exchange& ex) {
  1580. adjustRemoteAddr(ex);
  1581. // Initialize the pointers to the client's message and the server's
  1582. // response.
  1583. Pkt4Ptr query = ex.getQuery();
  1584. Pkt4Ptr response = ex.getResponse();
  1585. // The DHCPINFORM is generally unicast to the client. The only situation
  1586. // when the server is unable to unicast to the client is when the client
  1587. // doesn't include ciaddr and the message is relayed. In this case the
  1588. // server has to reply via relay agent. For other messages we send back
  1589. // through relay if message is relayed, and unicast to the client if the
  1590. // message is not relayed.
  1591. // Note that the call to this function may throw if invalid combination
  1592. // of hops and giaddr is found (hops = 0 if giaddr = 0 and hops != 0 if
  1593. // giaddr != 0). The exception will propagate down and eventually cause the
  1594. // packet to be discarded.
  1595. if (((query->getType() == DHCPINFORM) &&
  1596. ((!query->getCiaddr().isV4Zero()) ||
  1597. (!query->isRelayed() && !query->getRemoteAddr().isV4Zero()))) ||
  1598. ((query->getType() != DHCPINFORM) && !query->isRelayed())) {
  1599. response->setRemotePort(DHCP4_CLIENT_PORT);
  1600. } else {
  1601. response->setRemotePort(DHCP4_SERVER_PORT);
  1602. }
  1603. IOAddress local_addr = query->getLocalAddr();
  1604. // In many cases the query is sent to a broadcast address. This address
  1605. // apears as a local address in the query message. We can't simply copy
  1606. // this address to a response message and use it as a source address.
  1607. // Instead we will need to use the address assigned to the interface
  1608. // on which the query has been received. In other cases, we will just
  1609. // use this address as a source address for the response.
  1610. // Do the same for DHCPv4-over-DHCPv6 exchanges.
  1611. if (local_addr.isV4Bcast() || query->isDhcp4o6()) {
  1612. SocketInfo sock_info = IfaceMgr::instance().getSocket(*query);
  1613. local_addr = sock_info.addr_;
  1614. }
  1615. // We assume that there is an appropriate socket bound to this address
  1616. // and that the address is correct. This is safe assumption because
  1617. // the local address of the query is set when the query is received.
  1618. // The query sent to an incorrect address wouldn't have been received.
  1619. // However, if socket is closed for this address between the reception
  1620. // of the query and sending a response, the IfaceMgr should detect it
  1621. // and return an error.
  1622. response->setLocalAddr(local_addr);
  1623. // In many cases the query is sent to a broadcast address. This address
  1624. // appears as a local address in the query message. Therefore we can't
  1625. // simply copy local address from the query and use it as a source
  1626. // address for the response. Instead, we have to check what address our
  1627. // socket is bound to and use it as a source address. This operation
  1628. // may throw if for some reason the socket is closed.
  1629. /// @todo Consider an optimization that we use local address from
  1630. /// the query if this address is not broadcast.
  1631. response->setLocalPort(DHCP4_SERVER_PORT);
  1632. response->setIface(query->getIface());
  1633. response->setIndex(query->getIndex());
  1634. }
  1635. void
  1636. Dhcpv4Srv::adjustRemoteAddr(Dhcpv4Exchange& ex) {
  1637. // Initialize the pointers to the client's message and the server's
  1638. // response.
  1639. Pkt4Ptr query = ex.getQuery();
  1640. Pkt4Ptr response = ex.getResponse();
  1641. // DHCPv4-over-DHCPv6 is simple
  1642. if (query->isDhcp4o6()) {
  1643. response->setRemoteAddr(query->getRemoteAddr());
  1644. return;
  1645. }
  1646. // The DHCPINFORM is slightly different than other messages in a sense
  1647. // that the server should always unicast the response to the ciaddr.
  1648. // It appears however that some clients don't set the ciaddr. We still
  1649. // want to provision these clients and we do what we can't to send the
  1650. // packet to the address where client can receive it.
  1651. if (query->getType() == DHCPINFORM) {
  1652. // If client adheres to RFC2131 it will set the ciaddr and in this
  1653. // case we always unicast our response to this address.
  1654. if (!query->getCiaddr().isV4Zero()) {
  1655. response->setRemoteAddr(query->getCiaddr());
  1656. // If we received DHCPINFORM via relay and the ciaddr is not set we
  1657. // will try to send the response via relay. The caveat is that the
  1658. // relay will not have any idea where to forward the packet because
  1659. // the yiaddr is likely not set. So, the broadcast flag is set so
  1660. // as the response may be broadcast.
  1661. } else if (query->isRelayed()) {
  1662. response->setRemoteAddr(query->getGiaddr());
  1663. response->setFlags(response->getFlags() | BOOTP_BROADCAST);
  1664. // If there is no ciaddr and no giaddr the only thing we can do is
  1665. // to use the source address of the packet.
  1666. } else {
  1667. response->setRemoteAddr(query->getRemoteAddr());
  1668. }
  1669. // Remote address is now set so return.
  1670. return;
  1671. }
  1672. // If received relayed message, server responds to the relay address.
  1673. if (query->isRelayed()) {
  1674. // The client should set the ciaddr when sending the DHCPINFORM
  1675. // but in case he didn't, the relay may not be able to determine the
  1676. // address of the client, because yiaddr is not set when responding
  1677. // to Confirm and the only address available was the source address
  1678. // of the client. The source address is however not used here because
  1679. // the message is relayed. Therefore, we set the BROADCAST flag so
  1680. // as the relay can broadcast the packet.
  1681. if ((query->getType() == DHCPINFORM) &&
  1682. query->getCiaddr().isV4Zero()) {
  1683. response->setFlags(BOOTP_BROADCAST);
  1684. }
  1685. response->setRemoteAddr(query->getGiaddr());
  1686. // If giaddr is 0 but client set ciaddr, server should unicast the
  1687. // response to ciaddr.
  1688. } else if (!query->getCiaddr().isV4Zero()) {
  1689. response->setRemoteAddr(query->getCiaddr());
  1690. // We can't unicast the response to the client when sending NAK,
  1691. // because we haven't allocated address for him. Therefore,
  1692. // NAK is broadcast.
  1693. } else if (response->getType() == DHCPNAK) {
  1694. response->setRemoteAddr(IOAddress::IPV4_BCAST_ADDRESS());
  1695. // If yiaddr is set it means that we have created a lease for a client.
  1696. } else if (!response->getYiaddr().isV4Zero()) {
  1697. // If the broadcast bit is set in the flags field, we have to
  1698. // send the response to broadcast address. Client may have requested it
  1699. // because it doesn't support reception of messages on the interface
  1700. // which doesn't have an address assigned. The other case when response
  1701. // must be broadcasted is when our server does not support responding
  1702. // directly to a client without address assigned.
  1703. const bool bcast_flag = ((query->getFlags() & Pkt4::FLAG_BROADCAST_MASK) != 0);
  1704. if (!IfaceMgr::instance().isDirectResponseSupported() || bcast_flag) {
  1705. response->setRemoteAddr(IOAddress::IPV4_BCAST_ADDRESS());
  1706. // Client cleared the broadcast bit and we support direct responses
  1707. // so we should unicast the response to a newly allocated address -
  1708. // yiaddr.
  1709. } else {
  1710. response->setRemoteAddr(response ->getYiaddr());
  1711. }
  1712. // In most cases, we should have the remote address found already. If we
  1713. // found ourselves at this point, the rational thing to do is to respond
  1714. // to the address we got the query from.
  1715. } else {
  1716. response->setRemoteAddr(query->getRemoteAddr());
  1717. }
  1718. }
  1719. void
  1720. Dhcpv4Srv::setFixedFields(Dhcpv4Exchange& ex) {
  1721. Pkt4Ptr query = ex.getQuery();
  1722. Pkt4Ptr response = ex.getResponse();
  1723. // Step 1: Start with fixed fields defined on subnet level.
  1724. Subnet4Ptr subnet = ex.getContext()->subnet_;
  1725. if (subnet) {
  1726. IOAddress subnet_next_server = subnet->getSiaddr();
  1727. if (!subnet_next_server.isV4Zero()) {
  1728. response->setSiaddr(subnet_next_server);
  1729. }
  1730. }
  1731. // Step 2: Try to set the values based on classes.
  1732. // Any values defined in classes will override those from subnet level.
  1733. const ClientClasses classes = query->getClasses();
  1734. if (!classes.empty()) {
  1735. // Let's get class definitions
  1736. const ClientClassDefMapPtr& defs = CfgMgr::instance().getCurrentCfg()->
  1737. getClientClassDictionary()->getClasses();
  1738. // Now we need to iterate over the classes assigned to the
  1739. // query packet and find corresponding class defintions for it.
  1740. for (ClientClasses::const_iterator name = classes.begin();
  1741. name != classes.end(); ++name) {
  1742. ClientClassDefMap::const_iterator cl = defs->find(*name);
  1743. if (cl == defs->end()) {
  1744. // Let's skip classes that don't have definitions. Currently
  1745. // these are automatic classes VENDOR_CLASS_something, but there
  1746. // may be other classes assigned under other circumstances, e.g.
  1747. // by hooks.
  1748. continue;
  1749. }
  1750. IOAddress next_server = cl->second->getNextServer();
  1751. if (!next_server.isV4Zero()) {
  1752. response->setSiaddr(next_server);
  1753. }
  1754. const string& sname = cl->second->getSname();
  1755. if (!sname.empty()) {
  1756. // Converting string to (const uint8_t*, size_t len) format is
  1757. // tricky. reineterpret_cast is not the most elegant solution,
  1758. // but it does avoid us making unnecessary copy. We will convert
  1759. // sname and file fields in Pkt4 to string one day and life
  1760. // will be easier.
  1761. response->setSname(reinterpret_cast<const uint8_t*>(sname.c_str()),
  1762. sname.size());
  1763. }
  1764. const string& filename = cl->second->getFilename();
  1765. if (!filename.empty()) {
  1766. // Converting string to (const uint8_t*, size_t len) format is
  1767. // tricky. reineterpret_cast is not the most elegant solution,
  1768. // but it does avoid us making unnecessary copy. We will convert
  1769. // sname and file fields in Pkt4 to string one day and life
  1770. // will be easier.
  1771. response->setFile(reinterpret_cast<const uint8_t*>(filename.c_str()),
  1772. filename.size());
  1773. }
  1774. }
  1775. }
  1776. // Step 3: try to set values using HR. Any values coming from there will override
  1777. // the subnet or class values.
  1778. ex.setReservedMessageFields();
  1779. }
  1780. OptionPtr
  1781. Dhcpv4Srv::getNetmaskOption(const Subnet4Ptr& subnet) {
  1782. uint32_t netmask = getNetmask4(subnet->get().second);
  1783. OptionPtr opt(new OptionInt<uint32_t>(Option::V4,
  1784. DHO_SUBNET_MASK, netmask));
  1785. return (opt);
  1786. }
  1787. Pkt4Ptr
  1788. Dhcpv4Srv::processDiscover(Pkt4Ptr& discover) {
  1789. sanityCheck(discover, FORBIDDEN);
  1790. Dhcpv4Exchange ex(alloc_engine_, discover, selectSubnet(discover));
  1791. // If DHCPDISCOVER message contains the FQDN or Hostname option, server
  1792. // may respond to the client with the appropriate FQDN or Hostname
  1793. // option to indicate that whether it will take responsibility for
  1794. // updating DNS when the client sends DHCPREQUEST message.
  1795. processClientName(ex);
  1796. assignLease(ex);
  1797. if (!ex.getResponse()) {
  1798. // The offer is empty so return it *now*!
  1799. return (Pkt4Ptr());
  1800. }
  1801. // Adding any other options makes sense only when we got the lease.
  1802. if (!ex.getResponse()->getYiaddr().isV4Zero()) {
  1803. buildCfgOptionList(ex);
  1804. appendRequestedOptions(ex);
  1805. appendRequestedVendorOptions(ex);
  1806. // There are a few basic options that we always want to
  1807. // include in the response. If client did not request
  1808. // them we append them for him.
  1809. appendBasicOptions(ex);
  1810. // Set fixed fields (siaddr, sname, filename) if defined in
  1811. // the reservation, class or subnet specific configuration.
  1812. setFixedFields(ex);
  1813. } else {
  1814. // If the server can't offer an address, it drops the packet.
  1815. return (Pkt4Ptr());
  1816. }
  1817. // Set the src/dest IP address, port and interface for the outgoing
  1818. // packet.
  1819. adjustIfaceData(ex);
  1820. appendServerID(ex);
  1821. return (ex.getResponse());
  1822. }
  1823. Pkt4Ptr
  1824. Dhcpv4Srv::processRequest(Pkt4Ptr& request) {
  1825. /// @todo Uncomment this (see ticket #3116)
  1826. /// sanityCheck(request, MANDATORY);
  1827. Dhcpv4Exchange ex(alloc_engine_, request, selectSubnet(request));
  1828. // If DHCPREQUEST message contains the FQDN or Hostname option, server
  1829. // should respond to the client with the appropriate FQDN or Hostname
  1830. // option to indicate if it takes responsibility for the DNS updates.
  1831. // This is performed by the function below.
  1832. processClientName(ex);
  1833. // Note that we treat REQUEST message uniformly, regardless if this is a
  1834. // first request (requesting for new address), renewing existing address
  1835. // or even rebinding.
  1836. assignLease(ex);
  1837. if (!ex.getResponse()) {
  1838. // The ack is empty so return it *now*!
  1839. return (Pkt4Ptr());
  1840. }
  1841. // Adding any other options makes sense only when we got the lease.
  1842. if (!ex.getResponse()->getYiaddr().isV4Zero()) {
  1843. buildCfgOptionList(ex);
  1844. appendRequestedOptions(ex);
  1845. appendRequestedVendorOptions(ex);
  1846. // There are a few basic options that we always want to
  1847. // include in the response. If client did not request
  1848. // them we append them for him.
  1849. appendBasicOptions(ex);
  1850. // Set fixed fields (siaddr, sname, filename) if defined in
  1851. // the reservation, class or subnet specific configuration.
  1852. setFixedFields(ex);
  1853. }
  1854. // Set the src/dest IP address, port and interface for the outgoing
  1855. // packet.
  1856. adjustIfaceData(ex);
  1857. appendServerID(ex);
  1858. return (ex.getResponse());
  1859. }
  1860. void
  1861. Dhcpv4Srv::processRelease(Pkt4Ptr& release) {
  1862. /// @todo Uncomment this (see ticket #3116)
  1863. /// sanityCheck(release, MANDATORY);
  1864. // Try to find client-id. Note that for the DHCPRELEASE we don't check if the
  1865. // match-client-id configuration parameter is disabled because this parameter
  1866. // is configured for subnets and we don't select subnet for the DHCPRELEASE.
  1867. // Bogus clients usually generate new client identifiers when they first
  1868. // connect to the network, so whatever client identifier has been used to
  1869. // acquire the lease, the client identifier carried in the DHCPRELEASE is
  1870. // likely to be the same and the lease will be correctly identified in the
  1871. // lease database. If supplied client identifier differs from the one used
  1872. // to acquire the lease then the lease will remain in the database and
  1873. // simply expire.
  1874. ClientIdPtr client_id;
  1875. OptionPtr opt = release->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  1876. if (opt) {
  1877. client_id = ClientIdPtr(new ClientId(opt->getData()));
  1878. }
  1879. try {
  1880. // Do we have a lease for that particular address?
  1881. Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(release->getCiaddr());
  1882. if (!lease) {
  1883. // No such lease - bogus release
  1884. LOG_DEBUG(lease4_logger, DBG_DHCP4_DETAIL, DHCP4_RELEASE_FAIL_NO_LEASE)
  1885. .arg(release->getLabel())
  1886. .arg(release->getCiaddr().toText());
  1887. return;
  1888. }
  1889. if (!lease->belongsToClient(release->getHWAddr(), client_id)) {
  1890. LOG_DEBUG(lease4_logger, DBG_DHCP4_DETAIL, DHCP4_RELEASE_FAIL_WRONG_CLIENT)
  1891. .arg(release->getLabel())
  1892. .arg(release->getCiaddr().toText());
  1893. return;
  1894. }
  1895. bool skip = false;
  1896. // Execute all callouts registered for lease4_release
  1897. if (HooksManager::calloutsPresent(Hooks.hook_index_lease4_release_)) {
  1898. CalloutHandlePtr callout_handle = getCalloutHandle(release);
  1899. // Delete all previous arguments
  1900. callout_handle->deleteAllArguments();
  1901. // Enable copying options from the packet within hook library.
  1902. ScopedEnableOptionsCopy<Pkt4> query4_options_copy(release);
  1903. // Pass the original packet
  1904. callout_handle->setArgument("query4", release);
  1905. // Pass the lease to be updated
  1906. callout_handle->setArgument("lease4", lease);
  1907. // Call all installed callouts
  1908. HooksManager::callCallouts(Hooks.hook_index_lease4_release_,
  1909. *callout_handle);
  1910. // Callouts decided to skip the next processing step. The next
  1911. // processing step would to send the packet, so skip at this
  1912. // stage means "drop response".
  1913. if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  1914. skip = true;
  1915. LOG_DEBUG(hooks_logger, DBG_DHCP4_HOOKS,
  1916. DHCP4_HOOK_LEASE4_RELEASE_SKIP)
  1917. .arg(release->getLabel());
  1918. }
  1919. /// @todo add support for DROP status
  1920. }
  1921. // Callout didn't indicate to skip the release process. Let's release
  1922. // the lease.
  1923. if (!skip) {
  1924. bool success = LeaseMgrFactory::instance().deleteLease(lease->addr_);
  1925. if (success) {
  1926. // Release successful
  1927. LOG_INFO(lease4_logger, DHCP4_RELEASE)
  1928. .arg(release->getLabel())
  1929. .arg(lease->addr_.toText());
  1930. // Need to decrease statistic for assigned addresses.
  1931. StatsMgr::instance().addValue(
  1932. StatsMgr::generateName("subnet", lease->subnet_id_, "assigned-addresses"),
  1933. static_cast<int64_t>(-1));
  1934. // Remove existing DNS entries for the lease, if any.
  1935. queueNCR(CHG_REMOVE, lease);
  1936. } else {
  1937. // Release failed
  1938. LOG_ERROR(lease4_logger, DHCP4_RELEASE_FAIL)
  1939. .arg(release->getLabel())
  1940. .arg(lease->addr_.toText());
  1941. }
  1942. }
  1943. } catch (const isc::Exception& ex) {
  1944. LOG_ERROR(lease4_logger, DHCP4_RELEASE_EXCEPTION)
  1945. .arg(release->getLabel())
  1946. .arg(release->getCiaddr())
  1947. .arg(ex.what());
  1948. }
  1949. }
  1950. void
  1951. Dhcpv4Srv::processDecline(Pkt4Ptr& decline) {
  1952. // Server-id is mandatory in DHCPDECLINE (see table 5, RFC2131)
  1953. /// @todo Uncomment this (see ticket #3116)
  1954. // sanityCheck(decline, MANDATORY);
  1955. // Client is supposed to specify the address being declined in
  1956. // Requested IP address option, but must not set its ciaddr.
  1957. // (again, see table 5 in RFC2131).
  1958. OptionCustomPtr opt_requested_address = boost::dynamic_pointer_cast<
  1959. OptionCustom>(decline->getOption(DHO_DHCP_REQUESTED_ADDRESS));
  1960. if (!opt_requested_address) {
  1961. isc_throw(RFCViolation, "Mandatory 'Requested IP address' option missing"
  1962. "in DHCPDECLINE sent from " << decline->getLabel());
  1963. }
  1964. IOAddress addr(opt_requested_address->readAddress());
  1965. // We could also extract client's address from ciaddr, but that's clearly
  1966. // against RFC2131.
  1967. // Now we need to check whether this address really belongs to the client
  1968. // that attempts to decline it.
  1969. const Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(addr);
  1970. if (!lease) {
  1971. // Client tried to decline an address, but we don't have a lease for
  1972. // that address. Let's ignore it.
  1973. //
  1974. // We could assume that we're recovering from a mishandled migration
  1975. // to a new server and mark the address as declined, but the window of
  1976. // opportunity for that to be useful is small and the attack vector
  1977. // would be pretty severe.
  1978. LOG_WARN(dhcp4_logger, DHCP4_DECLINE_LEASE_NOT_FOUND)
  1979. .arg(addr.toText()).arg(decline->getLabel());
  1980. return;
  1981. }
  1982. // Get client-id, if available.
  1983. OptionPtr opt_clientid = decline->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  1984. ClientIdPtr client_id;
  1985. if (opt_clientid) {
  1986. client_id.reset(new ClientId(opt_clientid->getData()));
  1987. }
  1988. // Check if the client attempted to decline a lease it doesn't own.
  1989. if (!lease->belongsToClient(decline->getHWAddr(), client_id)) {
  1990. // Get printable hardware addresses
  1991. string client_hw = decline->getHWAddr() ?
  1992. decline->getHWAddr()->toText(false) : "(none)";
  1993. string lease_hw = lease->hwaddr_ ?
  1994. lease->hwaddr_->toText(false) : "(none)";
  1995. // Get printable client-ids
  1996. string client_id_txt = client_id ? client_id->toText() : "(none)";
  1997. string lease_id_txt = lease->client_id_ ?
  1998. lease->client_id_->toText() : "(none)";
  1999. // Print the warning and we're done here.
  2000. LOG_WARN(dhcp4_logger, DHCP4_DECLINE_LEASE_MISMATCH)
  2001. .arg(addr.toText()).arg(decline->getLabel())
  2002. .arg(client_hw).arg(lease_hw).arg(client_id_txt).arg(lease_id_txt);
  2003. return;
  2004. }
  2005. // Ok, all is good. The client is reporting its own address. Let's
  2006. // process it.
  2007. declineLease(lease, decline);
  2008. }
  2009. void
  2010. Dhcpv4Srv::declineLease(const Lease4Ptr& lease, const Pkt4Ptr& decline) {
  2011. // Let's check if there are hooks installed for decline4 hook point.
  2012. // If they are, let's pass the lease and client's packet. If the hook
  2013. // sets status to drop, we reject this Decline.
  2014. if (HooksManager::calloutsPresent(Hooks.hook_index_lease4_decline_)) {
  2015. CalloutHandlePtr callout_handle = getCalloutHandle(decline);
  2016. // Delete previously set arguments
  2017. callout_handle->deleteAllArguments();
  2018. // Enable copying options from the packet within hook library.
  2019. ScopedEnableOptionsCopy<Pkt4> query4_options_copy(decline);
  2020. // Pass incoming Decline and the lease to be declined.
  2021. callout_handle->setArgument("lease4", lease);
  2022. callout_handle->setArgument("query4", decline);
  2023. // Call callouts
  2024. HooksManager::callCallouts(Hooks.hook_index_lease4_decline_,
  2025. *callout_handle);
  2026. // Check if callouts decided to drop the packet. If any of them did,
  2027. // we will drop the packet.
  2028. if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP) {
  2029. LOG_DEBUG(hooks_logger, DBG_DHCP4_HOOKS, DHCP4_HOOK_DECLINE_SKIP)
  2030. .arg(decline->getLabel()).arg(lease->addr_.toText());
  2031. return;
  2032. }
  2033. }
  2034. // Remove existing DNS entries for the lease, if any.
  2035. // queueNCR will do the necessary checks and will skip the update, if not needed.
  2036. queueNCR(CHG_REMOVE, lease);
  2037. // Bump up the statistics.
  2038. // Per subnet declined addresses counter.
  2039. StatsMgr::instance().addValue(
  2040. StatsMgr::generateName("subnet", lease->subnet_id_, "declined-addresses"),
  2041. static_cast<int64_t>(1));
  2042. // Global declined addresses counter.
  2043. StatsMgr::instance().addValue("declined-addresses", static_cast<int64_t>(1));
  2044. // We do not want to decrease the assigned-addresses at this time. While
  2045. // technically a declined address is no longer allocated, the primary usage
  2046. // of the assigned-addresses statistic is to monitor pool utilization. Most
  2047. // people would forget to include declined-addresses in the calculation,
  2048. // and simply do assigned-addresses/total-addresses. This would have a bias
  2049. // towards under-representing pool utilization, if we decreased allocated
  2050. // immediately after receiving DHCPDECLINE, rather than later when we recover
  2051. // the address.
  2052. // @todo: Call hooks.
  2053. // We need to disassociate the lease from the client. Once we move a lease
  2054. // to declined state, it is no longer associated with the client in any
  2055. // way.
  2056. lease->decline(CfgMgr::instance().getCurrentCfg()->getDeclinePeriod());
  2057. LeaseMgrFactory::instance().updateLease4(lease);
  2058. LOG_INFO(lease4_logger, DHCP4_DECLINE_LEASE).arg(lease->addr_.toText())
  2059. .arg(decline->getLabel()).arg(lease->valid_lft_);
  2060. }
  2061. Pkt4Ptr
  2062. Dhcpv4Srv::processInform(Pkt4Ptr& inform) {
  2063. // DHCPINFORM MUST not include server identifier.
  2064. sanityCheck(inform, FORBIDDEN);
  2065. Dhcpv4Exchange ex(alloc_engine_, inform, selectSubnet(inform));
  2066. Pkt4Ptr ack = ex.getResponse();
  2067. buildCfgOptionList(ex);
  2068. appendRequestedOptions(ex);
  2069. appendRequestedVendorOptions(ex);
  2070. appendBasicOptions(ex);
  2071. adjustIfaceData(ex);
  2072. // Set fixed fields (siaddr, sname, filename) if defined in
  2073. // the reservation, class or subnet specific configuration.
  2074. setFixedFields(ex);
  2075. // There are cases for the DHCPINFORM that the server receives it via
  2076. // relay but will send the response to the client's unicast address
  2077. // carried in the ciaddr. In this case, the giaddr and hops field should
  2078. // be cleared (these fields were copied by the copyDefaultFields function).
  2079. // Also Relay Agent Options should be removed if present.
  2080. if (ack->getRemoteAddr() != inform->getGiaddr()) {
  2081. LOG_DEBUG(packet4_logger, DBG_DHCP4_DETAIL, DHCP4_INFORM_DIRECT_REPLY)
  2082. .arg(inform->getLabel())
  2083. .arg(ack->getRemoteAddr())
  2084. .arg(ack->getIface());
  2085. ack->setHops(0);
  2086. ack->setGiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  2087. ack->delOption(DHO_DHCP_AGENT_OPTIONS);
  2088. }
  2089. // The DHCPACK must contain server id.
  2090. appendServerID(ex);
  2091. return (ex.getResponse());
  2092. }
  2093. bool
  2094. Dhcpv4Srv::accept(const Pkt4Ptr& query) const {
  2095. // Check that the message type is accepted by the server. We rely on the
  2096. // function called to log a message if needed.
  2097. if (!acceptMessageType(query)) {
  2098. return (false);
  2099. }
  2100. // Check if the message from directly connected client (if directly
  2101. // connected) should be dropped or processed.
  2102. if (!acceptDirectRequest(query)) {
  2103. LOG_DEBUG(bad_packet4_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_DROP_0002)
  2104. .arg(query->getLabel())
  2105. .arg(query->getIface());
  2106. return (false);
  2107. }
  2108. // Check if the DHCPv4 packet has been sent to us or to someone else.
  2109. // If it hasn't been sent to us, drop it!
  2110. if (!acceptServerId(query)) {
  2111. LOG_DEBUG(bad_packet4_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_DROP_0003)
  2112. .arg(query->getLabel())
  2113. .arg(query->getIface());
  2114. return (false);
  2115. }
  2116. return (true);
  2117. }
  2118. bool
  2119. Dhcpv4Srv::acceptDirectRequest(const Pkt4Ptr& pkt) const {
  2120. // Accept all relayed messages.
  2121. if (pkt->isRelayed()) {
  2122. return (true);
  2123. }
  2124. // Accept all DHCPv4-over-DHCPv6 messages.
  2125. if (pkt->isDhcp4o6()) {
  2126. return (true);
  2127. }
  2128. // The source address must not be zero for the DHCPINFORM message from
  2129. // the directly connected client because the server will not know where
  2130. // to respond if the ciaddr was not present.
  2131. try {
  2132. if (pkt->getType() == DHCPINFORM) {
  2133. if (pkt->getRemoteAddr().isV4Zero() &&
  2134. pkt->getCiaddr().isV4Zero()) {
  2135. return (false);
  2136. }
  2137. }
  2138. } catch (...) {
  2139. // If we got here, it is probably because the message type hasn't
  2140. // been set. But, this should not really happen assuming that
  2141. // we validate the message type prior to calling this function.
  2142. return (false);
  2143. }
  2144. return (!pkt->getLocalAddr().isV4Bcast() || selectSubnet(pkt));
  2145. }
  2146. bool
  2147. Dhcpv4Srv::acceptMessageType(const Pkt4Ptr& query) const {
  2148. // When receiving a packet without message type option, getType() will
  2149. // throw.
  2150. int type;
  2151. try {
  2152. type = query->getType();
  2153. } catch (...) {
  2154. LOG_DEBUG(bad_packet4_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_DROP_0004)
  2155. .arg(query->getLabel())
  2156. .arg(query->getIface());
  2157. return (false);
  2158. }
  2159. // If we receive a message with a non-existing type, we are logging it.
  2160. if (type > DHCPLEASEQUERYDONE) {
  2161. LOG_DEBUG(bad_packet4_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_DROP_0005)
  2162. .arg(query->getLabel())
  2163. .arg(type);
  2164. return (false);
  2165. }
  2166. // Once we know that the message type is within a range of defined DHCPv4
  2167. // messages, we do a detailed check to make sure that the received message
  2168. // is targeted at server. Note that we could have received some Offer
  2169. // message broadcasted by the other server to a relay. Even though, the
  2170. // server would rather unicast its response to a relay, let's be on the
  2171. // safe side. Also, we want to drop other messages which we don't support.
  2172. // All these valid messages that we are not going to process are dropped
  2173. // silently.
  2174. if ((type != DHCPDISCOVER) && (type != DHCPREQUEST) &&
  2175. (type != DHCPRELEASE) && (type != DHCPDECLINE) &&
  2176. (type != DHCPINFORM)) {
  2177. LOG_DEBUG(bad_packet4_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_DROP_0006)
  2178. .arg(query->getLabel())
  2179. .arg(type);
  2180. return (false);
  2181. }
  2182. return (true);
  2183. }
  2184. bool
  2185. Dhcpv4Srv::acceptServerId(const Pkt4Ptr& query) const {
  2186. // This function is meant to be called internally by the server class, so
  2187. // we rely on the caller to sanity check the pointer and we don't check
  2188. // it here.
  2189. // Check if server identifier option is present. If it is not present
  2190. // we accept the message because it is targeted to all servers.
  2191. // Note that we don't check cases that server identifier is mandatory
  2192. // but not present. This is meant to be sanity checked in other
  2193. // functions.
  2194. OptionPtr option = query->getOption(DHO_DHCP_SERVER_IDENTIFIER);
  2195. if (!option) {
  2196. return (true);
  2197. }
  2198. // Server identifier is present. Let's convert it to 4-byte address
  2199. // and try to match with server identifiers used by the server.
  2200. OptionCustomPtr option_custom =
  2201. boost::dynamic_pointer_cast<OptionCustom>(option);
  2202. // Unable to convert the option to the option type which encapsulates it.
  2203. // We treat this as non-matching server id.
  2204. if (!option_custom) {
  2205. return (false);
  2206. }
  2207. // The server identifier option should carry exactly one IPv4 address.
  2208. // If the option definition for the server identifier doesn't change,
  2209. // the OptionCustom object should have exactly one IPv4 address and
  2210. // this check is somewhat redundant. On the other hand, if someone
  2211. // breaks option it may be better to check that here.
  2212. if (option_custom->getDataFieldsNum() != 1) {
  2213. return (false);
  2214. }
  2215. // The server identifier MUST be an IPv4 address. If given address is
  2216. // v6, it is wrong.
  2217. IOAddress server_id = option_custom->readAddress();
  2218. if (!server_id.isV4()) {
  2219. return (false);
  2220. }
  2221. // This function iterates over all interfaces on which the
  2222. // server is listening to find the one which has a socket bound
  2223. // to the address carried in the server identifier option.
  2224. // This has some performance implications. However, given that
  2225. // typically there will be just a few active interfaces the
  2226. // performance hit should be acceptable. If it turns out to
  2227. // be significant, we will have to cache server identifiers
  2228. // when sockets are opened.
  2229. return (IfaceMgr::instance().hasOpenSocket(server_id));
  2230. }
  2231. void
  2232. Dhcpv4Srv::sanityCheck(const Pkt4Ptr& query, RequirementLevel serverid) {
  2233. OptionPtr server_id = query->getOption(DHO_DHCP_SERVER_IDENTIFIER);
  2234. switch (serverid) {
  2235. case FORBIDDEN:
  2236. if (server_id) {
  2237. isc_throw(RFCViolation, "Server-id option was not expected, but "
  2238. << "received in "
  2239. << query->getName());
  2240. }
  2241. break;
  2242. case MANDATORY:
  2243. if (!server_id) {
  2244. isc_throw(RFCViolation, "Server-id option was expected, but not "
  2245. " received in message "
  2246. << query->getName());
  2247. }
  2248. break;
  2249. case OPTIONAL:
  2250. // do nothing here
  2251. ;
  2252. }
  2253. // If there is HWAddress set and it is non-empty, then we're good
  2254. if (query->getHWAddr() && !query->getHWAddr()->hwaddr_.empty()) {
  2255. return;
  2256. }
  2257. // There has to be something to uniquely identify the client:
  2258. // either non-zero MAC address or client-id option present (or both)
  2259. OptionPtr client_id = query->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  2260. // If there's no client-id (or a useless one is provided, i.e. 0 length)
  2261. if (!client_id || client_id->len() == client_id->getHeaderLen()) {
  2262. isc_throw(RFCViolation, "Missing or useless client-id and no HW address "
  2263. " provided in message "
  2264. << query->getName());
  2265. }
  2266. }
  2267. void Dhcpv4Srv::classifyByVendor(const Pkt4Ptr& pkt, std::string& classes) {
  2268. // Built-in vendor class processing
  2269. boost::shared_ptr<OptionString> vendor_class =
  2270. boost::dynamic_pointer_cast<OptionString>(pkt->getOption(DHO_VENDOR_CLASS_IDENTIFIER));
  2271. if (!vendor_class) {
  2272. return;
  2273. }
  2274. pkt->addClass(VENDOR_CLASS_PREFIX + vendor_class->getValue());
  2275. classes += VENDOR_CLASS_PREFIX + vendor_class->getValue();
  2276. }
  2277. void Dhcpv4Srv::classifyPacket(const Pkt4Ptr& pkt) {
  2278. string classes = "";
  2279. // First phase: built-in vendor class processing
  2280. classifyByVendor(pkt, classes);
  2281. // Run match expressions
  2282. // Note getClientClassDictionary() cannot be null
  2283. const ClientClassDefMapPtr& defs_ptr = CfgMgr::instance().getCurrentCfg()->
  2284. getClientClassDictionary()->getClasses();
  2285. for (ClientClassDefMap::const_iterator it = defs_ptr->begin();
  2286. it != defs_ptr->end(); ++it) {
  2287. // Note second cannot be null
  2288. const ExpressionPtr& expr_ptr = it->second->getMatchExpr();
  2289. // Nothing to do without an expression to evaluate
  2290. if (!expr_ptr) {
  2291. continue;
  2292. }
  2293. // Evaluate the expression which can return false (no match),
  2294. // true (match) or raise an exception (error)
  2295. try {
  2296. bool status = evaluate(*expr_ptr, *pkt);
  2297. if (status) {
  2298. LOG_INFO(options4_logger, EVAL_RESULT)
  2299. .arg(it->first)
  2300. .arg(status);
  2301. // Matching: add the class
  2302. pkt->addClass(it->first);
  2303. classes += it->first + " ";
  2304. } else {
  2305. LOG_DEBUG(options4_logger, DBG_DHCP4_DETAIL, EVAL_RESULT)
  2306. .arg(it->first)
  2307. .arg(status);
  2308. }
  2309. } catch (const Exception& ex) {
  2310. LOG_ERROR(options4_logger, EVAL_RESULT)
  2311. .arg(it->first)
  2312. .arg(ex.what());
  2313. } catch (...) {
  2314. LOG_ERROR(options4_logger, EVAL_RESULT)
  2315. .arg(it->first)
  2316. .arg("get exception?");
  2317. }
  2318. }
  2319. if (!classes.empty()) {
  2320. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_BASIC, DHCP4_CLASS_ASSIGNED)
  2321. .arg(pkt->getLabel())
  2322. .arg(classes);
  2323. }
  2324. }
  2325. void
  2326. Dhcpv4Srv::startD2() {
  2327. D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
  2328. if (d2_mgr.ddnsEnabled()) {
  2329. // Updates are enabled, so lets start the sender, passing in
  2330. // our error handler.
  2331. // This may throw so wherever this is called needs to ready.
  2332. d2_mgr.startSender(boost::bind(&Dhcpv4Srv::d2ClientErrorHandler,
  2333. this, _1, _2));
  2334. }
  2335. }
  2336. void
  2337. Dhcpv4Srv::stopD2() {
  2338. D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
  2339. if (d2_mgr.ddnsEnabled()) {
  2340. // Updates are enabled, so lets stop the sender
  2341. d2_mgr.stopSender();
  2342. }
  2343. }
  2344. void
  2345. Dhcpv4Srv::d2ClientErrorHandler(const
  2346. dhcp_ddns::NameChangeSender::Result result,
  2347. dhcp_ddns::NameChangeRequestPtr& ncr) {
  2348. LOG_ERROR(ddns4_logger, DHCP4_DDNS_REQUEST_SEND_FAILED).
  2349. arg(result).arg((ncr ? ncr->toText() : " NULL "));
  2350. // We cannot communicate with kea-dhcp-ddns, suspend further updates.
  2351. /// @todo We may wish to revisit this, but for now we will simply turn
  2352. /// them off.
  2353. CfgMgr::instance().getD2ClientMgr().suspendUpdates();
  2354. }
  2355. // Refer to config_report so it will be embedded in the binary
  2356. const char* const* dhcp4_config_report = isc::detail::config_report;
  2357. std::string
  2358. Dhcpv4Srv::getVersion(bool extended) {
  2359. std::stringstream tmp;
  2360. tmp << VERSION;
  2361. if (extended) {
  2362. tmp << endl << EXTENDED_VERSION << endl;
  2363. tmp << "linked with:" << endl;
  2364. tmp << Logger::getVersion() << endl;
  2365. tmp << CryptoLink::getVersion() << endl;
  2366. tmp << "database:" << endl;
  2367. #ifdef HAVE_MYSQL
  2368. tmp << MySqlLeaseMgr::getDBVersion() << endl;
  2369. #endif
  2370. #ifdef HAVE_PGSQL
  2371. tmp << PgSqlLeaseMgr::getDBVersion() << endl;
  2372. #endif
  2373. #ifdef HAVE_CQL
  2374. tmp << CqlLeaseMgr::getDBVersion() << endl;
  2375. #endif
  2376. tmp << Memfile_LeaseMgr::getDBVersion();
  2377. // @todo: more details about database runtime
  2378. }
  2379. return (tmp.str());
  2380. }
  2381. void Dhcpv4Srv::processStatsReceived(const Pkt4Ptr& query) {
  2382. // Note that we're not bumping pkt4-received statistic as it was
  2383. // increased early in the packet reception code.
  2384. string stat_name = "pkt4-unknown-received";
  2385. try {
  2386. switch (query->getType()) {
  2387. case DHCPDISCOVER:
  2388. stat_name = "pkt4-discover-received";
  2389. break;
  2390. case DHCPOFFER:
  2391. // Should not happen, but let's keep a counter for it
  2392. stat_name = "pkt4-offer-received";
  2393. break;
  2394. case DHCPREQUEST:
  2395. stat_name = "pkt4-request-received";
  2396. break;
  2397. case DHCPACK:
  2398. // Should not happen, but let's keep a counter for it
  2399. stat_name = "pkt4-ack-received";
  2400. break;
  2401. case DHCPNAK:
  2402. // Should not happen, but let's keep a counter for it
  2403. stat_name = "pkt4-nak-received";
  2404. break;
  2405. case DHCPRELEASE:
  2406. stat_name = "pkt4-release-received";
  2407. break;
  2408. case DHCPDECLINE:
  2409. stat_name = "pkt4-decline-received";
  2410. break;
  2411. case DHCPINFORM:
  2412. stat_name = "pkt4-inform-received";
  2413. break;
  2414. default:
  2415. ; // do nothing
  2416. }
  2417. }
  2418. catch (...) {
  2419. // If the incoming packet doesn't have option 53 (message type)
  2420. // or a hook set pkt4_receive_skip, then Pkt4::getType() may
  2421. // throw an exception. That's ok, we'll then use the default
  2422. // name of pkt4-unknown-received.
  2423. }
  2424. isc::stats::StatsMgr::instance().addValue(stat_name,
  2425. static_cast<int64_t>(1));
  2426. }
  2427. void Dhcpv4Srv::processStatsSent(const Pkt4Ptr& response) {
  2428. // Increase generic counter for sent packets.
  2429. isc::stats::StatsMgr::instance().addValue("pkt4-sent",
  2430. static_cast<int64_t>(1));
  2431. // Increase packet type specific counter for packets sent.
  2432. string stat_name;
  2433. switch (response->getType()) {
  2434. case DHCPOFFER:
  2435. stat_name = "pkt4-offer-sent";
  2436. break;
  2437. case DHCPACK:
  2438. stat_name = "pkt4-ack-sent";
  2439. break;
  2440. case DHCPNAK:
  2441. stat_name = "pkt4-nak-sent";
  2442. break;
  2443. default:
  2444. // That should never happen
  2445. return;
  2446. }
  2447. isc::stats::StatsMgr::instance().addValue(stat_name,
  2448. static_cast<int64_t>(1));
  2449. }
  2450. int Dhcpv4Srv::getHookIndexBuffer4Receive() {
  2451. return (Hooks.hook_index_buffer4_receive_);
  2452. }
  2453. int Dhcpv4Srv::getHookIndexPkt4Receive() {
  2454. return (Hooks.hook_index_pkt4_receive_);
  2455. }
  2456. int Dhcpv4Srv::getHookIndexSubnet4Select() {
  2457. return (Hooks.hook_index_subnet4_select_);
  2458. }
  2459. int Dhcpv4Srv::getHookIndexLease4Release() {
  2460. return (Hooks.hook_index_lease4_release_);
  2461. }
  2462. int Dhcpv4Srv::getHookIndexPkt4Send() {
  2463. return (Hooks.hook_index_pkt4_send_);
  2464. }
  2465. int Dhcpv4Srv::getHookIndexBuffer4Send() {
  2466. return (Hooks.hook_index_buffer4_send_);
  2467. }
  2468. int Dhcpv4Srv::getHookIndexLease4Decline() {
  2469. return (Hooks.hook_index_lease4_decline_);
  2470. }
  2471. } // namespace dhcp
  2472. } // namespace isc