dhcp4_srv.cc 110 KB

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