dhcp4_srv.cc 110 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908
  1. // Copyright (C) 2011-2017 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().getCurrentCfg()->getEchoClientId();
  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 3527)
  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 failures 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_OPTION_SPACE, *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_OPTION_SPACE,
  1135. required_options[i]);
  1136. if (desc.option_) {
  1137. resp->addOption(desc.option_);
  1138. break;
  1139. }
  1140. }
  1141. }
  1142. }
  1143. }
  1144. void
  1145. Dhcpv4Srv::processClientName(Dhcpv4Exchange& ex) {
  1146. // It is possible that client has sent both Client FQDN and Hostname
  1147. // option. In such case, server should prefer Client FQDN option and
  1148. // ignore the Hostname option.
  1149. try {
  1150. Pkt4Ptr resp = ex.getResponse();
  1151. Option4ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<Option4ClientFqdn>
  1152. (ex.getQuery()->getOption(DHO_FQDN));
  1153. if (fqdn) {
  1154. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL, DHCP4_CLIENT_FQDN_PROCESS)
  1155. .arg(ex.getQuery()->getLabel());
  1156. processClientFqdnOption(ex);
  1157. } else {
  1158. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL,
  1159. DHCP4_CLIENT_HOSTNAME_PROCESS)
  1160. .arg(ex.getQuery()->getLabel());
  1161. processHostnameOption(ex);
  1162. }
  1163. } catch (const Exception& e) {
  1164. // In some rare cases it is possible that the client's name processing
  1165. // fails. For example, the Hostname option may be malformed, or there
  1166. // may be an error in the server's logic which would cause multiple
  1167. // attempts to add the same option to the response message. This
  1168. // error message aggregates all these errors so they can be diagnosed
  1169. // from the log. We don't want to throw an exception here because,
  1170. // it will impact the processing of the whole packet. We rather want
  1171. // the processing to continue, even if the client's name is wrong.
  1172. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_CLIENT_NAME_PROC_FAIL)
  1173. .arg(ex.getQuery()->getLabel())
  1174. .arg(e.what());
  1175. }
  1176. }
  1177. void
  1178. Dhcpv4Srv::processClientFqdnOption(Dhcpv4Exchange& ex) {
  1179. // Obtain the FQDN option from the client's message.
  1180. Option4ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<
  1181. Option4ClientFqdn>(ex.getQuery()->getOption(DHO_FQDN));
  1182. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_CLIENT_FQDN_DATA)
  1183. .arg(ex.getQuery()->getLabel())
  1184. .arg(fqdn->toText());
  1185. // Create the DHCPv4 Client FQDN Option to be included in the server's
  1186. // response to a client.
  1187. Option4ClientFqdnPtr fqdn_resp(new Option4ClientFqdn(*fqdn));
  1188. // Set the server S, N, and O flags based on client's flags and
  1189. // current configuration.
  1190. D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
  1191. d2_mgr.adjustFqdnFlags<Option4ClientFqdn>(*fqdn, *fqdn_resp);
  1192. // Carry over the client's E flag.
  1193. fqdn_resp->setFlag(Option4ClientFqdn::FLAG_E,
  1194. fqdn->getFlag(Option4ClientFqdn::FLAG_E));
  1195. if (ex.getContext()->host_ && !ex.getContext()->host_->getHostname().empty()) {
  1196. D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
  1197. fqdn_resp->setDomainName(d2_mgr.qualifyName(ex.getContext()->host_->getHostname(),
  1198. true), Option4ClientFqdn::FULL);
  1199. } else {
  1200. // Adjust the domain name based on domain name value and type sent by the
  1201. // client and current configuration.
  1202. d2_mgr.adjustDomainName<Option4ClientFqdn>(*fqdn, *fqdn_resp);
  1203. }
  1204. // Add FQDN option to the response message. Note that, there may be some
  1205. // cases when server may choose not to include the FQDN option in a
  1206. // response to a client. In such cases, the FQDN should be removed from the
  1207. // outgoing message. In theory we could cease to include the FQDN option
  1208. // in this function until it is confirmed that it should be included.
  1209. // However, we include it here for simplicity. Functions used to acquire
  1210. // lease for a client will scan the response message for FQDN and if it
  1211. // is found they will take necessary actions to store the FQDN information
  1212. // in the lease database as well as to generate NameChangeRequests to DNS.
  1213. // If we don't store the option in the response message, we will have to
  1214. // propagate it in the different way to the functions which acquire the
  1215. // lease. This would require modifications to the API of this class.
  1216. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_RESPONSE_FQDN_DATA)
  1217. .arg(ex.getQuery()->getLabel())
  1218. .arg(fqdn_resp->toText());
  1219. ex.getResponse()->addOption(fqdn_resp);
  1220. }
  1221. void
  1222. Dhcpv4Srv::processHostnameOption(Dhcpv4Exchange& ex) {
  1223. // Fetch D2 configuration.
  1224. D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
  1225. // Obtain the Hostname option from the client's message.
  1226. OptionStringPtr opt_hostname = boost::dynamic_pointer_cast<OptionString>
  1227. (ex.getQuery()->getOption(DHO_HOST_NAME));
  1228. if (opt_hostname) {
  1229. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_CLIENT_HOSTNAME_DATA)
  1230. .arg(ex.getQuery()->getLabel())
  1231. .arg(opt_hostname->getValue());
  1232. }
  1233. AllocEngine::ClientContext4Ptr ctx = ex.getContext();
  1234. // Hostname reservations take precedence over any other configuration,
  1235. // i.e. DDNS configuration.
  1236. if (ctx->host_ && !ctx->host_->getHostname().empty()) {
  1237. // In order to send a reserved hostname value we expect that at least
  1238. // one of the following is the case: the client has sent us a hostname
  1239. // option, or the client has sent Parameter Request List option with
  1240. // the hostname option code included.
  1241. // It is going to be less expensive to first check the presence of the
  1242. // hostname option.
  1243. bool should_send_hostname = static_cast<bool>(opt_hostname);
  1244. // Hostname option is not present, so we have to check PRL option.
  1245. if (!should_send_hostname) {
  1246. OptionUint8ArrayPtr
  1247. option_prl = boost::dynamic_pointer_cast<OptionUint8Array>
  1248. (ex.getQuery()->getOption(DHO_DHCP_PARAMETER_REQUEST_LIST));
  1249. if (option_prl) {
  1250. // PRL option exists, so check if the hostname option code is
  1251. // included in it.
  1252. const std::vector<uint8_t>&
  1253. requested_opts = option_prl->getValues();
  1254. if (std::find(requested_opts.begin(), requested_opts.end(),
  1255. DHO_HOST_NAME) != requested_opts.end()) {
  1256. // Client has requested hostname via Parameter Request
  1257. // List option.
  1258. should_send_hostname = true;
  1259. }
  1260. }
  1261. }
  1262. // If the hostname or PRL option indicates that the server should
  1263. // send back a hostname option, send this option with a reserved
  1264. // name for this client.
  1265. if (should_send_hostname) {
  1266. const std::string& hostname = d2_mgr.qualifyName(ctx->host_->getHostname(),
  1267. false);
  1268. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL_DATA,
  1269. DHCP4_RESERVED_HOSTNAME_ASSIGNED)
  1270. .arg(ex.getQuery()->getLabel())
  1271. .arg(hostname);
  1272. OptionStringPtr opt_hostname_resp(new OptionString(Option::V4,
  1273. DHO_HOST_NAME,
  1274. hostname));
  1275. ex.getResponse()->addOption(opt_hostname_resp);
  1276. // We're done here.
  1277. return;
  1278. }
  1279. }
  1280. // There is no reservation for this client or the client hasn't requested
  1281. // hostname option. There is still a possibility that we'll have to send
  1282. // hostname option to this client if the client has included hostname option
  1283. // but there is no reservation, or the configuration of the server requires
  1284. // that we send the option regardless.
  1285. D2ClientConfig::ReplaceClientNameMode replace_name_mode =
  1286. d2_mgr.getD2ClientConfig()->getReplaceClientNameMode();
  1287. // If we don't have a hostname then either we'll supply it or do nothing.
  1288. if (!opt_hostname) {
  1289. // If we're configured to supply it then add it to the response.
  1290. // Use the root domain to signal later on that we should replace it.
  1291. if (replace_name_mode == D2ClientConfig::RCM_ALWAYS ||
  1292. replace_name_mode == D2ClientConfig::RCM_WHEN_NOT_PRESENT) {
  1293. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL_DATA,
  1294. DHCP4_GENERATE_FQDN)
  1295. .arg(ex.getQuery()->getLabel());
  1296. OptionStringPtr opt_hostname_resp(new OptionString(Option::V4,
  1297. DHO_HOST_NAME,
  1298. "."));
  1299. ex.getResponse()->addOption(opt_hostname_resp);
  1300. }
  1301. return;
  1302. }
  1303. // Client sent us a hostname option so figure out what to do with it.
  1304. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_CLIENT_HOSTNAME_DATA)
  1305. .arg(ex.getQuery()->getLabel())
  1306. .arg(opt_hostname->getValue());
  1307. std::string hostname = isc::util::str::trim(opt_hostname->getValue());
  1308. unsigned int label_count = OptionDataTypeUtil::getLabelCount(hostname);
  1309. // The hostname option sent by the client should be at least 1 octet long.
  1310. // If it isn't we ignore this option. (Per RFC 2131, section 3.14)
  1311. /// @todo It would be more liberal to accept this and let it fall into
  1312. /// the case of replace or less than two below.
  1313. if (label_count == 0) {
  1314. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_EMPTY_HOSTNAME)
  1315. .arg(ex.getQuery()->getLabel());
  1316. return;
  1317. }
  1318. // Copy construct the hostname provided by the client. It is entirely
  1319. // possible that we will use the hostname option provided by the client
  1320. // to perform the DNS update and we will send the same option to him to
  1321. // indicate that we accepted this hostname.
  1322. OptionStringPtr opt_hostname_resp(new OptionString(*opt_hostname));
  1323. // The hostname option may be unqualified or fully qualified. The lab_count
  1324. // holds the number of labels for the name. The number of 1 means that
  1325. // there is only root label "." (even for unqualified names, as the
  1326. // getLabelCount function treats each name as a fully qualified one).
  1327. // By checking the number of labels present in the hostname we may infer
  1328. // whether client has sent the fully qualified or unqualified hostname.
  1329. if ((replace_name_mode == D2ClientConfig::RCM_ALWAYS ||
  1330. replace_name_mode == D2ClientConfig::RCM_WHEN_PRESENT)
  1331. || label_count < 2) {
  1332. // Set to root domain to signal later on that we should replace it.
  1333. // DHO_HOST_NAME is a string option which cannot be empty.
  1334. /// @todo We may want to reconsider whether it is appropriate for the
  1335. /// client to send a root domain name as a Hostname. There are
  1336. /// also extensions to the auto generation of the client's name,
  1337. /// e.g. conversion to the puny code which may be considered at some
  1338. /// point.
  1339. /// For now, we just remain liberal and expect that the DNS will handle
  1340. /// conversion if needed and possible.
  1341. opt_hostname_resp->setValue(".");
  1342. } else if (label_count == 2) {
  1343. // If there are two labels, it means that the client has specified
  1344. // the unqualified name. We have to concatenate the unqualified name
  1345. // with the domain name. The false value passed as a second argument
  1346. // indicates that the trailing dot should not be appended to the
  1347. // hostname. We don't want to append the trailing dot because
  1348. // we don't know whether the hostname is partial or not and some
  1349. // clients do not handle the hostnames with the trailing dot.
  1350. opt_hostname_resp->setValue(d2_mgr.qualifyName(hostname, false));
  1351. }
  1352. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_RESPONSE_HOSTNAME_DATA)
  1353. .arg(ex.getQuery()->getLabel())
  1354. .arg(opt_hostname_resp->getValue());
  1355. ex.getResponse()->addOption(opt_hostname_resp);
  1356. }
  1357. void
  1358. Dhcpv4Srv::createNameChangeRequests(const Lease4Ptr& lease,
  1359. const Lease4Ptr& old_lease) {
  1360. if (!lease) {
  1361. isc_throw(isc::Unexpected,
  1362. "NULL lease specified when creating NameChangeRequest");
  1363. } else if (!old_lease || !lease->hasIdenticalFqdn(*old_lease)) {
  1364. // We may need to generate the NameChangeRequest for the new lease. It
  1365. // will be generated only if hostname is set and if forward or reverse
  1366. // update has been requested.
  1367. queueNCR(CHG_ADD, lease);
  1368. }
  1369. }
  1370. void
  1371. Dhcpv4Srv::assignLease(Dhcpv4Exchange& ex) {
  1372. // Get the pointers to the query and the response messages.
  1373. Pkt4Ptr query = ex.getQuery();
  1374. Pkt4Ptr resp = ex.getResponse();
  1375. // Get the context.
  1376. AllocEngine::ClientContext4Ptr ctx = ex.getContext();
  1377. // Subnet should have been already selected when the context was created.
  1378. Subnet4Ptr subnet = ctx->subnet_;
  1379. if (!subnet) {
  1380. // This particular client is out of luck today. We do not have
  1381. // information about the subnet he is connected to. This likely means
  1382. // misconfiguration of the server (or some relays).
  1383. // Perhaps this should be logged on some higher level?
  1384. LOG_ERROR(bad_packet4_logger, DHCP4_PACKET_NAK_0001)
  1385. .arg(query->getLabel())
  1386. .arg(query->getRemoteAddr().toText())
  1387. .arg(query->getName());
  1388. resp->setType(DHCPNAK);
  1389. resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  1390. return;
  1391. }
  1392. // Get the server identifier. It will be used to determine the state
  1393. // of the client.
  1394. OptionCustomPtr opt_serverid = boost::dynamic_pointer_cast<
  1395. OptionCustom>(query->getOption(DHO_DHCP_SERVER_IDENTIFIER));
  1396. // Check if the client has sent a requested IP address option or
  1397. // ciaddr.
  1398. OptionCustomPtr opt_requested_address = boost::dynamic_pointer_cast<
  1399. OptionCustom>(query->getOption(DHO_DHCP_REQUESTED_ADDRESS));
  1400. IOAddress hint(IOAddress::IPV4_ZERO_ADDRESS());
  1401. if (opt_requested_address) {
  1402. hint = opt_requested_address->readAddress();
  1403. } else if (!query->getCiaddr().isV4Zero()) {
  1404. hint = query->getCiaddr();
  1405. }
  1406. HWAddrPtr hwaddr = query->getHWAddr();
  1407. // "Fake" allocation is processing of DISCOVER message. We pretend to do an
  1408. // allocation, but we do not put the lease in the database. That is ok,
  1409. // because we do not guarantee that the user will get that exact lease. If
  1410. // the user selects this server to do actual allocation (i.e. sends REQUEST)
  1411. // it should include this hint. That will help us during the actual lease
  1412. // allocation.
  1413. bool fake_allocation = (query->getType() == DHCPDISCOVER);
  1414. // Get client-id. It is not mandatory in DHCPv4.
  1415. ClientIdPtr client_id = ex.getContext()->clientid_;
  1416. // If there is no server id and there is a Requested IP Address option
  1417. // the client is in the INIT-REBOOT state in which the server has to
  1418. // determine whether the client's notion of the address is correct
  1419. // and whether the client is known, i.e., has a lease.
  1420. if (!fake_allocation && !opt_serverid && opt_requested_address) {
  1421. LOG_INFO(lease4_logger, DHCP4_INIT_REBOOT)
  1422. .arg(query->getLabel())
  1423. .arg(hint.toText());
  1424. Lease4Ptr lease;
  1425. if (client_id) {
  1426. lease = LeaseMgrFactory::instance().getLease4(*client_id, subnet->getID());
  1427. }
  1428. if (!lease && hwaddr) {
  1429. lease = LeaseMgrFactory::instance().getLease4(*hwaddr, subnet->getID());
  1430. }
  1431. // Check the first error case: unknown client. We check this before
  1432. // validating the address sent because we don't want to respond if
  1433. // we don't know this client.
  1434. if (!lease || !lease->belongsToClient(hwaddr, client_id)) {
  1435. LOG_DEBUG(bad_packet4_logger, DBG_DHCP4_DETAIL,
  1436. DHCP4_NO_LEASE_INIT_REBOOT)
  1437. .arg(query->getLabel())
  1438. .arg(hint.toText());
  1439. ex.deleteResponse();
  1440. return;
  1441. }
  1442. // We know this client so we can now check if his notion of the
  1443. // IP address is correct.
  1444. if (lease && (lease->addr_ != hint)) {
  1445. LOG_DEBUG(bad_packet4_logger, DBG_DHCP4_DETAIL,
  1446. DHCP4_PACKET_NAK_0002)
  1447. .arg(query->getLabel())
  1448. .arg(hint.toText());
  1449. resp->setType(DHCPNAK);
  1450. resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  1451. return;
  1452. }
  1453. }
  1454. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  1455. std::string hostname;
  1456. bool fqdn_fwd = false;
  1457. bool fqdn_rev = false;
  1458. OptionStringPtr opt_hostname;
  1459. Option4ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<
  1460. Option4ClientFqdn>(resp->getOption(DHO_FQDN));
  1461. if (fqdn) {
  1462. hostname = fqdn->getDomainName();
  1463. CfgMgr::instance().getD2ClientMgr().getUpdateDirections(*fqdn,
  1464. fqdn_fwd,
  1465. fqdn_rev);
  1466. } else {
  1467. opt_hostname = boost::dynamic_pointer_cast<OptionString>
  1468. (resp->getOption(DHO_HOST_NAME));
  1469. if (opt_hostname) {
  1470. hostname = opt_hostname->getValue();
  1471. // DHO_HOST_NAME is string option which cannot be blank,
  1472. // we use "." to know we should replace it with a fully
  1473. // generated name. The local string variable needs to be
  1474. // blank in logic below.
  1475. if (hostname == ".") {
  1476. hostname = "";
  1477. }
  1478. /// @todo It could be configurable what sort of updates the
  1479. /// server is doing when Hostname option was sent.
  1480. fqdn_fwd = true;
  1481. fqdn_rev = true;
  1482. }
  1483. }
  1484. // We need to set these values in the context as they haven't been set yet.
  1485. ctx->requested_address_ = hint;
  1486. ctx->fwd_dns_update_ = fqdn_fwd;
  1487. ctx->rev_dns_update_ = fqdn_rev;
  1488. ctx->hostname_ = hostname;
  1489. ctx->fake_allocation_ = fake_allocation;
  1490. ctx->callout_handle_ = callout_handle;
  1491. Lease4Ptr lease = alloc_engine_->allocateLease4(*ctx);
  1492. if (lease) {
  1493. // We have a lease! Let's set it in the packet and send it back to
  1494. // the client.
  1495. LOG_INFO(lease4_logger, fake_allocation ? DHCP4_LEASE_ADVERT : DHCP4_LEASE_ALLOC)
  1496. .arg(query->getLabel())
  1497. .arg(lease->addr_.toText());
  1498. resp->setYiaddr(lease->addr_);
  1499. /// @todo The server should check what ciaddr the client has supplied
  1500. /// in ciaddr. Currently the ciaddr is ignored except for the subnet
  1501. /// selection. If the client supplied an invalid address, the server
  1502. /// will also return an invalid address here.
  1503. if (!fake_allocation) {
  1504. // If this is a renewing client it will set a ciaddr which the
  1505. // server may include in the response. If this is a new allocation
  1506. // the client will set ciaddr to 0 and this will also be propagated
  1507. // to the server's resp.
  1508. resp->setCiaddr(query->getCiaddr());
  1509. }
  1510. // If there has been Client FQDN or Hostname option sent, but the
  1511. // hostname is empty, it means that server is responsible for
  1512. // generating the entire hostname for the client. The example of the
  1513. // client's name, generated from the IP address is: host-192-0-2-3.
  1514. if ((fqdn || opt_hostname) && lease->hostname_.empty()) {
  1515. // Note that if we have received the hostname option, rather than
  1516. // Client FQDN the trailing dot is not appended to the generated
  1517. // hostname because some clients don't handle the trailing dot in
  1518. // the hostname. Whether the trailing dot is appended or not is
  1519. // controlled by the second argument to the generateFqdn().
  1520. lease->hostname_ = CfgMgr::instance().getD2ClientMgr()
  1521. .generateFqdn(lease->addr_, static_cast<bool>(fqdn));
  1522. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL, DHCP4_RESPONSE_HOSTNAME_GENERATE)
  1523. .arg(query->getLabel())
  1524. .arg(lease->hostname_);
  1525. // The operations below are rather safe, but we want to catch
  1526. // any potential exceptions (e.g. invalid lease database backend
  1527. // implementation) and log an error.
  1528. try {
  1529. if (!fake_allocation) {
  1530. // The lease update should be safe, because the lease should
  1531. // be already in the database. In most cases the exception
  1532. // would be thrown if the lease was missing.
  1533. LeaseMgrFactory::instance().updateLease4(lease);
  1534. }
  1535. // The name update in the option should be also safe,
  1536. // because the generated name is well formed.
  1537. if (fqdn) {
  1538. fqdn->setDomainName(lease->hostname_,
  1539. Option4ClientFqdn::FULL);
  1540. } else if (opt_hostname) {
  1541. opt_hostname->setValue(lease->hostname_);
  1542. }
  1543. } catch (const Exception& ex) {
  1544. LOG_ERROR(ddns4_logger, DHCP4_NAME_GEN_UPDATE_FAIL)
  1545. .arg(query->getLabel())
  1546. .arg(lease->hostname_)
  1547. .arg(ex.what());
  1548. }
  1549. }
  1550. // IP Address Lease time (type 51)
  1551. OptionPtr opt(new OptionUint32(Option::V4, DHO_DHCP_LEASE_TIME,
  1552. lease->valid_lft_));
  1553. resp->addOption(opt);
  1554. // Subnet mask (type 1)
  1555. resp->addOption(getNetmaskOption(subnet));
  1556. // renewal-timer (type 58)
  1557. if (!subnet->getT1().unspecified()) {
  1558. OptionUint32Ptr t1(new OptionUint32(Option::V4,
  1559. DHO_DHCP_RENEWAL_TIME,
  1560. subnet->getT1()));
  1561. resp->addOption(t1);
  1562. }
  1563. // rebind timer (type 59)
  1564. if (!subnet->getT2().unspecified()) {
  1565. OptionUint32Ptr t2(new OptionUint32(Option::V4,
  1566. DHO_DHCP_REBINDING_TIME,
  1567. subnet->getT2()));
  1568. resp->addOption(t2);
  1569. }
  1570. // Create NameChangeRequests if DDNS is enabled and this is a
  1571. // real allocation.
  1572. if (!fake_allocation && CfgMgr::instance().ddnsEnabled()) {
  1573. try {
  1574. LOG_DEBUG(ddns4_logger, DBG_DHCP4_DETAIL, DHCP4_NCR_CREATE)
  1575. .arg(query->getLabel());
  1576. createNameChangeRequests(lease, ctx->old_lease_);
  1577. } catch (const Exception& ex) {
  1578. LOG_ERROR(ddns4_logger, DHCP4_NCR_CREATION_FAILED)
  1579. .arg(query->getLabel())
  1580. .arg(ex.what());
  1581. }
  1582. }
  1583. } else {
  1584. // Allocation engine did not allocate a lease. The engine logged
  1585. // cause of that failure.
  1586. LOG_DEBUG(bad_packet4_logger, DBG_DHCP4_DETAIL, fake_allocation ?
  1587. DHCP4_PACKET_NAK_0003 : DHCP4_PACKET_NAK_0004)
  1588. .arg(query->getLabel())
  1589. .arg(query->getCiaddr().toText())
  1590. .arg(opt_requested_address ?
  1591. opt_requested_address->readAddress().toText() : "(no address)");
  1592. resp->setType(DHCPNAK);
  1593. resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  1594. resp->delOption(DHO_FQDN);
  1595. resp->delOption(DHO_HOST_NAME);
  1596. }
  1597. }
  1598. void
  1599. Dhcpv4Srv::adjustIfaceData(Dhcpv4Exchange& ex) {
  1600. adjustRemoteAddr(ex);
  1601. // Initialize the pointers to the client's message and the server's
  1602. // response.
  1603. Pkt4Ptr query = ex.getQuery();
  1604. Pkt4Ptr response = ex.getResponse();
  1605. // The DHCPINFORM is generally unicast to the client. The only situation
  1606. // when the server is unable to unicast to the client is when the client
  1607. // doesn't include ciaddr and the message is relayed. In this case the
  1608. // server has to reply via relay agent. For other messages we send back
  1609. // through relay if message is relayed, and unicast to the client if the
  1610. // message is not relayed.
  1611. // Note that the call to this function may throw if invalid combination
  1612. // of hops and giaddr is found (hops = 0 if giaddr = 0 and hops != 0 if
  1613. // giaddr != 0). The exception will propagate down and eventually cause the
  1614. // packet to be discarded.
  1615. if (((query->getType() == DHCPINFORM) &&
  1616. ((!query->getCiaddr().isV4Zero()) ||
  1617. (!query->isRelayed() && !query->getRemoteAddr().isV4Zero()))) ||
  1618. ((query->getType() != DHCPINFORM) && !query->isRelayed())) {
  1619. response->setRemotePort(DHCP4_CLIENT_PORT);
  1620. } else {
  1621. response->setRemotePort(DHCP4_SERVER_PORT);
  1622. }
  1623. IOAddress local_addr = query->getLocalAddr();
  1624. // In many cases the query is sent to a broadcast address. This address
  1625. // apears as a local address in the query message. We can't simply copy
  1626. // this address to a response message and use it as a source address.
  1627. // Instead we will need to use the address assigned to the interface
  1628. // on which the query has been received. In other cases, we will just
  1629. // use this address as a source address for the response.
  1630. // Do the same for DHCPv4-over-DHCPv6 exchanges.
  1631. if (local_addr.isV4Bcast() || query->isDhcp4o6()) {
  1632. SocketInfo sock_info = IfaceMgr::instance().getSocket(*query);
  1633. local_addr = sock_info.addr_;
  1634. }
  1635. // We assume that there is an appropriate socket bound to this address
  1636. // and that the address is correct. This is safe assumption because
  1637. // the local address of the query is set when the query is received.
  1638. // The query sent to an incorrect address wouldn't have been received.
  1639. // However, if socket is closed for this address between the reception
  1640. // of the query and sending a response, the IfaceMgr should detect it
  1641. // and return an error.
  1642. response->setLocalAddr(local_addr);
  1643. // In many cases the query is sent to a broadcast address. This address
  1644. // appears as a local address in the query message. Therefore we can't
  1645. // simply copy local address from the query and use it as a source
  1646. // address for the response. Instead, we have to check what address our
  1647. // socket is bound to and use it as a source address. This operation
  1648. // may throw if for some reason the socket is closed.
  1649. /// @todo Consider an optimization that we use local address from
  1650. /// the query if this address is not broadcast.
  1651. response->setLocalPort(DHCP4_SERVER_PORT);
  1652. response->setIface(query->getIface());
  1653. response->setIndex(query->getIndex());
  1654. }
  1655. void
  1656. Dhcpv4Srv::adjustRemoteAddr(Dhcpv4Exchange& ex) {
  1657. // Initialize the pointers to the client's message and the server's
  1658. // response.
  1659. Pkt4Ptr query = ex.getQuery();
  1660. Pkt4Ptr response = ex.getResponse();
  1661. // DHCPv4-over-DHCPv6 is simple
  1662. if (query->isDhcp4o6()) {
  1663. response->setRemoteAddr(query->getRemoteAddr());
  1664. return;
  1665. }
  1666. // The DHCPINFORM is slightly different than other messages in a sense
  1667. // that the server should always unicast the response to the ciaddr.
  1668. // It appears however that some clients don't set the ciaddr. We still
  1669. // want to provision these clients and we do what we can't to send the
  1670. // packet to the address where client can receive it.
  1671. if (query->getType() == DHCPINFORM) {
  1672. // If client adheres to RFC2131 it will set the ciaddr and in this
  1673. // case we always unicast our response to this address.
  1674. if (!query->getCiaddr().isV4Zero()) {
  1675. response->setRemoteAddr(query->getCiaddr());
  1676. // If we received DHCPINFORM via relay and the ciaddr is not set we
  1677. // will try to send the response via relay. The caveat is that the
  1678. // relay will not have any idea where to forward the packet because
  1679. // the yiaddr is likely not set. So, the broadcast flag is set so
  1680. // as the response may be broadcast.
  1681. } else if (query->isRelayed()) {
  1682. response->setRemoteAddr(query->getGiaddr());
  1683. response->setFlags(response->getFlags() | BOOTP_BROADCAST);
  1684. // If there is no ciaddr and no giaddr the only thing we can do is
  1685. // to use the source address of the packet.
  1686. } else {
  1687. response->setRemoteAddr(query->getRemoteAddr());
  1688. }
  1689. // Remote address is now set so return.
  1690. return;
  1691. }
  1692. // If received relayed message, server responds to the relay address.
  1693. if (query->isRelayed()) {
  1694. // The client should set the ciaddr when sending the DHCPINFORM
  1695. // but in case he didn't, the relay may not be able to determine the
  1696. // address of the client, because yiaddr is not set when responding
  1697. // to Confirm and the only address available was the source address
  1698. // of the client. The source address is however not used here because
  1699. // the message is relayed. Therefore, we set the BROADCAST flag so
  1700. // as the relay can broadcast the packet.
  1701. if ((query->getType() == DHCPINFORM) &&
  1702. query->getCiaddr().isV4Zero()) {
  1703. response->setFlags(BOOTP_BROADCAST);
  1704. }
  1705. response->setRemoteAddr(query->getGiaddr());
  1706. // If giaddr is 0 but client set ciaddr, server should unicast the
  1707. // response to ciaddr.
  1708. } else if (!query->getCiaddr().isV4Zero()) {
  1709. response->setRemoteAddr(query->getCiaddr());
  1710. // We can't unicast the response to the client when sending NAK,
  1711. // because we haven't allocated address for him. Therefore,
  1712. // NAK is broadcast.
  1713. } else if (response->getType() == DHCPNAK) {
  1714. response->setRemoteAddr(IOAddress::IPV4_BCAST_ADDRESS());
  1715. // If yiaddr is set it means that we have created a lease for a client.
  1716. } else if (!response->getYiaddr().isV4Zero()) {
  1717. // If the broadcast bit is set in the flags field, we have to
  1718. // send the response to broadcast address. Client may have requested it
  1719. // because it doesn't support reception of messages on the interface
  1720. // which doesn't have an address assigned. The other case when response
  1721. // must be broadcasted is when our server does not support responding
  1722. // directly to a client without address assigned.
  1723. const bool bcast_flag = ((query->getFlags() & Pkt4::FLAG_BROADCAST_MASK) != 0);
  1724. if (!IfaceMgr::instance().isDirectResponseSupported() || bcast_flag) {
  1725. response->setRemoteAddr(IOAddress::IPV4_BCAST_ADDRESS());
  1726. // Client cleared the broadcast bit and we support direct responses
  1727. // so we should unicast the response to a newly allocated address -
  1728. // yiaddr.
  1729. } else {
  1730. response->setRemoteAddr(response ->getYiaddr());
  1731. }
  1732. // In most cases, we should have the remote address found already. If we
  1733. // found ourselves at this point, the rational thing to do is to respond
  1734. // to the address we got the query from.
  1735. } else {
  1736. response->setRemoteAddr(query->getRemoteAddr());
  1737. }
  1738. }
  1739. void
  1740. Dhcpv4Srv::setFixedFields(Dhcpv4Exchange& ex) {
  1741. Pkt4Ptr query = ex.getQuery();
  1742. Pkt4Ptr response = ex.getResponse();
  1743. // Step 1: Start with fixed fields defined on subnet level.
  1744. Subnet4Ptr subnet = ex.getContext()->subnet_;
  1745. if (subnet) {
  1746. IOAddress subnet_next_server = subnet->getSiaddr();
  1747. if (!subnet_next_server.isV4Zero()) {
  1748. response->setSiaddr(subnet_next_server);
  1749. }
  1750. }
  1751. // Step 2: Try to set the values based on classes.
  1752. // Any values defined in classes will override those from subnet level.
  1753. const ClientClasses classes = query->getClasses();
  1754. if (!classes.empty()) {
  1755. // Let's get class definitions
  1756. const ClientClassDefMapPtr& defs = CfgMgr::instance().getCurrentCfg()->
  1757. getClientClassDictionary()->getClasses();
  1758. // Now we need to iterate over the classes assigned to the
  1759. // query packet and find corresponding class definitions for it.
  1760. for (ClientClasses::const_iterator name = classes.begin();
  1761. name != classes.end(); ++name) {
  1762. ClientClassDefMap::const_iterator cl = defs->find(*name);
  1763. if (cl == defs->end()) {
  1764. // Let's skip classes that don't have definitions. Currently
  1765. // these are automatic classes VENDOR_CLASS_something, but there
  1766. // may be other classes assigned under other circumstances, e.g.
  1767. // by hooks.
  1768. continue;
  1769. }
  1770. IOAddress next_server = cl->second->getNextServer();
  1771. if (!next_server.isV4Zero()) {
  1772. response->setSiaddr(next_server);
  1773. }
  1774. const string& sname = cl->second->getSname();
  1775. if (!sname.empty()) {
  1776. // Converting string to (const uint8_t*, size_t len) format is
  1777. // tricky. reinterpret_cast is not the most elegant solution,
  1778. // but it does avoid us making unnecessary copy. We will convert
  1779. // sname and file fields in Pkt4 to string one day and life
  1780. // will be easier.
  1781. response->setSname(reinterpret_cast<const uint8_t*>(sname.c_str()),
  1782. sname.size());
  1783. }
  1784. const string& filename = cl->second->getFilename();
  1785. if (!filename.empty()) {
  1786. // Converting string to (const uint8_t*, size_t len) format is
  1787. // tricky. reinterpret_cast is not the most elegant solution,
  1788. // but it does avoid us making unnecessary copy. We will convert
  1789. // sname and file fields in Pkt4 to string one day and life
  1790. // will be easier.
  1791. response->setFile(reinterpret_cast<const uint8_t*>(filename.c_str()),
  1792. filename.size());
  1793. }
  1794. }
  1795. }
  1796. // Step 3: try to set values using HR. Any values coming from there will override
  1797. // the subnet or class values.
  1798. ex.setReservedMessageFields();
  1799. }
  1800. OptionPtr
  1801. Dhcpv4Srv::getNetmaskOption(const Subnet4Ptr& subnet) {
  1802. uint32_t netmask = getNetmask4(subnet->get().second).toUint32();
  1803. OptionPtr opt(new OptionInt<uint32_t>(Option::V4,
  1804. DHO_SUBNET_MASK, netmask));
  1805. return (opt);
  1806. }
  1807. Pkt4Ptr
  1808. Dhcpv4Srv::processDiscover(Pkt4Ptr& discover) {
  1809. sanityCheck(discover, FORBIDDEN);
  1810. Dhcpv4Exchange ex(alloc_engine_, discover, selectSubnet(discover));
  1811. // If DHCPDISCOVER message contains the FQDN or Hostname option, server
  1812. // may respond to the client with the appropriate FQDN or Hostname
  1813. // option to indicate that whether it will take responsibility for
  1814. // updating DNS when the client sends DHCPREQUEST message.
  1815. processClientName(ex);
  1816. assignLease(ex);
  1817. if (!ex.getResponse()) {
  1818. // The offer is empty so return it *now*!
  1819. return (Pkt4Ptr());
  1820. }
  1821. // Adding any other options makes sense only when we got the lease.
  1822. if (!ex.getResponse()->getYiaddr().isV4Zero()) {
  1823. buildCfgOptionList(ex);
  1824. appendRequestedOptions(ex);
  1825. appendRequestedVendorOptions(ex);
  1826. // There are a few basic options that we always want to
  1827. // include in the response. If client did not request
  1828. // them we append them for him.
  1829. appendBasicOptions(ex);
  1830. // Set fixed fields (siaddr, sname, filename) if defined in
  1831. // the reservation, class or subnet specific configuration.
  1832. setFixedFields(ex);
  1833. } else {
  1834. // If the server can't offer an address, it drops the packet.
  1835. return (Pkt4Ptr());
  1836. }
  1837. // Set the src/dest IP address, port and interface for the outgoing
  1838. // packet.
  1839. adjustIfaceData(ex);
  1840. appendServerID(ex);
  1841. return (ex.getResponse());
  1842. }
  1843. Pkt4Ptr
  1844. Dhcpv4Srv::processRequest(Pkt4Ptr& request) {
  1845. /// @todo Uncomment this (see ticket #3116)
  1846. /// sanityCheck(request, MANDATORY);
  1847. Dhcpv4Exchange ex(alloc_engine_, request, selectSubnet(request));
  1848. // If DHCPREQUEST message contains the FQDN or Hostname option, server
  1849. // should respond to the client with the appropriate FQDN or Hostname
  1850. // option to indicate if it takes responsibility for the DNS updates.
  1851. // This is performed by the function below.
  1852. processClientName(ex);
  1853. // Note that we treat REQUEST message uniformly, regardless if this is a
  1854. // first request (requesting for new address), renewing existing address
  1855. // or even rebinding.
  1856. assignLease(ex);
  1857. if (!ex.getResponse()) {
  1858. // The ack is empty so return it *now*!
  1859. return (Pkt4Ptr());
  1860. }
  1861. // Adding any other options makes sense only when we got the lease.
  1862. if (!ex.getResponse()->getYiaddr().isV4Zero()) {
  1863. buildCfgOptionList(ex);
  1864. appendRequestedOptions(ex);
  1865. appendRequestedVendorOptions(ex);
  1866. // There are a few basic options that we always want to
  1867. // include in the response. If client did not request
  1868. // them we append them for him.
  1869. appendBasicOptions(ex);
  1870. // Set fixed fields (siaddr, sname, filename) if defined in
  1871. // the reservation, class or subnet specific configuration.
  1872. setFixedFields(ex);
  1873. }
  1874. // Set the src/dest IP address, port and interface for the outgoing
  1875. // packet.
  1876. adjustIfaceData(ex);
  1877. appendServerID(ex);
  1878. return (ex.getResponse());
  1879. }
  1880. void
  1881. Dhcpv4Srv::processRelease(Pkt4Ptr& release) {
  1882. /// @todo Uncomment this (see ticket #3116)
  1883. /// sanityCheck(release, MANDATORY);
  1884. // Try to find client-id. Note that for the DHCPRELEASE we don't check if the
  1885. // match-client-id configuration parameter is disabled because this parameter
  1886. // is configured for subnets and we don't select subnet for the DHCPRELEASE.
  1887. // Bogus clients usually generate new client identifiers when they first
  1888. // connect to the network, so whatever client identifier has been used to
  1889. // acquire the lease, the client identifier carried in the DHCPRELEASE is
  1890. // likely to be the same and the lease will be correctly identified in the
  1891. // lease database. If supplied client identifier differs from the one used
  1892. // to acquire the lease then the lease will remain in the database and
  1893. // simply expire.
  1894. ClientIdPtr client_id;
  1895. OptionPtr opt = release->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  1896. if (opt) {
  1897. client_id = ClientIdPtr(new ClientId(opt->getData()));
  1898. }
  1899. try {
  1900. // Do we have a lease for that particular address?
  1901. Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(release->getCiaddr());
  1902. if (!lease) {
  1903. // No such lease - bogus release
  1904. LOG_DEBUG(lease4_logger, DBG_DHCP4_DETAIL, DHCP4_RELEASE_FAIL_NO_LEASE)
  1905. .arg(release->getLabel())
  1906. .arg(release->getCiaddr().toText());
  1907. return;
  1908. }
  1909. if (!lease->belongsToClient(release->getHWAddr(), client_id)) {
  1910. LOG_DEBUG(lease4_logger, DBG_DHCP4_DETAIL, DHCP4_RELEASE_FAIL_WRONG_CLIENT)
  1911. .arg(release->getLabel())
  1912. .arg(release->getCiaddr().toText());
  1913. return;
  1914. }
  1915. bool skip = false;
  1916. // Execute all callouts registered for lease4_release
  1917. if (HooksManager::calloutsPresent(Hooks.hook_index_lease4_release_)) {
  1918. CalloutHandlePtr callout_handle = getCalloutHandle(release);
  1919. // Delete all previous arguments
  1920. callout_handle->deleteAllArguments();
  1921. // Enable copying options from the packet within hook library.
  1922. ScopedEnableOptionsCopy<Pkt4> query4_options_copy(release);
  1923. // Pass the original packet
  1924. callout_handle->setArgument("query4", release);
  1925. // Pass the lease to be updated
  1926. callout_handle->setArgument("lease4", lease);
  1927. // Call all installed callouts
  1928. HooksManager::callCallouts(Hooks.hook_index_lease4_release_,
  1929. *callout_handle);
  1930. // Callouts decided to skip the next processing step. The next
  1931. // processing step would to send the packet, so skip at this
  1932. // stage means "drop response".
  1933. if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
  1934. skip = true;
  1935. LOG_DEBUG(hooks_logger, DBG_DHCP4_HOOKS,
  1936. DHCP4_HOOK_LEASE4_RELEASE_SKIP)
  1937. .arg(release->getLabel());
  1938. }
  1939. /// @todo add support for DROP status
  1940. }
  1941. // Callout didn't indicate to skip the release process. Let's release
  1942. // the lease.
  1943. if (!skip) {
  1944. bool success = LeaseMgrFactory::instance().deleteLease(lease->addr_);
  1945. if (success) {
  1946. // Release successful
  1947. LOG_INFO(lease4_logger, DHCP4_RELEASE)
  1948. .arg(release->getLabel())
  1949. .arg(lease->addr_.toText());
  1950. // Need to decrease statistic for assigned addresses.
  1951. StatsMgr::instance().addValue(
  1952. StatsMgr::generateName("subnet", lease->subnet_id_, "assigned-addresses"),
  1953. static_cast<int64_t>(-1));
  1954. // Remove existing DNS entries for the lease, if any.
  1955. queueNCR(CHG_REMOVE, lease);
  1956. } else {
  1957. // Release failed
  1958. LOG_ERROR(lease4_logger, DHCP4_RELEASE_FAIL)
  1959. .arg(release->getLabel())
  1960. .arg(lease->addr_.toText());
  1961. }
  1962. }
  1963. } catch (const isc::Exception& ex) {
  1964. LOG_ERROR(lease4_logger, DHCP4_RELEASE_EXCEPTION)
  1965. .arg(release->getLabel())
  1966. .arg(release->getCiaddr())
  1967. .arg(ex.what());
  1968. }
  1969. }
  1970. void
  1971. Dhcpv4Srv::processDecline(Pkt4Ptr& decline) {
  1972. // Server-id is mandatory in DHCPDECLINE (see table 5, RFC2131)
  1973. /// @todo Uncomment this (see ticket #3116)
  1974. // sanityCheck(decline, MANDATORY);
  1975. // Client is supposed to specify the address being declined in
  1976. // Requested IP address option, but must not set its ciaddr.
  1977. // (again, see table 5 in RFC2131).
  1978. OptionCustomPtr opt_requested_address = boost::dynamic_pointer_cast<
  1979. OptionCustom>(decline->getOption(DHO_DHCP_REQUESTED_ADDRESS));
  1980. if (!opt_requested_address) {
  1981. isc_throw(RFCViolation, "Mandatory 'Requested IP address' option missing"
  1982. "in DHCPDECLINE sent from " << decline->getLabel());
  1983. }
  1984. IOAddress addr(opt_requested_address->readAddress());
  1985. // We could also extract client's address from ciaddr, but that's clearly
  1986. // against RFC2131.
  1987. // Now we need to check whether this address really belongs to the client
  1988. // that attempts to decline it.
  1989. const Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(addr);
  1990. if (!lease) {
  1991. // Client tried to decline an address, but we don't have a lease for
  1992. // that address. Let's ignore it.
  1993. //
  1994. // We could assume that we're recovering from a mishandled migration
  1995. // to a new server and mark the address as declined, but the window of
  1996. // opportunity for that to be useful is small and the attack vector
  1997. // would be pretty severe.
  1998. LOG_WARN(dhcp4_logger, DHCP4_DECLINE_LEASE_NOT_FOUND)
  1999. .arg(addr.toText()).arg(decline->getLabel());
  2000. return;
  2001. }
  2002. // Get client-id, if available.
  2003. OptionPtr opt_clientid = decline->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  2004. ClientIdPtr client_id;
  2005. if (opt_clientid) {
  2006. client_id.reset(new ClientId(opt_clientid->getData()));
  2007. }
  2008. // Check if the client attempted to decline a lease it doesn't own.
  2009. if (!lease->belongsToClient(decline->getHWAddr(), client_id)) {
  2010. // Get printable hardware addresses
  2011. string client_hw = decline->getHWAddr() ?
  2012. decline->getHWAddr()->toText(false) : "(none)";
  2013. string lease_hw = lease->hwaddr_ ?
  2014. lease->hwaddr_->toText(false) : "(none)";
  2015. // Get printable client-ids
  2016. string client_id_txt = client_id ? client_id->toText() : "(none)";
  2017. string lease_id_txt = lease->client_id_ ?
  2018. lease->client_id_->toText() : "(none)";
  2019. // Print the warning and we're done here.
  2020. LOG_WARN(dhcp4_logger, DHCP4_DECLINE_LEASE_MISMATCH)
  2021. .arg(addr.toText()).arg(decline->getLabel())
  2022. .arg(client_hw).arg(lease_hw).arg(client_id_txt).arg(lease_id_txt);
  2023. return;
  2024. }
  2025. // Ok, all is good. The client is reporting its own address. Let's
  2026. // process it.
  2027. declineLease(lease, decline);
  2028. }
  2029. void
  2030. Dhcpv4Srv::declineLease(const Lease4Ptr& lease, const Pkt4Ptr& decline) {
  2031. // Let's check if there are hooks installed for decline4 hook point.
  2032. // If they are, let's pass the lease and client's packet. If the hook
  2033. // sets status to drop, we reject this Decline.
  2034. if (HooksManager::calloutsPresent(Hooks.hook_index_lease4_decline_)) {
  2035. CalloutHandlePtr callout_handle = getCalloutHandle(decline);
  2036. // Delete previously set arguments
  2037. callout_handle->deleteAllArguments();
  2038. // Enable copying options from the packet within hook library.
  2039. ScopedEnableOptionsCopy<Pkt4> query4_options_copy(decline);
  2040. // Pass incoming Decline and the lease to be declined.
  2041. callout_handle->setArgument("lease4", lease);
  2042. callout_handle->setArgument("query4", decline);
  2043. // Call callouts
  2044. HooksManager::callCallouts(Hooks.hook_index_lease4_decline_,
  2045. *callout_handle);
  2046. // Check if callouts decided to drop the packet. If any of them did,
  2047. // we will drop the packet.
  2048. if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP) {
  2049. LOG_DEBUG(hooks_logger, DBG_DHCP4_HOOKS, DHCP4_HOOK_DECLINE_SKIP)
  2050. .arg(decline->getLabel()).arg(lease->addr_.toText());
  2051. return;
  2052. }
  2053. }
  2054. // Remove existing DNS entries for the lease, if any.
  2055. // queueNCR will do the necessary checks and will skip the update, if not needed.
  2056. queueNCR(CHG_REMOVE, lease);
  2057. // Bump up the statistics.
  2058. // Per subnet declined addresses counter.
  2059. StatsMgr::instance().addValue(
  2060. StatsMgr::generateName("subnet", lease->subnet_id_, "declined-addresses"),
  2061. static_cast<int64_t>(1));
  2062. // Global declined addresses counter.
  2063. StatsMgr::instance().addValue("declined-addresses", static_cast<int64_t>(1));
  2064. // We do not want to decrease the assigned-addresses at this time. While
  2065. // technically a declined address is no longer allocated, the primary usage
  2066. // of the assigned-addresses statistic is to monitor pool utilization. Most
  2067. // people would forget to include declined-addresses in the calculation,
  2068. // and simply do assigned-addresses/total-addresses. This would have a bias
  2069. // towards under-representing pool utilization, if we decreased allocated
  2070. // immediately after receiving DHCPDECLINE, rather than later when we recover
  2071. // the address.
  2072. // @todo: Call hooks.
  2073. // We need to disassociate the lease from the client. Once we move a lease
  2074. // to declined state, it is no longer associated with the client in any
  2075. // way.
  2076. lease->decline(CfgMgr::instance().getCurrentCfg()->getDeclinePeriod());
  2077. LeaseMgrFactory::instance().updateLease4(lease);
  2078. LOG_INFO(lease4_logger, DHCP4_DECLINE_LEASE).arg(lease->addr_.toText())
  2079. .arg(decline->getLabel()).arg(lease->valid_lft_);
  2080. }
  2081. Pkt4Ptr
  2082. Dhcpv4Srv::processInform(Pkt4Ptr& inform) {
  2083. // DHCPINFORM MUST not include server identifier.
  2084. sanityCheck(inform, FORBIDDEN);
  2085. Dhcpv4Exchange ex(alloc_engine_, inform, selectSubnet(inform));
  2086. Pkt4Ptr ack = ex.getResponse();
  2087. buildCfgOptionList(ex);
  2088. appendRequestedOptions(ex);
  2089. appendRequestedVendorOptions(ex);
  2090. appendBasicOptions(ex);
  2091. adjustIfaceData(ex);
  2092. // Set fixed fields (siaddr, sname, filename) if defined in
  2093. // the reservation, class or subnet specific configuration.
  2094. setFixedFields(ex);
  2095. // There are cases for the DHCPINFORM that the server receives it via
  2096. // relay but will send the response to the client's unicast address
  2097. // carried in the ciaddr. In this case, the giaddr and hops field should
  2098. // be cleared (these fields were copied by the copyDefaultFields function).
  2099. // Also Relay Agent Options should be removed if present.
  2100. if (ack->getRemoteAddr() != inform->getGiaddr()) {
  2101. LOG_DEBUG(packet4_logger, DBG_DHCP4_DETAIL, DHCP4_INFORM_DIRECT_REPLY)
  2102. .arg(inform->getLabel())
  2103. .arg(ack->getRemoteAddr())
  2104. .arg(ack->getIface());
  2105. ack->setHops(0);
  2106. ack->setGiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  2107. ack->delOption(DHO_DHCP_AGENT_OPTIONS);
  2108. }
  2109. // The DHCPACK must contain server id.
  2110. appendServerID(ex);
  2111. return (ex.getResponse());
  2112. }
  2113. bool
  2114. Dhcpv4Srv::accept(const Pkt4Ptr& query) const {
  2115. // Check that the message type is accepted by the server. We rely on the
  2116. // function called to log a message if needed.
  2117. if (!acceptMessageType(query)) {
  2118. return (false);
  2119. }
  2120. // Check if the message from directly connected client (if directly
  2121. // connected) should be dropped or processed.
  2122. if (!acceptDirectRequest(query)) {
  2123. LOG_DEBUG(bad_packet4_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_DROP_0002)
  2124. .arg(query->getLabel())
  2125. .arg(query->getIface());
  2126. return (false);
  2127. }
  2128. // Check if the DHCPv4 packet has been sent to us or to someone else.
  2129. // If it hasn't been sent to us, drop it!
  2130. if (!acceptServerId(query)) {
  2131. LOG_DEBUG(bad_packet4_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_DROP_0003)
  2132. .arg(query->getLabel())
  2133. .arg(query->getIface());
  2134. return (false);
  2135. }
  2136. return (true);
  2137. }
  2138. bool
  2139. Dhcpv4Srv::acceptDirectRequest(const Pkt4Ptr& pkt) const {
  2140. // Accept all relayed messages.
  2141. if (pkt->isRelayed()) {
  2142. return (true);
  2143. }
  2144. // Accept all DHCPv4-over-DHCPv6 messages.
  2145. if (pkt->isDhcp4o6()) {
  2146. return (true);
  2147. }
  2148. // The source address must not be zero for the DHCPINFORM message from
  2149. // the directly connected client because the server will not know where
  2150. // to respond if the ciaddr was not present.
  2151. try {
  2152. if (pkt->getType() == DHCPINFORM) {
  2153. if (pkt->getRemoteAddr().isV4Zero() &&
  2154. pkt->getCiaddr().isV4Zero()) {
  2155. return (false);
  2156. }
  2157. }
  2158. } catch (...) {
  2159. // If we got here, it is probably because the message type hasn't
  2160. // been set. But, this should not really happen assuming that
  2161. // we validate the message type prior to calling this function.
  2162. return (false);
  2163. }
  2164. return (!pkt->getLocalAddr().isV4Bcast() || selectSubnet(pkt));
  2165. }
  2166. bool
  2167. Dhcpv4Srv::acceptMessageType(const Pkt4Ptr& query) const {
  2168. // When receiving a packet without message type option, getType() will
  2169. // throw.
  2170. int type;
  2171. try {
  2172. type = query->getType();
  2173. } catch (...) {
  2174. LOG_DEBUG(bad_packet4_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_DROP_0004)
  2175. .arg(query->getLabel())
  2176. .arg(query->getIface());
  2177. return (false);
  2178. }
  2179. // If we receive a message with a non-existing type, we are logging it.
  2180. if (type > DHCPLEASEQUERYDONE) {
  2181. LOG_DEBUG(bad_packet4_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_DROP_0005)
  2182. .arg(query->getLabel())
  2183. .arg(type);
  2184. return (false);
  2185. }
  2186. // Once we know that the message type is within a range of defined DHCPv4
  2187. // messages, we do a detailed check to make sure that the received message
  2188. // is targeted at server. Note that we could have received some Offer
  2189. // message broadcasted by the other server to a relay. Even though, the
  2190. // server would rather unicast its response to a relay, let's be on the
  2191. // safe side. Also, we want to drop other messages which we don't support.
  2192. // All these valid messages that we are not going to process are dropped
  2193. // silently.
  2194. if ((type != DHCPDISCOVER) && (type != DHCPREQUEST) &&
  2195. (type != DHCPRELEASE) && (type != DHCPDECLINE) &&
  2196. (type != DHCPINFORM)) {
  2197. LOG_DEBUG(bad_packet4_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_DROP_0006)
  2198. .arg(query->getLabel())
  2199. .arg(type);
  2200. return (false);
  2201. }
  2202. return (true);
  2203. }
  2204. bool
  2205. Dhcpv4Srv::acceptServerId(const Pkt4Ptr& query) const {
  2206. // This function is meant to be called internally by the server class, so
  2207. // we rely on the caller to sanity check the pointer and we don't check
  2208. // it here.
  2209. // Check if server identifier option is present. If it is not present
  2210. // we accept the message because it is targeted to all servers.
  2211. // Note that we don't check cases that server identifier is mandatory
  2212. // but not present. This is meant to be sanity checked in other
  2213. // functions.
  2214. OptionPtr option = query->getOption(DHO_DHCP_SERVER_IDENTIFIER);
  2215. if (!option) {
  2216. return (true);
  2217. }
  2218. // Server identifier is present. Let's convert it to 4-byte address
  2219. // and try to match with server identifiers used by the server.
  2220. OptionCustomPtr option_custom =
  2221. boost::dynamic_pointer_cast<OptionCustom>(option);
  2222. // Unable to convert the option to the option type which encapsulates it.
  2223. // We treat this as non-matching server id.
  2224. if (!option_custom) {
  2225. return (false);
  2226. }
  2227. // The server identifier option should carry exactly one IPv4 address.
  2228. // If the option definition for the server identifier doesn't change,
  2229. // the OptionCustom object should have exactly one IPv4 address and
  2230. // this check is somewhat redundant. On the other hand, if someone
  2231. // breaks option it may be better to check that here.
  2232. if (option_custom->getDataFieldsNum() != 1) {
  2233. return (false);
  2234. }
  2235. // The server identifier MUST be an IPv4 address. If given address is
  2236. // v6, it is wrong.
  2237. IOAddress server_id = option_custom->readAddress();
  2238. if (!server_id.isV4()) {
  2239. return (false);
  2240. }
  2241. // This function iterates over all interfaces on which the
  2242. // server is listening to find the one which has a socket bound
  2243. // to the address carried in the server identifier option.
  2244. // This has some performance implications. However, given that
  2245. // typically there will be just a few active interfaces the
  2246. // performance hit should be acceptable. If it turns out to
  2247. // be significant, we will have to cache server identifiers
  2248. // when sockets are opened.
  2249. return (IfaceMgr::instance().hasOpenSocket(server_id));
  2250. }
  2251. void
  2252. Dhcpv4Srv::sanityCheck(const Pkt4Ptr& query, RequirementLevel serverid) {
  2253. OptionPtr server_id = query->getOption(DHO_DHCP_SERVER_IDENTIFIER);
  2254. switch (serverid) {
  2255. case FORBIDDEN:
  2256. if (server_id) {
  2257. isc_throw(RFCViolation, "Server-id option was not expected, but "
  2258. << "received in "
  2259. << query->getName());
  2260. }
  2261. break;
  2262. case MANDATORY:
  2263. if (!server_id) {
  2264. isc_throw(RFCViolation, "Server-id option was expected, but not "
  2265. " received in message "
  2266. << query->getName());
  2267. }
  2268. break;
  2269. case OPTIONAL:
  2270. // do nothing here
  2271. ;
  2272. }
  2273. // If there is HWAddress set and it is non-empty, then we're good
  2274. if (query->getHWAddr() && !query->getHWAddr()->hwaddr_.empty()) {
  2275. return;
  2276. }
  2277. // There has to be something to uniquely identify the client:
  2278. // either non-zero MAC address or client-id option present (or both)
  2279. OptionPtr client_id = query->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  2280. // If there's no client-id (or a useless one is provided, i.e. 0 length)
  2281. if (!client_id || client_id->len() == client_id->getHeaderLen()) {
  2282. isc_throw(RFCViolation, "Missing or useless client-id and no HW address "
  2283. " provided in message "
  2284. << query->getName());
  2285. }
  2286. }
  2287. void Dhcpv4Srv::classifyByVendor(const Pkt4Ptr& pkt) {
  2288. // Built-in vendor class processing
  2289. boost::shared_ptr<OptionString> vendor_class =
  2290. boost::dynamic_pointer_cast<OptionString>(pkt->getOption(DHO_VENDOR_CLASS_IDENTIFIER));
  2291. if (!vendor_class) {
  2292. return;
  2293. }
  2294. pkt->addClass(VENDOR_CLASS_PREFIX + vendor_class->getValue());
  2295. }
  2296. void Dhcpv4Srv::classifyPacket(const Pkt4Ptr& pkt) {
  2297. // First phase: built-in vendor class processing
  2298. classifyByVendor(pkt);
  2299. // Run match expressions
  2300. // Note getClientClassDictionary() cannot be null
  2301. const ClientClassDefMapPtr& defs_ptr = CfgMgr::instance().getCurrentCfg()->
  2302. getClientClassDictionary()->getClasses();
  2303. for (ClientClassDefMap::const_iterator it = defs_ptr->begin();
  2304. it != defs_ptr->end(); ++it) {
  2305. // Note second cannot be null
  2306. const ExpressionPtr& expr_ptr = it->second->getMatchExpr();
  2307. // Nothing to do without an expression to evaluate
  2308. if (!expr_ptr) {
  2309. continue;
  2310. }
  2311. // Evaluate the expression which can return false (no match),
  2312. // true (match) or raise an exception (error)
  2313. try {
  2314. bool status = evaluate(*expr_ptr, *pkt);
  2315. if (status) {
  2316. LOG_INFO(options4_logger, EVAL_RESULT)
  2317. .arg(it->first)
  2318. .arg(status);
  2319. // Matching: add the class
  2320. pkt->addClass(it->first);
  2321. } else {
  2322. LOG_DEBUG(options4_logger, DBG_DHCP4_DETAIL, EVAL_RESULT)
  2323. .arg(it->first)
  2324. .arg(status);
  2325. }
  2326. } catch (const Exception& ex) {
  2327. LOG_ERROR(options4_logger, EVAL_RESULT)
  2328. .arg(it->first)
  2329. .arg(ex.what());
  2330. } catch (...) {
  2331. LOG_ERROR(options4_logger, EVAL_RESULT)
  2332. .arg(it->first)
  2333. .arg("get exception?");
  2334. }
  2335. }
  2336. }
  2337. void
  2338. Dhcpv4Srv::startD2() {
  2339. D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
  2340. if (d2_mgr.ddnsEnabled()) {
  2341. // Updates are enabled, so lets start the sender, passing in
  2342. // our error handler.
  2343. // This may throw so wherever this is called needs to ready.
  2344. d2_mgr.startSender(boost::bind(&Dhcpv4Srv::d2ClientErrorHandler,
  2345. this, _1, _2));
  2346. }
  2347. }
  2348. void
  2349. Dhcpv4Srv::stopD2() {
  2350. D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
  2351. if (d2_mgr.ddnsEnabled()) {
  2352. // Updates are enabled, so lets stop the sender
  2353. d2_mgr.stopSender();
  2354. }
  2355. }
  2356. void
  2357. Dhcpv4Srv::d2ClientErrorHandler(const
  2358. dhcp_ddns::NameChangeSender::Result result,
  2359. dhcp_ddns::NameChangeRequestPtr& ncr) {
  2360. LOG_ERROR(ddns4_logger, DHCP4_DDNS_REQUEST_SEND_FAILED).
  2361. arg(result).arg((ncr ? ncr->toText() : " NULL "));
  2362. // We cannot communicate with kea-dhcp-ddns, suspend further updates.
  2363. /// @todo We may wish to revisit this, but for now we will simply turn
  2364. /// them off.
  2365. CfgMgr::instance().getD2ClientMgr().suspendUpdates();
  2366. }
  2367. // Refer to config_report so it will be embedded in the binary
  2368. const char* const* dhcp4_config_report = isc::detail::config_report;
  2369. std::string
  2370. Dhcpv4Srv::getVersion(bool extended) {
  2371. std::stringstream tmp;
  2372. tmp << VERSION;
  2373. if (extended) {
  2374. tmp << endl << EXTENDED_VERSION << endl;
  2375. tmp << "linked with:" << endl;
  2376. tmp << Logger::getVersion() << endl;
  2377. tmp << CryptoLink::getVersion() << endl;
  2378. tmp << "database:" << endl;
  2379. #ifdef HAVE_MYSQL
  2380. tmp << MySqlLeaseMgr::getDBVersion() << endl;
  2381. #endif
  2382. #ifdef HAVE_PGSQL
  2383. tmp << PgSqlLeaseMgr::getDBVersion() << endl;
  2384. #endif
  2385. #ifdef HAVE_CQL
  2386. tmp << CqlLeaseMgr::getDBVersion() << endl;
  2387. #endif
  2388. tmp << Memfile_LeaseMgr::getDBVersion();
  2389. // @todo: more details about database runtime
  2390. }
  2391. return (tmp.str());
  2392. }
  2393. void Dhcpv4Srv::processStatsReceived(const Pkt4Ptr& query) {
  2394. // Note that we're not bumping pkt4-received statistic as it was
  2395. // increased early in the packet reception code.
  2396. string stat_name = "pkt4-unknown-received";
  2397. try {
  2398. switch (query->getType()) {
  2399. case DHCPDISCOVER:
  2400. stat_name = "pkt4-discover-received";
  2401. break;
  2402. case DHCPOFFER:
  2403. // Should not happen, but let's keep a counter for it
  2404. stat_name = "pkt4-offer-received";
  2405. break;
  2406. case DHCPREQUEST:
  2407. stat_name = "pkt4-request-received";
  2408. break;
  2409. case DHCPACK:
  2410. // Should not happen, but let's keep a counter for it
  2411. stat_name = "pkt4-ack-received";
  2412. break;
  2413. case DHCPNAK:
  2414. // Should not happen, but let's keep a counter for it
  2415. stat_name = "pkt4-nak-received";
  2416. break;
  2417. case DHCPRELEASE:
  2418. stat_name = "pkt4-release-received";
  2419. break;
  2420. case DHCPDECLINE:
  2421. stat_name = "pkt4-decline-received";
  2422. break;
  2423. case DHCPINFORM:
  2424. stat_name = "pkt4-inform-received";
  2425. break;
  2426. default:
  2427. ; // do nothing
  2428. }
  2429. }
  2430. catch (...) {
  2431. // If the incoming packet doesn't have option 53 (message type)
  2432. // or a hook set pkt4_receive_skip, then Pkt4::getType() may
  2433. // throw an exception. That's ok, we'll then use the default
  2434. // name of pkt4-unknown-received.
  2435. }
  2436. isc::stats::StatsMgr::instance().addValue(stat_name,
  2437. static_cast<int64_t>(1));
  2438. }
  2439. void Dhcpv4Srv::processStatsSent(const Pkt4Ptr& response) {
  2440. // Increase generic counter for sent packets.
  2441. isc::stats::StatsMgr::instance().addValue("pkt4-sent",
  2442. static_cast<int64_t>(1));
  2443. // Increase packet type specific counter for packets sent.
  2444. string stat_name;
  2445. switch (response->getType()) {
  2446. case DHCPOFFER:
  2447. stat_name = "pkt4-offer-sent";
  2448. break;
  2449. case DHCPACK:
  2450. stat_name = "pkt4-ack-sent";
  2451. break;
  2452. case DHCPNAK:
  2453. stat_name = "pkt4-nak-sent";
  2454. break;
  2455. default:
  2456. // That should never happen
  2457. return;
  2458. }
  2459. isc::stats::StatsMgr::instance().addValue(stat_name,
  2460. static_cast<int64_t>(1));
  2461. }
  2462. int Dhcpv4Srv::getHookIndexBuffer4Receive() {
  2463. return (Hooks.hook_index_buffer4_receive_);
  2464. }
  2465. int Dhcpv4Srv::getHookIndexPkt4Receive() {
  2466. return (Hooks.hook_index_pkt4_receive_);
  2467. }
  2468. int Dhcpv4Srv::getHookIndexSubnet4Select() {
  2469. return (Hooks.hook_index_subnet4_select_);
  2470. }
  2471. int Dhcpv4Srv::getHookIndexLease4Release() {
  2472. return (Hooks.hook_index_lease4_release_);
  2473. }
  2474. int Dhcpv4Srv::getHookIndexPkt4Send() {
  2475. return (Hooks.hook_index_pkt4_send_);
  2476. }
  2477. int Dhcpv4Srv::getHookIndexBuffer4Send() {
  2478. return (Hooks.hook_index_buffer4_send_);
  2479. }
  2480. int Dhcpv4Srv::getHookIndexLease4Decline() {
  2481. return (Hooks.hook_index_lease4_decline_);
  2482. }
  2483. } // namespace dhcp
  2484. } // namespace isc