dhcp4_srv.cc 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167
  1. // Copyright (C) 2011-2015 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <asiolink/io_address.h>
  15. #include <dhcp/dhcp4.h>
  16. #include <dhcp/duid.h>
  17. #include <dhcp/hwaddr.h>
  18. #include <dhcp/iface_mgr.h>
  19. #include <dhcp/option4_addrlst.h>
  20. #include <dhcp/option_int.h>
  21. #include <dhcp/option_int_array.h>
  22. #include <dhcp/option_vendor.h>
  23. #include <dhcp/option_string.h>
  24. #include <dhcp/pkt4.h>
  25. #include <dhcp/docsis3_option_defs.h>
  26. #include <dhcp4/dhcp4_log.h>
  27. #include <dhcp4/dhcp4_srv.h>
  28. #include <dhcpsrv/addr_utilities.h>
  29. #include <dhcpsrv/callout_handle_store.h>
  30. #include <dhcpsrv/cfgmgr.h>
  31. #include <dhcpsrv/cfg_subnets4.h>
  32. #include <dhcpsrv/lease_mgr.h>
  33. #include <dhcpsrv/lease_mgr_factory.h>
  34. #include <dhcpsrv/subnet.h>
  35. #include <dhcpsrv/subnet_selector.h>
  36. #include <dhcpsrv/utils.h>
  37. #include <dhcpsrv/utils.h>
  38. #include <hooks/callout_handle.h>
  39. #include <hooks/hooks_manager.h>
  40. #include <util/strutil.h>
  41. #include <asio.hpp>
  42. #include <boost/bind.hpp>
  43. #include <boost/foreach.hpp>
  44. #include <boost/shared_ptr.hpp>
  45. #include <iomanip>
  46. using namespace isc;
  47. using namespace isc::asiolink;
  48. using namespace isc::dhcp;
  49. using namespace isc::dhcp_ddns;
  50. using namespace isc::hooks;
  51. using namespace isc::log;
  52. using namespace std;
  53. /// Structure that holds registered hook indexes
  54. struct Dhcp4Hooks {
  55. int hook_index_buffer4_receive_;///< index for "buffer4_receive" hook point
  56. int hook_index_pkt4_receive_; ///< index for "pkt4_receive" hook point
  57. int hook_index_subnet4_select_; ///< index for "subnet4_select" hook point
  58. int hook_index_lease4_release_; ///< index for "lease4_release" hook point
  59. int hook_index_pkt4_send_; ///< index for "pkt4_send" hook point
  60. int hook_index_buffer4_send_; ///< index for "buffer4_send" hook point
  61. /// Constructor that registers hook points for DHCPv4 engine
  62. Dhcp4Hooks() {
  63. hook_index_buffer4_receive_= HooksManager::registerHook("buffer4_receive");
  64. hook_index_pkt4_receive_ = HooksManager::registerHook("pkt4_receive");
  65. hook_index_subnet4_select_ = HooksManager::registerHook("subnet4_select");
  66. hook_index_pkt4_send_ = HooksManager::registerHook("pkt4_send");
  67. hook_index_lease4_release_ = HooksManager::registerHook("lease4_release");
  68. hook_index_buffer4_send_ = HooksManager::registerHook("buffer4_send");
  69. }
  70. };
  71. // Declare a Hooks object. As this is outside any function or method, it
  72. // will be instantiated (and the constructor run) when the module is loaded.
  73. // As a result, the hook indexes will be defined before any method in this
  74. // module is called.
  75. Dhcp4Hooks Hooks;
  76. namespace isc {
  77. namespace dhcp {
  78. Dhcpv4Exchange::Dhcpv4Exchange(const AllocEnginePtr& alloc_engine,
  79. const Pkt4Ptr& query)
  80. : alloc_engine_(alloc_engine), query_(query), resp_(),
  81. context_(new AllocEngine::ClientContext4()) {
  82. // Create response message.
  83. initResponse();
  84. // Select subnet for the query message.
  85. selectSubnet();
  86. // Hardware address.
  87. context_->hwaddr_ = query->getHWAddr();
  88. // Client Identifier
  89. OptionPtr opt_clientid = query->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  90. if (opt_clientid) {
  91. context_->clientid_.reset(new ClientId(opt_clientid->getData()));
  92. }
  93. // Check for static reservations.
  94. alloc_engine->findReservation(*context_);
  95. };
  96. void
  97. Dhcpv4Exchange::initResponse() {
  98. uint8_t resp_type = 0;
  99. switch (getQuery()->getType()) {
  100. case DHCPDISCOVER:
  101. resp_type = DHCPOFFER;
  102. break;
  103. case DHCPREQUEST:
  104. case DHCPINFORM:
  105. resp_type = DHCPACK;
  106. break;
  107. default:
  108. ;
  109. }
  110. if (resp_type > 0) {
  111. resp_.reset(new Pkt4(resp_type, getQuery()->getTransid()));
  112. }
  113. }
  114. void
  115. Dhcpv4Exchange::selectSubnet() {
  116. context_->subnet_ = selectSubnet(query_);
  117. }
  118. Subnet4Ptr
  119. Dhcpv4Exchange::selectSubnet(const Pkt4Ptr& query) {
  120. Subnet4Ptr subnet;
  121. SubnetSelector selector;
  122. selector.ciaddr_ = query->getCiaddr();
  123. selector.giaddr_ = query->getGiaddr();
  124. selector.local_address_ = query->getLocalAddr();
  125. selector.remote_address_ = query->getRemoteAddr();
  126. selector.client_classes_ = query->classes_;
  127. selector.iface_name_ = query->getIface();
  128. CfgMgr& cfgmgr = CfgMgr::instance();
  129. subnet = cfgmgr.getCurrentCfg()->getCfgSubnets4()->selectSubnet(selector);
  130. // Let's execute all callouts registered for subnet4_select
  131. if (HooksManager::calloutsPresent(Hooks.hook_index_subnet4_select_)) {
  132. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  133. // We're reusing callout_handle from previous calls
  134. callout_handle->deleteAllArguments();
  135. // Set new arguments
  136. callout_handle->setArgument("query4", query);
  137. callout_handle->setArgument("subnet4", subnet);
  138. callout_handle->setArgument("subnet4collection",
  139. cfgmgr.getCurrentCfg()->
  140. getCfgSubnets4()->getAll());
  141. // Call user (and server-side) callouts
  142. HooksManager::callCallouts(Hooks.hook_index_subnet4_select_,
  143. *callout_handle);
  144. // Callouts decided to skip this step. This means that no subnet
  145. // will be selected. Packet processing will continue, but it will
  146. // be severely limited (i.e. only global options will be assigned)
  147. if (callout_handle->getSkip()) {
  148. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_HOOKS,
  149. DHCP4_HOOK_SUBNET4_SELECT_SKIP);
  150. return (Subnet4Ptr());
  151. }
  152. // Use whatever subnet was specified by the callout
  153. callout_handle->getArgument("subnet4", subnet);
  154. }
  155. return (subnet);
  156. }
  157. const std::string Dhcpv4Srv::VENDOR_CLASS_PREFIX("VENDOR_CLASS_");
  158. Dhcpv4Srv::Dhcpv4Srv(uint16_t port, const bool use_bcast,
  159. const bool direct_response_desired)
  160. : shutdown_(true), alloc_engine_(), port_(port),
  161. use_bcast_(use_bcast), hook_index_pkt4_receive_(-1),
  162. hook_index_subnet4_select_(-1), hook_index_pkt4_send_(-1) {
  163. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_START, DHCP4_OPEN_SOCKET).arg(port);
  164. try {
  165. // Port 0 is used for testing purposes where we don't open broadcast
  166. // capable sockets. So, set the packet filter handling direct traffic
  167. // only if we are in non-test mode.
  168. if (port) {
  169. // First call to instance() will create IfaceMgr (it's a singleton)
  170. // it may throw something if things go wrong.
  171. // The 'true' value of the call to setMatchingPacketFilter imposes
  172. // that IfaceMgr will try to use the mechanism to respond directly
  173. // to the client which doesn't have address assigned. This capability
  174. // may be lacking on some OSes, so there is no guarantee that server
  175. // will be able to respond directly.
  176. IfaceMgr::instance().setMatchingPacketFilter(direct_response_desired);
  177. }
  178. // Instantiate allocation engine
  179. alloc_engine_.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE, 100,
  180. false /* false = IPv4 */));
  181. // Register hook points
  182. hook_index_pkt4_receive_ = Hooks.hook_index_pkt4_receive_;
  183. hook_index_subnet4_select_ = Hooks.hook_index_subnet4_select_;
  184. hook_index_pkt4_send_ = Hooks.hook_index_pkt4_send_;
  185. /// @todo call loadLibraries() when handling configuration changes
  186. } catch (const std::exception &e) {
  187. LOG_ERROR(dhcp4_logger, DHCP4_SRV_CONSTRUCT_ERROR).arg(e.what());
  188. shutdown_ = true;
  189. return;
  190. }
  191. shutdown_ = false;
  192. }
  193. Dhcpv4Srv::~Dhcpv4Srv() {
  194. IfaceMgr::instance().closeSockets();
  195. }
  196. void
  197. Dhcpv4Srv::shutdown() {
  198. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_BASIC, DHCP4_SHUTDOWN_REQUEST);
  199. shutdown_ = true;
  200. }
  201. isc::dhcp::Subnet4Ptr
  202. Dhcpv4Srv::selectSubnet(const Pkt4Ptr& question) {
  203. return (Dhcpv4Exchange::selectSubnet(question));
  204. }
  205. Pkt4Ptr
  206. Dhcpv4Srv::receivePacket(int timeout) {
  207. return (IfaceMgr::instance().receive4(timeout));
  208. }
  209. void
  210. Dhcpv4Srv::sendPacket(const Pkt4Ptr& packet) {
  211. IfaceMgr::instance().send(packet);
  212. }
  213. bool
  214. Dhcpv4Srv::run() {
  215. while (!shutdown_) {
  216. // client's message and server's response
  217. Pkt4Ptr query;
  218. Pkt4Ptr rsp;
  219. try {
  220. // The lease database backend may install some timers for which
  221. // the handlers need to be executed periodically. Retrieve the
  222. // maximum interval at which the handlers must be executed from
  223. // the lease manager.
  224. uint32_t timeout = LeaseMgrFactory::instance().getIOServiceExecInterval();
  225. // If the returned value is zero it means that there are no
  226. // timers installed, so use a default value.
  227. if (timeout == 0) {
  228. timeout = 1000;
  229. }
  230. query = receivePacket(timeout);
  231. } catch (const SignalInterruptOnSelect) {
  232. // Packet reception interrupted because a signal has been received.
  233. // This is not an error because we might have received a SIGTERM,
  234. // SIGINT or SIGHUP which are handled by the server. For signals
  235. // that are not handled by the server we rely on the default
  236. // behavior of the system, but there is nothing we should log here.
  237. } catch (const std::exception& e) {
  238. // Log all other errors.
  239. LOG_ERROR(dhcp4_logger, DHCP4_PACKET_RECEIVE_FAIL).arg(e.what());
  240. }
  241. // Handle next signal received by the process. It must be called after
  242. // an attempt to receive a packet to properly handle server shut down.
  243. // The SIGTERM or SIGINT will be received prior to, or during execution
  244. // of select() (select is invoked by receivePacket()). When that
  245. // happens, select will be interrupted. The signal handler will be
  246. // invoked immediately after select(). The handler will set the
  247. // shutdown flag and cause the process to terminate before the next
  248. // select() function is called. If the function was called before
  249. // receivePacket the process could wait up to the duration of timeout
  250. // of select() to terminate.
  251. handleSignal();
  252. // Execute ready timers for the lease database, e.g. Lease File Cleanup.
  253. try {
  254. LeaseMgrFactory::instance().getIOService()->poll();
  255. } catch (const std::exception& ex) {
  256. LOG_WARN(dhcp4_logger, DHCP4_LEASE_DATABASE_TIMERS_EXEC_FAIL)
  257. .arg(ex.what());
  258. }
  259. // Timeout may be reached or signal received, which breaks select()
  260. // with no reception occurred
  261. if (!query) {
  262. continue;
  263. }
  264. // In order to parse the DHCP options, the server needs to use some
  265. // configuration information such as: existing option spaces, option
  266. // definitions etc. This is the kind of information which is not
  267. // available in the libdhcp, so we need to supply our own implementation
  268. // of the option parsing function here, which would rely on the
  269. // configuration data.
  270. query->setCallback(boost::bind(&Dhcpv4Srv::unpackOptions, this,
  271. _1, _2, _3));
  272. bool skip_unpack = false;
  273. // The packet has just been received so contains the uninterpreted wire
  274. // data; execute callouts registered for buffer4_receive.
  275. if (HooksManager::calloutsPresent(Hooks.hook_index_buffer4_receive_)) {
  276. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  277. // Delete previously set arguments
  278. callout_handle->deleteAllArguments();
  279. // Pass incoming packet as argument
  280. callout_handle->setArgument("query4", query);
  281. // Call callouts
  282. HooksManager::callCallouts(Hooks.hook_index_buffer4_receive_,
  283. *callout_handle);
  284. // Callouts decided to skip the next processing step. The next
  285. // processing step would to parse the packet, so skip at this
  286. // stage means that callouts did the parsing already, so server
  287. // should skip parsing.
  288. if (callout_handle->getSkip()) {
  289. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_HOOKS, DHCP4_HOOK_BUFFER_RCVD_SKIP);
  290. skip_unpack = true;
  291. }
  292. callout_handle->getArgument("query4", query);
  293. }
  294. // Unpack the packet information unless the buffer4_receive callouts
  295. // indicated they did it
  296. if (!skip_unpack) {
  297. try {
  298. query->unpack();
  299. } catch (const std::exception& e) {
  300. // Failed to parse the packet.
  301. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL,
  302. DHCP4_PACKET_PARSE_FAIL).arg(e.what());
  303. continue;
  304. }
  305. }
  306. // Assign this packet to one or more classes if needed. We need to do
  307. // this before calling accept(), because getSubnet4() may need client
  308. // class information.
  309. classifyPacket(query);
  310. // Check whether the message should be further processed or discarded.
  311. // There is no need to log anything here. This function logs by itself.
  312. if (!accept(query)) {
  313. continue;
  314. }
  315. // We have sanity checked (in accept() that the Message Type option
  316. // exists, so we can safely get it here.
  317. int type = query->getType();
  318. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_RECEIVED)
  319. .arg(serverReceivedPacketName(type))
  320. .arg(type)
  321. .arg(query->getIface());
  322. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_QUERY_DATA)
  323. .arg(type)
  324. .arg(query->toText());
  325. // Let's execute all callouts registered for pkt4_receive
  326. if (HooksManager::calloutsPresent(hook_index_pkt4_receive_)) {
  327. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  328. // Delete previously set arguments
  329. callout_handle->deleteAllArguments();
  330. // Pass incoming packet as argument
  331. callout_handle->setArgument("query4", query);
  332. // Call callouts
  333. HooksManager::callCallouts(hook_index_pkt4_receive_,
  334. *callout_handle);
  335. // Callouts decided to skip the next processing step. The next
  336. // processing step would to process the packet, so skip at this
  337. // stage means drop.
  338. if (callout_handle->getSkip()) {
  339. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_HOOKS, DHCP4_HOOK_PACKET_RCVD_SKIP);
  340. continue;
  341. }
  342. callout_handle->getArgument("query4", query);
  343. }
  344. try {
  345. switch (query->getType()) {
  346. case DHCPDISCOVER:
  347. rsp = processDiscover(query);
  348. break;
  349. case DHCPREQUEST:
  350. // Note that REQUEST is used for many things in DHCPv4: for
  351. // requesting new leases, renewing existing ones and even
  352. // for rebinding.
  353. rsp = processRequest(query);
  354. break;
  355. case DHCPRELEASE:
  356. processRelease(query);
  357. break;
  358. case DHCPDECLINE:
  359. processDecline(query);
  360. break;
  361. case DHCPINFORM:
  362. rsp = processInform(query);
  363. break;
  364. default:
  365. // Only action is to output a message if debug is enabled,
  366. // and that is covered by the debug statement before the
  367. // "switch" statement.
  368. ;
  369. }
  370. } catch (const isc::Exception& e) {
  371. // Catch-all exception (at least for ones based on the isc Exception
  372. // class, which covers more or less all that are explicitly raised
  373. // in the Kea code). Just log the problem and ignore the packet.
  374. // (The problem is logged as a debug message because debug is
  375. // disabled by default - it prevents a DDOS attack based on the
  376. // sending of problem packets.)
  377. if (dhcp4_logger.isDebugEnabled(DBG_DHCP4_BASIC)) {
  378. std::string source = "unknown";
  379. HWAddrPtr hwptr = query->getHWAddr();
  380. if (hwptr) {
  381. source = hwptr->toText();
  382. }
  383. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_BASIC,
  384. DHCP4_PACKET_PROCESS_FAIL)
  385. .arg(source).arg(e.what());
  386. }
  387. }
  388. if (!rsp) {
  389. continue;
  390. }
  391. // Let's do class specific processing. This is done before
  392. // pkt4_send.
  393. //
  394. /// @todo: decide whether we want to add a new hook point for
  395. /// doing class specific processing.
  396. if (!classSpecificProcessing(query, rsp)) {
  397. /// @todo add more verbosity here
  398. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_BASIC, DHCP4_CLASS_PROCESSING_FAILED);
  399. continue;
  400. }
  401. // Specifies if server should do the packing
  402. bool skip_pack = false;
  403. // Execute all callouts registered for pkt4_send
  404. if (HooksManager::calloutsPresent(hook_index_pkt4_send_)) {
  405. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  406. // Delete all previous arguments
  407. callout_handle->deleteAllArguments();
  408. // Clear skip flag if it was set in previous callouts
  409. callout_handle->setSkip(false);
  410. // Set our response
  411. callout_handle->setArgument("response4", rsp);
  412. // Call all installed callouts
  413. HooksManager::callCallouts(hook_index_pkt4_send_,
  414. *callout_handle);
  415. // Callouts decided to skip the next processing step. The next
  416. // processing step would to send the packet, so skip at this
  417. // stage means "drop response".
  418. if (callout_handle->getSkip()) {
  419. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_HOOKS, DHCP4_HOOK_PACKET_SEND_SKIP);
  420. skip_pack = true;
  421. }
  422. }
  423. if (!skip_pack) {
  424. try {
  425. rsp->pack();
  426. } catch (const std::exception& e) {
  427. LOG_ERROR(dhcp4_logger, DHCP4_PACKET_SEND_FAIL)
  428. .arg(e.what());
  429. }
  430. }
  431. try {
  432. // Now all fields and options are constructed into output wire buffer.
  433. // Option objects modification does not make sense anymore. Hooks
  434. // can only manipulate wire buffer at this stage.
  435. // Let's execute all callouts registered for buffer4_send
  436. if (HooksManager::calloutsPresent(Hooks.hook_index_buffer4_send_)) {
  437. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  438. // Delete previously set arguments
  439. callout_handle->deleteAllArguments();
  440. // Pass incoming packet as argument
  441. callout_handle->setArgument("response4", rsp);
  442. // Call callouts
  443. HooksManager::callCallouts(Hooks.hook_index_buffer4_send_,
  444. *callout_handle);
  445. // Callouts decided to skip the next processing step. The next
  446. // processing step would to parse the packet, so skip at this
  447. // stage means drop.
  448. if (callout_handle->getSkip()) {
  449. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_HOOKS,
  450. DHCP4_HOOK_BUFFER_SEND_SKIP);
  451. continue;
  452. }
  453. callout_handle->getArgument("response4", rsp);
  454. }
  455. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL_DATA,
  456. DHCP4_RESPONSE_DATA)
  457. .arg(static_cast<int>(rsp->getType())).arg(rsp->toText());
  458. sendPacket(rsp);
  459. } catch (const std::exception& e) {
  460. LOG_ERROR(dhcp4_logger, DHCP4_PACKET_SEND_FAIL)
  461. .arg(e.what());
  462. }
  463. }
  464. return (true);
  465. }
  466. string
  467. Dhcpv4Srv::srvidToString(const OptionPtr& srvid) {
  468. if (!srvid) {
  469. isc_throw(BadValue, "NULL pointer passed to srvidToString()");
  470. }
  471. boost::shared_ptr<Option4AddrLst> generated =
  472. boost::dynamic_pointer_cast<Option4AddrLst>(srvid);
  473. if (!srvid) {
  474. isc_throw(BadValue, "Pointer to invalid option passed to srvidToString()");
  475. }
  476. Option4AddrLst::AddressContainer addrs = generated->getAddresses();
  477. if (addrs.size() != 1) {
  478. isc_throw(BadValue, "Malformed option passed to srvidToString(). "
  479. << "Expected to contain a single IPv4 address.");
  480. }
  481. return (addrs[0].toText());
  482. }
  483. isc::dhcp_ddns::D2Dhcid
  484. Dhcpv4Srv::computeDhcid(const Lease4Ptr& lease) {
  485. if (!lease) {
  486. isc_throw(DhcidComputeError, "a pointer to the lease must be not"
  487. " NULL to compute DHCID");
  488. } else if (lease->hostname_.empty()) {
  489. isc_throw(DhcidComputeError, "unable to compute the DHCID for the"
  490. " lease which has empty hostname set");
  491. }
  492. // In order to compute DHCID the client's hostname must be encoded in
  493. // canonical wire format. It is unlikely that the FQDN is malformed
  494. // because it is validated by the classes which encapsulate options
  495. // carrying client FQDN. However, if the client name was carried in the
  496. // Hostname option it is more likely as it carries the hostname as a
  497. // regular string.
  498. std::vector<uint8_t> fqdn_wire;
  499. try {
  500. OptionDataTypeUtil::writeFqdn(lease->hostname_, fqdn_wire, true);
  501. } catch (const Exception& ex) {
  502. isc_throw(DhcidComputeError, "unable to compute DHCID because the"
  503. " hostname: " << lease->hostname_ << " is invalid");
  504. }
  505. // Prefer client id to HW address to compute DHCID. If Client Id is
  506. // NULL, use HW address.
  507. try {
  508. if (lease->client_id_) {
  509. return (D2Dhcid(lease->client_id_->getClientId(), fqdn_wire));
  510. } else {
  511. return (D2Dhcid(lease->hwaddr_, fqdn_wire));
  512. }
  513. } catch (const Exception& ex) {
  514. isc_throw(DhcidComputeError, "unable to compute DHCID: "
  515. << ex.what());
  516. }
  517. }
  518. void
  519. Dhcpv4Srv::copyDefaultFields(Dhcpv4Exchange& ex) {
  520. ex.getResponse()->setIface(ex.getQuery()->getIface());
  521. ex.getResponse()->setIndex(ex.getQuery()->getIndex());
  522. ex.getResponse()->setSiaddr(IOAddress::IPV4_ZERO_ADDRESS()); // explicitly set this to 0
  523. // ciaddr is always 0, except for the Renew/Rebind state when it may
  524. // be set to the ciaddr sent by the client.
  525. ex.getResponse()->setCiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  526. ex.getResponse()->setHops(ex.getQuery()->getHops());
  527. // copy MAC address
  528. ex.getResponse()->setHWAddr(ex.getQuery()->getHWAddr());
  529. // relay address
  530. ex.getResponse()->setGiaddr(ex.getQuery()->getGiaddr());
  531. // Let's copy client-id to response. See RFC6842.
  532. // It is possible to disable RFC6842 to keep backward compatibility
  533. bool echo = CfgMgr::instance().echoClientId();
  534. OptionPtr client_id = ex.getQuery()->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  535. if (client_id && echo) {
  536. ex.getResponse()->addOption(client_id);
  537. }
  538. // If src/dest HW addresses are used by the packet filtering class
  539. // we need to copy them as well. There is a need to check that the
  540. // address being set is not-NULL because an attempt to set the NULL
  541. // HW would result in exception. If these values are not set, the
  542. // the default HW addresses (zeroed) should be generated by the
  543. // packet filtering class when creating Ethernet header for
  544. // outgoing packet.
  545. HWAddrPtr src_hw_addr = ex.getQuery()->getLocalHWAddr();
  546. if (src_hw_addr) {
  547. ex.getResponse()->setLocalHWAddr(src_hw_addr);
  548. }
  549. HWAddrPtr dst_hw_addr = ex.getQuery()->getRemoteHWAddr();
  550. if (dst_hw_addr) {
  551. ex.getResponse()->setRemoteHWAddr(dst_hw_addr);
  552. }
  553. // If this packet is relayed, we want to copy Relay Agent Info option
  554. OptionPtr rai = ex.getQuery()->getOption(DHO_DHCP_AGENT_OPTIONS);
  555. if (rai) {
  556. ex.getResponse()->addOption(rai);
  557. }
  558. }
  559. void
  560. Dhcpv4Srv::appendDefaultOptions(Dhcpv4Exchange& ex) {
  561. // no-op at this time
  562. }
  563. void
  564. Dhcpv4Srv::appendServerID(Dhcpv4Exchange& ex) {
  565. // The source address for the outbound message should have been set already.
  566. // This is the address that to the best of the server's knowledge will be
  567. // available from the client.
  568. /// @todo: perhaps we should consider some more sophisticated server id
  569. /// generation, but for the current use cases, it should be ok.
  570. ex.getResponse()->addOption(OptionPtr(new Option4AddrLst(DHO_DHCP_SERVER_IDENTIFIER,
  571. ex.getResponse()->getLocalAddr())));
  572. }
  573. void
  574. Dhcpv4Srv::appendRequestedOptions(Dhcpv4Exchange& ex) {
  575. // Get the subnet relevant for the client. We will need it
  576. // to get the options associated with it.
  577. Subnet4Ptr subnet = ex.getContext()->subnet_;
  578. // If we can't find the subnet for the client there is no way
  579. // to get the options to be sent to a client. We don't log an
  580. // error because it will be logged by the assignLease method
  581. // anyway.
  582. if (!subnet) {
  583. return;
  584. }
  585. // try to get the 'Parameter Request List' option which holds the
  586. // codes of requested options.
  587. OptionUint8ArrayPtr option_prl = boost::dynamic_pointer_cast<
  588. OptionUint8Array>(ex.getQuery()->getOption(DHO_DHCP_PARAMETER_REQUEST_LIST));
  589. // If there is no PRL option in the message from the client then
  590. // there is nothing to do.
  591. if (!option_prl) {
  592. return;
  593. }
  594. // Get the codes of requested options.
  595. const std::vector<uint8_t>& requested_opts = option_prl->getValues();
  596. // For each requested option code get the instance of the option
  597. // to be returned to the client.
  598. for (std::vector<uint8_t>::const_iterator opt = requested_opts.begin();
  599. opt != requested_opts.end(); ++opt) {
  600. if (!ex.getResponse()->getOption(*opt)) {
  601. OptionDescriptor desc = subnet->getCfgOption()->get("dhcp4", *opt);
  602. if (desc.option_) {
  603. ex.getResponse()->addOption(desc.option_);
  604. }
  605. }
  606. }
  607. }
  608. void
  609. Dhcpv4Srv::appendRequestedVendorOptions(Dhcpv4Exchange& ex) {
  610. // Get the configured subnet suitable for the incoming packet.
  611. Subnet4Ptr subnet = ex.getContext()->subnet_;
  612. // Leave if there is no subnet matching the incoming packet.
  613. // There is no need to log the error message here because
  614. // it will be logged in the assignLease() when it fails to
  615. // pick the suitable subnet. We don't want to duplicate
  616. // error messages in such case.
  617. if (!subnet) {
  618. return;
  619. }
  620. // Try to get the vendor option
  621. boost::shared_ptr<OptionVendor> vendor_req = boost::dynamic_pointer_cast<
  622. OptionVendor>(ex.getQuery()->getOption(DHO_VIVSO_SUBOPTIONS));
  623. if (!vendor_req) {
  624. return;
  625. }
  626. uint32_t vendor_id = vendor_req->getVendorId();
  627. // Let's try to get ORO within that vendor-option
  628. /// @todo This is very specific to vendor-id=4491 (Cable Labs). Other
  629. /// vendors may have different policies.
  630. OptionUint8ArrayPtr oro =
  631. boost::dynamic_pointer_cast<OptionUint8Array>(vendor_req->getOption(DOCSIS3_V4_ORO));
  632. // Option ORO not found. Don't do anything then.
  633. if (!oro) {
  634. return;
  635. }
  636. boost::shared_ptr<OptionVendor> vendor_rsp(new OptionVendor(Option::V4, vendor_id));
  637. // Get the list of options that client requested.
  638. bool added = false;
  639. const std::vector<uint8_t>& requested_opts = oro->getValues();
  640. for (std::vector<uint8_t>::const_iterator code = requested_opts.begin();
  641. code != requested_opts.end(); ++code) {
  642. if (!vendor_rsp->getOption(*code)) {
  643. OptionDescriptor desc = subnet->getCfgOption()->get(vendor_id,
  644. *code);
  645. if (desc.option_) {
  646. vendor_rsp->addOption(desc.option_);
  647. added = true;
  648. }
  649. }
  650. if (added) {
  651. ex.getResponse()->addOption(vendor_rsp);
  652. }
  653. }
  654. }
  655. void
  656. Dhcpv4Srv::appendBasicOptions(Dhcpv4Exchange& ex) {
  657. // Identify options that we always want to send to the
  658. // client (if they are configured).
  659. static const uint16_t required_options[] = {
  660. DHO_ROUTERS,
  661. DHO_DOMAIN_NAME_SERVERS,
  662. DHO_DOMAIN_NAME };
  663. static size_t required_options_size =
  664. sizeof(required_options) / sizeof(required_options[0]);
  665. // Get the subnet.
  666. Subnet4Ptr subnet = ex.getContext()->subnet_;
  667. if (!subnet) {
  668. return;
  669. }
  670. // Try to find all 'required' options in the outgoing
  671. // message. Those that are not present will be added.
  672. for (int i = 0; i < required_options_size; ++i) {
  673. OptionPtr opt = ex.getResponse()->getOption(required_options[i]);
  674. if (!opt) {
  675. // Check whether option has been configured.
  676. OptionDescriptor desc = subnet->getCfgOption()->
  677. get("dhcp4", required_options[i]);
  678. if (desc.option_) {
  679. ex.getResponse()->addOption(desc.option_);
  680. }
  681. }
  682. }
  683. }
  684. void
  685. Dhcpv4Srv::processClientName(Dhcpv4Exchange& ex) {
  686. // It is possible that client has sent both Client FQDN and Hostname
  687. // option. In such case, server should prefer Client FQDN option and
  688. // ignore the Hostname option.
  689. try {
  690. Pkt4Ptr resp = ex.getResponse();
  691. Option4ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<Option4ClientFqdn>
  692. (ex.getQuery()->getOption(DHO_FQDN));
  693. if (fqdn) {
  694. processClientFqdnOption(ex);
  695. } else {
  696. OptionStringPtr hostname = boost::dynamic_pointer_cast<OptionString>
  697. (ex.getQuery()->getOption(DHO_HOST_NAME));
  698. if (hostname) {
  699. processHostnameOption(ex);
  700. }
  701. }
  702. } catch (const Exception& ex) {
  703. // In some rare cases it is possible that the client's name processing
  704. // fails. For example, the Hostname option may be malformed, or there
  705. // may be an error in the server's logic which would cause multiple
  706. // attempts to add the same option to the response message. This
  707. // error message aggregates all these errors so they can be diagnosed
  708. // from the log. We don't want to throw an exception here because,
  709. // it will impact the processing of the whole packet. We rather want
  710. // the processing to continue, even if the client's name is wrong.
  711. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_CLIENT_NAME_PROC_FAIL)
  712. .arg(ex.what());
  713. }
  714. }
  715. void
  716. Dhcpv4Srv::processClientFqdnOption(Dhcpv4Exchange& ex) {
  717. // Obtain the FQDN option from the client's message.
  718. Option4ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<
  719. Option4ClientFqdn>(ex.getQuery()->getOption(DHO_FQDN));
  720. // Create the DHCPv4 Client FQDN Option to be included in the server's
  721. // response to a client.
  722. Option4ClientFqdnPtr fqdn_resp(new Option4ClientFqdn(*fqdn));
  723. // Set the server S, N, and O flags based on client's flags and
  724. // current configuration.
  725. D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
  726. d2_mgr.adjustFqdnFlags<Option4ClientFqdn>(*fqdn, *fqdn_resp);
  727. // Carry over the client's E flag.
  728. fqdn_resp->setFlag(Option4ClientFqdn::FLAG_E,
  729. fqdn->getFlag(Option4ClientFqdn::FLAG_E));
  730. if (ex.getContext()->host_ && !ex.getContext()->host_->getHostname().empty()) {
  731. D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
  732. fqdn_resp->setDomainName(d2_mgr.qualifyName(ex.getContext()->host_->getHostname(),
  733. true), Option4ClientFqdn::FULL);
  734. } else {
  735. // Adjust the domain name based on domain name value and type sent by the
  736. // client and current configuration.
  737. d2_mgr.adjustDomainName<Option4ClientFqdn>(*fqdn, *fqdn_resp);
  738. }
  739. // Add FQDN option to the response message. Note that, there may be some
  740. // cases when server may choose not to include the FQDN option in a
  741. // response to a client. In such cases, the FQDN should be removed from the
  742. // outgoing message. In theory we could cease to include the FQDN option
  743. // in this function until it is confirmed that it should be included.
  744. // However, we include it here for simplicity. Functions used to acquire
  745. // lease for a client will scan the response message for FQDN and if it
  746. // is found they will take necessary actions to store the FQDN information
  747. // in the lease database as well as to generate NameChangeRequests to DNS.
  748. // If we don't store the option in the response message, we will have to
  749. // propagate it in the different way to the functions which acquire the
  750. // lease. This would require modifications to the API of this class.
  751. ex.getResponse()->addOption(fqdn_resp);
  752. }
  753. void
  754. Dhcpv4Srv::processHostnameOption(Dhcpv4Exchange& ex) {
  755. // Obtain the Hostname option from the client's message.
  756. OptionStringPtr opt_hostname = boost::dynamic_pointer_cast<OptionString>
  757. (ex.getQuery()->getOption(DHO_HOST_NAME));
  758. // Fetch D2 configuration.
  759. D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
  760. // Do nothing if the DNS updates are disabled.
  761. if (!d2_mgr.ddnsEnabled()) {
  762. return;
  763. }
  764. std::string hostname = isc::util::str::trim(opt_hostname->getValue());
  765. unsigned int label_count = OptionDataTypeUtil::getLabelCount(hostname);
  766. // The hostname option sent by the client should be at least 1 octet long.
  767. // If it isn't we ignore this option. (Per RFC 2131, section 3.14)
  768. /// @todo It would be more liberal to accept this and let it fall into
  769. /// the case of replace or less than two below.
  770. if (label_count == 0) {
  771. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_EMPTY_HOSTNAME);
  772. return;
  773. }
  774. // Copy construct the hostname provided by the client. It is entirely
  775. // possible that we will use the hostname option provided by the client
  776. // to perform the DNS update and we will send the same option to him to
  777. // indicate that we accepted this hostname.
  778. OptionStringPtr opt_hostname_resp(new OptionString(*opt_hostname));
  779. // The hostname option may be unqualified or fully qualified. The lab_count
  780. // holds the number of labels for the name. The number of 1 means that
  781. // there is only root label "." (even for unqualified names, as the
  782. // getLabelCount function treats each name as a fully qualified one).
  783. // By checking the number of labels present in the hostname we may infer
  784. // whether client has sent the fully qualified or unqualified hostname.
  785. // If there is a hostname reservation for this client, use it.
  786. if (ex.getContext()->host_ && !ex.getContext()->host_->getHostname().empty()) {
  787. opt_hostname_resp->setValue(d2_mgr.qualifyName(ex.getContext()->host_->getHostname(),
  788. false));
  789. } else if ((d2_mgr.getD2ClientConfig()->getReplaceClientName()) ||
  790. (label_count < 2)) {
  791. // Set to root domain to signal later on that we should replace it.
  792. // DHO_HOST_NAME is a string option which cannot be empty.
  793. /// @todo We may want to reconsider whether it is appropriate for the
  794. /// client to send a root domain name as a Hostname. There are
  795. /// also extensions to the auto generation of the client's name,
  796. /// e.g. conversion to the puny code which may be considered at some point.
  797. /// For now, we just remain liberal and expect that the DNS will handle
  798. /// conversion if needed and possible.
  799. opt_hostname_resp->setValue(".");
  800. } else if (label_count == 2) {
  801. // If there are two labels, it means that the client has specified
  802. // the unqualified name. We have to concatenate the unqualified name
  803. // with the domain name. The false value passed as a second argument
  804. // indicates that the trailing dot should not be appended to the
  805. // hostname. We don't want to append the trailing dot because
  806. // we don't know whether the hostname is partial or not and some
  807. // clients do not handle the hostnames with the trailing dot.
  808. opt_hostname_resp->setValue(d2_mgr.qualifyName(hostname, false));
  809. }
  810. ex.getResponse()->addOption(opt_hostname_resp);
  811. }
  812. void
  813. Dhcpv4Srv::createNameChangeRequests(const Lease4Ptr& lease,
  814. const Lease4Ptr& old_lease) {
  815. if (!lease) {
  816. isc_throw(isc::Unexpected,
  817. "NULL lease specified when creating NameChangeRequest");
  818. }
  819. // If old lease is not NULL, it is an indication that the lease has
  820. // just been renewed. In such case we may need to generate the
  821. // additional NameChangeRequest to remove an existing entry before
  822. // we create a NameChangeRequest to add the entry for an updated lease.
  823. // We may also decide not to generate any requests at all. This is when
  824. // we discover that nothing has changed in the client's FQDN data.
  825. if (old_lease) {
  826. if (!lease->matches(*old_lease)) {
  827. isc_throw(isc::Unexpected,
  828. "there is no match between the current instance of the"
  829. " lease: " << lease->toText() << ", and the previous"
  830. " instance: " << lease->toText());
  831. } else {
  832. // There will be a NameChangeRequest generated to remove existing
  833. // DNS entries if the following conditions are met:
  834. // - The hostname is set for the existing lease, we can't generate
  835. // removal request for non-existent hostname.
  836. // - A server has performed reverse, forward or both updates.
  837. // - FQDN data between the new and old lease do not match.
  838. if (!lease->hasIdenticalFqdn(*old_lease)) {
  839. queueNameChangeRequest(isc::dhcp_ddns::CHG_REMOVE,
  840. old_lease);
  841. // If FQDN data from both leases match, there is no need to update.
  842. } else if (lease->hasIdenticalFqdn(*old_lease)) {
  843. return;
  844. }
  845. }
  846. }
  847. // We may need to generate the NameChangeRequest for the new lease. It
  848. // will be generated only if hostname is set and if forward or reverse
  849. // update has been requested.
  850. queueNameChangeRequest(isc::dhcp_ddns::CHG_ADD, lease);
  851. }
  852. void
  853. Dhcpv4Srv::
  854. queueNameChangeRequest(const isc::dhcp_ddns::NameChangeType chg_type,
  855. const Lease4Ptr& lease) {
  856. // The hostname must not be empty, and at least one type of update
  857. // should be requested.
  858. if (!lease || lease->hostname_.empty() ||
  859. (!lease->fqdn_rev_ && !lease->fqdn_fwd_)) {
  860. return;
  861. }
  862. // Create the DHCID for the NameChangeRequest.
  863. D2Dhcid dhcid;
  864. try {
  865. dhcid = computeDhcid(lease);
  866. } catch (const DhcidComputeError& ex) {
  867. LOG_ERROR(dhcp4_logger, DHCP4_DHCID_COMPUTE_ERROR)
  868. .arg(lease->toText())
  869. .arg(ex.what());
  870. return;
  871. }
  872. // Create NameChangeRequest
  873. NameChangeRequestPtr ncr(new NameChangeRequest(chg_type, lease->fqdn_fwd_,
  874. lease->fqdn_rev_,
  875. lease->hostname_,
  876. lease->addr_.toText(),
  877. dhcid,
  878. (lease->cltt_ +
  879. lease->valid_lft_),
  880. lease->valid_lft_));
  881. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_QUEUE_NCR)
  882. .arg(chg_type == CHG_ADD ? "add" : "remove")
  883. .arg(ncr->toText());
  884. // And pass it to the the manager.
  885. CfgMgr::instance().getD2ClientMgr().sendRequest(ncr);
  886. }
  887. void
  888. Dhcpv4Srv::assignLease(Dhcpv4Exchange& ex) {
  889. // Get the pointers to the query and the response messages.
  890. Pkt4Ptr query = ex.getQuery();
  891. Pkt4Ptr resp = ex.getResponse();
  892. // Get the context.
  893. AllocEngine::ClientContext4Ptr ctx = ex.getContext();
  894. // Subnet should have been already selected when the context was created.
  895. Subnet4Ptr subnet = ctx->subnet_;
  896. if (!subnet) {
  897. // This particular client is out of luck today. We do not have
  898. // information about the subnet he is connected to. This likely means
  899. // misconfiguration of the server (or some relays). We will continue to
  900. // process this message, but our response will be almost useless: no
  901. // addresses or prefixes, no subnet specific configuration etc. The only
  902. // thing this client can get is some global information (like DNS
  903. // servers).
  904. // perhaps this should be logged on some higher level? This is most
  905. // likely configuration bug.
  906. LOG_ERROR(dhcp4_logger, DHCP4_SUBNET_SELECTION_FAILED)
  907. .arg(query->getRemoteAddr().toText())
  908. .arg(serverReceivedPacketName(query->getType()));
  909. resp->setType(DHCPNAK);
  910. resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  911. return;
  912. }
  913. // Set up siaddr. Perhaps assignLease is not the best place to call this
  914. // as siaddr has nothing to do with a lease, but otherwise we would have
  915. // to select subnet twice (performance hit) or update too many functions
  916. // at once.
  917. /// @todo: move subnet selection to a common code
  918. resp->setSiaddr(subnet->getSiaddr());
  919. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_SUBNET_SELECTED)
  920. .arg(subnet->toText());
  921. // Get client-id option
  922. ClientIdPtr client_id;
  923. OptionPtr opt = query->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  924. if (opt) {
  925. client_id = ClientIdPtr(new ClientId(opt->getData()));
  926. }
  927. // client-id is not mandatory in DHCPv4
  928. // Get the server identifier. It will be used to determine the state
  929. // of the client.
  930. OptionCustomPtr opt_serverid = boost::dynamic_pointer_cast<
  931. OptionCustom>(query->getOption(DHO_DHCP_SERVER_IDENTIFIER));
  932. // Check if the client has sent a requested IP address option or
  933. // ciaddr.
  934. OptionCustomPtr opt_requested_address = boost::dynamic_pointer_cast<
  935. OptionCustom>(query->getOption(DHO_DHCP_REQUESTED_ADDRESS));
  936. IOAddress hint(0);
  937. if (opt_requested_address) {
  938. hint = opt_requested_address->readAddress();
  939. } else if (query->getCiaddr() != IOAddress::IPV4_ZERO_ADDRESS()) {
  940. hint = query->getCiaddr();
  941. }
  942. HWAddrPtr hwaddr = query->getHWAddr();
  943. // "Fake" allocation is processing of DISCOVER message. We pretend to do an
  944. // allocation, but we do not put the lease in the database. That is ok,
  945. // because we do not guarantee that the user will get that exact lease. If
  946. // the user selects this server to do actual allocation (i.e. sends REQUEST)
  947. // it should include this hint. That will help us during the actual lease
  948. // allocation.
  949. bool fake_allocation = (query->getType() == DHCPDISCOVER);
  950. // If there is no server id and there is a Requested IP Address option
  951. // the client is in the INIT-REBOOT state in which the server has to
  952. // determine whether the client's notion of the address is correct
  953. // and whether the client is known, i.e., has a lease.
  954. if (!fake_allocation && !opt_serverid && opt_requested_address) {
  955. Lease4Ptr lease;
  956. if (hwaddr) {
  957. lease = LeaseMgrFactory::instance().getLease4(*hwaddr,
  958. subnet->getID());
  959. }
  960. if (!lease && client_id) {
  961. lease = LeaseMgrFactory::instance().getLease4(*client_id,
  962. subnet->getID());
  963. }
  964. // Got a lease so we can check the address.
  965. if (lease && (lease->addr_ != hint)) {
  966. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL,
  967. DHCP4_INVALID_ADDRESS_INIT_REBOOT)
  968. .arg(hint.toText())
  969. .arg(client_id ? client_id->toText():"(no client-id)")
  970. .arg(hwaddr ? hwaddr->toText():"(no hwaddr info)");
  971. resp->setType(DHCPNAK);
  972. resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  973. return;
  974. }
  975. // Now check the second error case: unknown client.
  976. if (!lease) {
  977. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL,
  978. DHCP4_NO_LEASE_INIT_REBOOT)
  979. .arg(hint.toText())
  980. .arg(client_id ? client_id->toText():"(no client-id)")
  981. .arg(hwaddr ? hwaddr->toText():"(no hwaddr info)");
  982. ex.deleteResponse();
  983. return;
  984. }
  985. }
  986. CalloutHandlePtr callout_handle = getCalloutHandle(query);
  987. std::string hostname;
  988. bool fqdn_fwd = false;
  989. bool fqdn_rev = false;
  990. OptionStringPtr opt_hostname;
  991. Option4ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<
  992. Option4ClientFqdn>(resp->getOption(DHO_FQDN));
  993. if (fqdn) {
  994. hostname = fqdn->getDomainName();
  995. CfgMgr::instance().getD2ClientMgr().getUpdateDirections(*fqdn,
  996. fqdn_fwd,
  997. fqdn_rev);
  998. } else {
  999. opt_hostname = boost::dynamic_pointer_cast<OptionString>
  1000. (resp->getOption(DHO_HOST_NAME));
  1001. if (opt_hostname) {
  1002. hostname = opt_hostname->getValue();
  1003. // DHO_HOST_NAME is string option which cannot be blank,
  1004. // we use "." to know we should replace it with a fully
  1005. // generated name. The local string variable needs to be
  1006. // blank in logic below.
  1007. if (hostname == ".") {
  1008. hostname = "";
  1009. }
  1010. /// @todo It could be configurable what sort of updates the
  1011. /// server is doing when Hostname option was sent.
  1012. fqdn_fwd = true;
  1013. fqdn_rev = true;
  1014. }
  1015. }
  1016. // We need to set these values in the context as they haven't been set yet.
  1017. ctx->requested_address_ = hint;
  1018. ctx->fwd_dns_update_ = fqdn_fwd;
  1019. ctx->rev_dns_update_ = fqdn_rev;
  1020. ctx->hostname_ = hostname;
  1021. ctx->fake_allocation_ = fake_allocation;
  1022. ctx->callout_handle_ = callout_handle;
  1023. Lease4Ptr lease = alloc_engine_->allocateLease4(*ctx);
  1024. if (lease) {
  1025. // We have a lease! Let's set it in the packet and send it back to
  1026. // the client.
  1027. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, fake_allocation?
  1028. DHCP4_LEASE_ADVERT:DHCP4_LEASE_ALLOC)
  1029. .arg(lease->addr_.toText())
  1030. .arg(client_id?client_id->toText():"(no client-id)")
  1031. .arg(hwaddr?hwaddr->toText():"(no hwaddr info)");
  1032. resp->setYiaddr(lease->addr_);
  1033. /// @todo The server should check what ciaddr the client has supplied
  1034. /// in ciaddr. Currently the ciaddr is ignored except for the subnet
  1035. /// selection. If the client supplied an invalid address, the server
  1036. /// will also return an invalid address here.
  1037. if (!fake_allocation) {
  1038. // If this is a renewing client it will set a ciaddr which the
  1039. // server may include in the response. If this is a new allocation
  1040. // the client will set ciaddr to 0 and this will also be propagated
  1041. // to the server's resp.
  1042. resp->setCiaddr(query->getCiaddr());
  1043. }
  1044. // If there has been Client FQDN or Hostname option sent, but the
  1045. // hostname is empty, it means that server is responsible for
  1046. // generating the entire hostname for the client. The example of the
  1047. // client's name, generated from the IP address is: host-192-0-2-3.
  1048. if ((fqdn || opt_hostname) && lease->hostname_.empty()) {
  1049. // Note that if we have received the hostname option, rather than
  1050. // Client FQDN the trailing dot is not appended to the generated
  1051. // hostname because some clients don't handle the trailing dot in
  1052. // the hostname. Whether the trailing dot is appended or not is
  1053. // controlled by the second argument to the generateFqdn().
  1054. lease->hostname_ = CfgMgr::instance().getD2ClientMgr()
  1055. .generateFqdn(lease->addr_, static_cast<bool>(fqdn));
  1056. // The operations below are rather safe, but we want to catch
  1057. // any potential exceptions (e.g. invalid lease database backend
  1058. // implementation) and log an error.
  1059. try {
  1060. // The lease update should be safe, because the lease should
  1061. // be already in the database. In most cases the exception
  1062. // would be thrown if the lease was missing.
  1063. LeaseMgrFactory::instance().updateLease4(lease);
  1064. // The name update in the option should be also safe,
  1065. // because the generated name is well formed.
  1066. if (fqdn) {
  1067. fqdn->setDomainName(lease->hostname_,
  1068. Option4ClientFqdn::FULL);
  1069. } else if (opt_hostname) {
  1070. opt_hostname->setValue(lease->hostname_);
  1071. }
  1072. } catch (const Exception& ex) {
  1073. LOG_ERROR(dhcp4_logger, DHCP4_NAME_GEN_UPDATE_FAIL)
  1074. .arg(ex.what());
  1075. }
  1076. }
  1077. // IP Address Lease time (type 51)
  1078. opt.reset(new OptionUint32(Option::V4, DHO_DHCP_LEASE_TIME,
  1079. lease->valid_lft_));
  1080. resp->addOption(opt);
  1081. // Subnet mask (type 1)
  1082. resp->addOption(getNetmaskOption(subnet));
  1083. // renewal-timer (type 58)
  1084. if (!subnet->getT1().unspecified()) {
  1085. OptionUint32Ptr t1(new OptionUint32(Option::V4,
  1086. DHO_DHCP_RENEWAL_TIME,
  1087. subnet->getT1()));
  1088. resp->addOption(t1);
  1089. }
  1090. // rebind timer (type 59)
  1091. if (!subnet->getT2().unspecified()) {
  1092. OptionUint32Ptr t2(new OptionUint32(Option::V4,
  1093. DHO_DHCP_REBINDING_TIME,
  1094. subnet->getT2()));
  1095. resp->addOption(t2);
  1096. }
  1097. // Create NameChangeRequests if DDNS is enabled and this is a
  1098. // real allocation.
  1099. if (!fake_allocation && CfgMgr::instance().ddnsEnabled()) {
  1100. try {
  1101. createNameChangeRequests(lease, ctx->old_lease_);
  1102. } catch (const Exception& ex) {
  1103. LOG_ERROR(dhcp4_logger, DHCP4_NCR_CREATION_FAILED)
  1104. .arg(ex.what());
  1105. }
  1106. }
  1107. } else {
  1108. // Allocation engine did not allocate a lease. The engine logged
  1109. // cause of that failure. The only thing left is to insert
  1110. // status code to pass the sad news to the client.
  1111. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, fake_allocation?
  1112. DHCP4_LEASE_ADVERT_FAIL:DHCP4_LEASE_ALLOC_FAIL)
  1113. .arg(client_id?client_id->toText():"(no client-id)")
  1114. .arg(hwaddr?hwaddr->toText():"(no hwaddr info)")
  1115. .arg(hint.toText());
  1116. resp->setType(DHCPNAK);
  1117. resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  1118. resp->delOption(DHO_FQDN);
  1119. resp->delOption(DHO_HOST_NAME);
  1120. }
  1121. }
  1122. void
  1123. Dhcpv4Srv::adjustIfaceData(Dhcpv4Exchange& ex) {
  1124. adjustRemoteAddr(ex);
  1125. // Initialize the pointers to the client's message and the server's
  1126. // response.
  1127. Pkt4Ptr query = ex.getQuery();
  1128. Pkt4Ptr response = ex.getResponse();
  1129. // For the non-relayed message, the destination port is the client's port.
  1130. // For the relayed message, the server/relay port is a destination.
  1131. // Note that the call to this function may throw if invalid combination
  1132. // of hops and giaddr is found (hops = 0 if giaddr = 0 and hops != 0 if
  1133. // giaddr != 0). The exception will propagate down and eventually cause the
  1134. // packet to be discarded.
  1135. response->setRemotePort(query->isRelayed() ? DHCP4_SERVER_PORT :
  1136. DHCP4_CLIENT_PORT);
  1137. IOAddress local_addr = query->getLocalAddr();
  1138. // In many cases the query is sent to a broadcast address. This address
  1139. // apears as a local address in the query message. We can't simply copy
  1140. // this address to a response message and use it as a source address.
  1141. // Instead we will need to use the address assigned to the interface
  1142. // on which the query has been received. In other cases, we will just
  1143. // use this address as a source address for the response.
  1144. if (local_addr == IOAddress::IPV4_BCAST_ADDRESS()) {
  1145. SocketInfo sock_info = IfaceMgr::instance().getSocket(*query);
  1146. local_addr = sock_info.addr_;
  1147. }
  1148. // We assume that there is an appropriate socket bound to this address
  1149. // and that the address is correct. This is safe assumption because
  1150. // the local address of the query is set when the query is received.
  1151. // The query sent to an incorrect address wouldn't have been received.
  1152. // However, if socket is closed for this address between the reception
  1153. // of the query and sending a response, the IfaceMgr should detect it
  1154. // and return an error.
  1155. response->setLocalAddr(local_addr);
  1156. // In many cases the query is sent to a broadcast address. This address
  1157. // appears as a local address in the query message. Therefore we can't
  1158. // simply copy local address from the query and use it as a source
  1159. // address for the response. Instead, we have to check what address our
  1160. // socket is bound to and use it as a source address. This operation
  1161. // may throw if for some reason the socket is closed.
  1162. /// @todo Consider an optimization that we use local address from
  1163. /// the query if this address is not broadcast.
  1164. response->setLocalPort(DHCP4_SERVER_PORT);
  1165. response->setIface(query->getIface());
  1166. response->setIndex(query->getIndex());
  1167. }
  1168. void
  1169. Dhcpv4Srv::adjustRemoteAddr(Dhcpv4Exchange& ex) {
  1170. // Initialize the pointers to the client's message and the server's
  1171. // response.
  1172. Pkt4Ptr query = ex.getQuery();
  1173. Pkt4Ptr response = ex.getResponse();
  1174. // The DHCPINFORM is slightly different than other messages in a sense
  1175. // that the server should always unicast the response to the ciaddr.
  1176. // It appears however that some clients don't set the ciaddr. We still
  1177. // want to provision these clients and we do what we can't to send the
  1178. // packet to the address where client can receive it.
  1179. if (query->getType() == DHCPINFORM) {
  1180. // If client adheres to RFC2131 it will set the ciaddr and in this
  1181. // case we always unicast our response to this address.
  1182. if (query->getCiaddr() != IOAddress::IPV4_ZERO_ADDRESS()) {
  1183. response->setRemoteAddr(query->getCiaddr());
  1184. // If we received DHCPINFORM via relay and the ciaddr is not set we
  1185. // will try to send the response via relay. The caveat is that the
  1186. // relay will not have any idea where to forward the packet because
  1187. // the yiaddr is likely not set. So, the broadcast flag is set so
  1188. // as the response may be broadcast.
  1189. } else if (query->isRelayed()) {
  1190. response->setRemoteAddr(query->getGiaddr());
  1191. response->setFlags(response->getFlags() | BOOTP_BROADCAST);
  1192. // If there is no ciaddr and no giaddr the only thing we can do is
  1193. // to use the source address of the packet.
  1194. } else {
  1195. response->setRemoteAddr(query->getRemoteAddr());
  1196. }
  1197. // Remote address is now set so return.
  1198. return;
  1199. }
  1200. // If received relayed message, server responds to the relay address.
  1201. if (query->isRelayed()) {
  1202. // The client should set the ciaddr when sending the DHCPINFORM
  1203. // but in case he didn't, the relay may not be able to determine the
  1204. // address of the client, because yiaddr is not set when responding
  1205. // to Confirm and the only address available was the source address
  1206. // of the client. The source address is however not used here because
  1207. // the message is relayed. Therefore, we set the BROADCAST flag so
  1208. // as the relay can broadcast the packet.
  1209. if ((query->getType() == DHCPINFORM) &&
  1210. (query->getCiaddr() == IOAddress::IPV4_ZERO_ADDRESS())) {
  1211. response->setFlags(BOOTP_BROADCAST);
  1212. }
  1213. response->setRemoteAddr(query->getGiaddr());
  1214. // If giaddr is 0 but client set ciaddr, server should unicast the
  1215. // response to ciaddr.
  1216. } else if (query->getCiaddr() != IOAddress::IPV4_ZERO_ADDRESS()) {
  1217. response->setRemoteAddr(query->getCiaddr());
  1218. // We can't unicast the response to the client when sending NAK,
  1219. // because we haven't allocated address for him. Therefore,
  1220. // NAK is broadcast.
  1221. } else if (response->getType() == DHCPNAK) {
  1222. response->setRemoteAddr(IOAddress::IPV4_BCAST_ADDRESS());
  1223. // If yiaddr is set it means that we have created a lease for a client.
  1224. } else if (response->getYiaddr() != IOAddress::IPV4_ZERO_ADDRESS()) {
  1225. // If the broadcast bit is set in the flags field, we have to
  1226. // send the response to broadcast address. Client may have requested it
  1227. // because it doesn't support reception of messages on the interface
  1228. // which doesn't have an address assigned. The other case when response
  1229. // must be broadcasted is when our server does not support responding
  1230. // directly to a client without address assigned.
  1231. const bool bcast_flag = ((query->getFlags() & Pkt4::FLAG_BROADCAST_MASK) != 0);
  1232. if (!IfaceMgr::instance().isDirectResponseSupported() || bcast_flag) {
  1233. response->setRemoteAddr(IOAddress::IPV4_BCAST_ADDRESS());
  1234. // Client cleared the broadcast bit and we support direct responses
  1235. // so we should unicast the response to a newly allocated address -
  1236. // yiaddr.
  1237. } else {
  1238. response->setRemoteAddr(response ->getYiaddr());
  1239. }
  1240. // In most cases, we should have the remote address found already. If we
  1241. // found ourselves at this point, the rational thing to do is to respond
  1242. // to the address we got the query from.
  1243. } else {
  1244. response->setRemoteAddr(query->getRemoteAddr());
  1245. }
  1246. }
  1247. OptionPtr
  1248. Dhcpv4Srv::getNetmaskOption(const Subnet4Ptr& subnet) {
  1249. uint32_t netmask = getNetmask4(subnet->get().second);
  1250. OptionPtr opt(new OptionInt<uint32_t>(Option::V4,
  1251. DHO_SUBNET_MASK, netmask));
  1252. return (opt);
  1253. }
  1254. Pkt4Ptr
  1255. Dhcpv4Srv::processDiscover(Pkt4Ptr& discover) {
  1256. Dhcpv4Exchange ex(alloc_engine_, discover);
  1257. sanityCheck(ex, FORBIDDEN);
  1258. copyDefaultFields(ex);
  1259. appendDefaultOptions(ex);
  1260. // If DHCPDISCOVER message contains the FQDN or Hostname option, server
  1261. // may respond to the client with the appropriate FQDN or Hostname
  1262. // option to indicate that whether it will take responsibility for
  1263. // updating DNS when the client sends DHCPREQUEST message.
  1264. processClientName(ex);
  1265. assignLease(ex);
  1266. if (!ex.getResponse()) {
  1267. // The offer is empty so return it *now*!
  1268. return (Pkt4Ptr());
  1269. }
  1270. // Adding any other options makes sense only when we got the lease.
  1271. if (!ex.getResponse()->getYiaddr().isV4Zero()) {
  1272. appendRequestedOptions(ex);
  1273. appendRequestedVendorOptions(ex);
  1274. // There are a few basic options that we always want to
  1275. // include in the response. If client did not request
  1276. // them we append them for him.
  1277. appendBasicOptions(ex);
  1278. } else {
  1279. // If the server can't offer an address, it drops the packet.
  1280. return (Pkt4Ptr());
  1281. }
  1282. // Set the src/dest IP address, port and interface for the outgoing
  1283. // packet.
  1284. adjustIfaceData(ex);
  1285. appendServerID(ex);
  1286. return (ex.getResponse());
  1287. }
  1288. Pkt4Ptr
  1289. Dhcpv4Srv::processRequest(Pkt4Ptr& request) {
  1290. Dhcpv4Exchange ex(alloc_engine_, request);
  1291. /// @todo Uncomment this (see ticket #3116)
  1292. /// sanityCheck(ex, MANDATORY);
  1293. copyDefaultFields(ex);
  1294. appendDefaultOptions(ex);
  1295. // If DHCPREQUEST message contains the FQDN or Hostname option, server
  1296. // should respond to the client with the appropriate FQDN or Hostname
  1297. // option to indicate if it takes responsibility for the DNS updates.
  1298. // This is performed by the function below.
  1299. processClientName(ex);
  1300. // Note that we treat REQUEST message uniformly, regardless if this is a
  1301. // first request (requesting for new address), renewing existing address
  1302. // or even rebinding.
  1303. assignLease(ex);
  1304. if (!ex.getResponse()) {
  1305. // The ack is empty so return it *now*!
  1306. return (Pkt4Ptr());
  1307. }
  1308. // Adding any other options makes sense only when we got the lease.
  1309. if (!ex.getResponse()->getYiaddr().isV4Zero()) {
  1310. appendRequestedOptions(ex);
  1311. appendRequestedVendorOptions(ex);
  1312. // There are a few basic options that we always want to
  1313. // include in the response. If client did not request
  1314. // them we append them for him.
  1315. appendBasicOptions(ex);
  1316. }
  1317. // Set the src/dest IP address, port and interface for the outgoing
  1318. // packet.
  1319. adjustIfaceData(ex);
  1320. appendServerID(ex);
  1321. return (ex.getResponse());
  1322. }
  1323. void
  1324. Dhcpv4Srv::processRelease(Pkt4Ptr& release) {
  1325. /// @todo Uncomment this (see ticket #3116)
  1326. /// sanityCheck(release, MANDATORY);
  1327. // Try to find client-id
  1328. ClientIdPtr client_id;
  1329. OptionPtr opt = release->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  1330. if (opt) {
  1331. client_id = ClientIdPtr(new ClientId(opt->getData()));
  1332. }
  1333. try {
  1334. // Do we have a lease for that particular address?
  1335. Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(release->getCiaddr());
  1336. if (!lease) {
  1337. // No such lease - bogus release
  1338. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL,
  1339. DHCP4_RELEASE_FAIL_NO_LEASE)
  1340. .arg(client_id ? client_id->toText() : "(no client-id)")
  1341. .arg(release->getHWAddr() ?
  1342. release->getHWAddr()->toText() : "(no hwaddr info)")
  1343. .arg(release->getCiaddr().toText());
  1344. return;
  1345. }
  1346. // Does the hardware address match? We don't want one client releasing
  1347. // second client's leases. Note that we're comparing the hardware
  1348. // addresses only, not hardware types or sources of the hardware
  1349. // addresses. Thus we don't use HWAddr::equals().
  1350. if (lease->hwaddr_->hwaddr_ != release->getHWAddr()->hwaddr_) {
  1351. /// @todo: Print hwaddr from lease as part of ticket #2589
  1352. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_RELEASE_FAIL_WRONG_HWADDR)
  1353. .arg(release->getCiaddr().toText())
  1354. .arg(client_id ? client_id->toText() : "(no client-id)")
  1355. .arg(release->getHWAddr()->toText());
  1356. return;
  1357. }
  1358. // Does the lease have client-id info? If it has, then check it with what
  1359. // the client sent us.
  1360. if (lease->client_id_ && client_id && *lease->client_id_ != *client_id) {
  1361. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_RELEASE_FAIL_WRONG_CLIENT_ID)
  1362. .arg(release->getCiaddr().toText())
  1363. .arg(client_id->toText())
  1364. .arg(lease->client_id_->toText());
  1365. return;
  1366. }
  1367. bool skip = false;
  1368. // Execute all callouts registered for lease4_release
  1369. if (HooksManager::calloutsPresent(Hooks.hook_index_lease4_release_)) {
  1370. CalloutHandlePtr callout_handle = getCalloutHandle(release);
  1371. // Delete all previous arguments
  1372. callout_handle->deleteAllArguments();
  1373. // Pass the original packet
  1374. callout_handle->setArgument("query4", release);
  1375. // Pass the lease to be updated
  1376. callout_handle->setArgument("lease4", lease);
  1377. // Call all installed callouts
  1378. HooksManager::callCallouts(Hooks.hook_index_lease4_release_,
  1379. *callout_handle);
  1380. // Callouts decided to skip the next processing step. The next
  1381. // processing step would to send the packet, so skip at this
  1382. // stage means "drop response".
  1383. if (callout_handle->getSkip()) {
  1384. skip = true;
  1385. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_HOOKS,
  1386. DHCP4_HOOK_LEASE4_RELEASE_SKIP);
  1387. }
  1388. }
  1389. // Ok, hw and client-id match - let's release the lease.
  1390. if (!skip) {
  1391. bool success = LeaseMgrFactory::instance().deleteLease(lease->addr_);
  1392. if (success) {
  1393. // Release successful
  1394. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_RELEASE)
  1395. .arg(lease->addr_.toText())
  1396. .arg(client_id ? client_id->toText() : "(no client-id)")
  1397. .arg(release->getHWAddr()->toText());
  1398. if (CfgMgr::instance().ddnsEnabled()) {
  1399. // Remove existing DNS entries for the lease, if any.
  1400. queueNameChangeRequest(isc::dhcp_ddns::CHG_REMOVE, lease);
  1401. }
  1402. } else {
  1403. // Release failed -
  1404. LOG_ERROR(dhcp4_logger, DHCP4_RELEASE_FAIL)
  1405. .arg(lease->addr_.toText())
  1406. .arg(client_id ? client_id->toText() : "(no client-id)")
  1407. .arg(release->getHWAddr()->toText());
  1408. }
  1409. }
  1410. } catch (const isc::Exception& ex) {
  1411. // Rethrow the exception with a bit more data.
  1412. LOG_ERROR(dhcp4_logger, DHCP4_RELEASE_EXCEPTION)
  1413. .arg(ex.what())
  1414. .arg(release->getYiaddr());
  1415. }
  1416. }
  1417. void
  1418. Dhcpv4Srv::processDecline(Pkt4Ptr&) {
  1419. /// @todo Implement this (also see ticket #3116)
  1420. }
  1421. Pkt4Ptr
  1422. Dhcpv4Srv::processInform(Pkt4Ptr& inform) {
  1423. Dhcpv4Exchange ex(alloc_engine_, inform);
  1424. // DHCPINFORM MUST not include server identifier.
  1425. sanityCheck(ex, FORBIDDEN);
  1426. Pkt4Ptr ack = ex.getResponse();
  1427. copyDefaultFields(ex);
  1428. appendRequestedOptions(ex);
  1429. appendRequestedVendorOptions(ex);
  1430. appendBasicOptions(ex);
  1431. adjustIfaceData(ex);
  1432. // There are cases for the DHCPINFORM that the server receives it via
  1433. // relay but will send the response to the client's unicast address
  1434. // carried in the ciaddr. In this case, the giaddr and hops field should
  1435. // be cleared (these fields were copied by the copyDefaultFields function).
  1436. // Also Relay Agent Options should be removed if present.
  1437. if (ack->getRemoteAddr() != inform->getGiaddr()) {
  1438. ack->setHops(0);
  1439. ack->setGiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  1440. ack->delOption(DHO_DHCP_AGENT_OPTIONS);
  1441. }
  1442. // The DHCPACK must contain server id.
  1443. appendServerID(ex);
  1444. return (ex.getResponse());
  1445. }
  1446. const char*
  1447. Dhcpv4Srv::serverReceivedPacketName(uint8_t type) {
  1448. static const char* DISCOVER = "DISCOVER";
  1449. static const char* REQUEST = "REQUEST";
  1450. static const char* RELEASE = "RELEASE";
  1451. static const char* DECLINE = "DECLINE";
  1452. static const char* INFORM = "INFORM";
  1453. static const char* UNKNOWN = "UNKNOWN";
  1454. switch (type) {
  1455. case DHCPDISCOVER:
  1456. return (DISCOVER);
  1457. case DHCPREQUEST:
  1458. return (REQUEST);
  1459. case DHCPRELEASE:
  1460. return (RELEASE);
  1461. case DHCPDECLINE:
  1462. return (DECLINE);
  1463. case DHCPINFORM:
  1464. return (INFORM);
  1465. default:
  1466. ;
  1467. }
  1468. return (UNKNOWN);
  1469. }
  1470. bool
  1471. Dhcpv4Srv::accept(const Pkt4Ptr& query) const {
  1472. // Check that the message type is accepted by the server. We rely on the
  1473. // function called to log a message if needed.
  1474. if (!acceptMessageType(query)) {
  1475. return (false);
  1476. }
  1477. // Check if the message from directly connected client (if directly
  1478. // connected) should be dropped or processed.
  1479. if (!acceptDirectRequest(query)) {
  1480. LOG_INFO(dhcp4_logger, DHCP4_NO_SUBNET_FOR_DIRECT_CLIENT)
  1481. .arg(query->getTransid())
  1482. .arg(query->getIface());
  1483. return (false);
  1484. }
  1485. // Check if the DHCPv4 packet has been sent to us or to someone else.
  1486. // If it hasn't been sent to us, drop it!
  1487. if (!acceptServerId(query)) {
  1488. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_NOT_FOR_US)
  1489. .arg(query->getTransid())
  1490. .arg(query->getIface());
  1491. return (false);
  1492. }
  1493. return (true);
  1494. }
  1495. bool
  1496. Dhcpv4Srv::acceptDirectRequest(const Pkt4Ptr& pkt) const {
  1497. try {
  1498. // This is the first call to the isRelayed function for this packet,
  1499. // so we have to catch exceptions which will be emitted if the
  1500. // packet contains invalid combination of hops and giaddr. For all
  1501. // other invocations of isRelayed function we will not catch
  1502. // exceptions because we eliminate malformed packets here.
  1503. if (pkt->isRelayed()) {
  1504. return (true);
  1505. }
  1506. } catch (const Exception& ex) {
  1507. OptionPtr client_id = pkt->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  1508. HWAddrPtr hwaddr = pkt->getHWAddr();
  1509. LOG_INFO(dhcp4_logger, DHCP4_INVALID_RELAY_INFO)
  1510. .arg(client_id ? client_id->toText():"(no client-id)")
  1511. .arg(hwaddr ? hwaddr->toText():"(no hwaddr info)")
  1512. .arg(ex.what());
  1513. return (false);
  1514. }
  1515. // The source address must not be zero for the DHCPINFORM message from
  1516. // the directly connected client because the server will not know where
  1517. // to respond if the ciaddr was not present.
  1518. try {
  1519. if (pkt->getType() == DHCPINFORM) {
  1520. if ((pkt->getRemoteAddr() == IOAddress::IPV4_ZERO_ADDRESS()) &&
  1521. (pkt->getCiaddr() == IOAddress::IPV4_ZERO_ADDRESS())) {
  1522. return (false);
  1523. }
  1524. }
  1525. } catch (...) {
  1526. // If we got here, it is probably because the message type hasn't
  1527. // been set. But, this should not really happen assuming that
  1528. // we validate the message type prior to calling this function.
  1529. return (false);
  1530. }
  1531. return ((pkt->getLocalAddr() != IOAddress::IPV4_BCAST_ADDRESS()
  1532. || Dhcpv4Exchange::selectSubnet(pkt)));
  1533. }
  1534. bool
  1535. Dhcpv4Srv::acceptMessageType(const Pkt4Ptr& query) const {
  1536. // When receiving a packet without message type option, getType() will
  1537. // throw.
  1538. int type;
  1539. try {
  1540. type = query->getType();
  1541. } catch (...) {
  1542. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_DROP_NO_TYPE)
  1543. .arg(query->getIface());
  1544. return (false);
  1545. }
  1546. // If we receive a message with a non-existing type, we are logging it.
  1547. if (type > DHCPLEASEQUERYDONE) {
  1548. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL,
  1549. DHCP4_UNRECOGNIZED_RCVD_PACKET_TYPE)
  1550. .arg(type)
  1551. .arg(query->getTransid());
  1552. return (false);
  1553. }
  1554. // Once we know that the message type is within a range of defined DHCPv4
  1555. // messages, we do a detailed check to make sure that the received message
  1556. // is targeted at server. Note that we could have received some Offer
  1557. // message broadcasted by the other server to a relay. Even though, the
  1558. // server would rather unicast its response to a relay, let's be on the
  1559. // safe side. Also, we want to drop other messages which we don't support.
  1560. // All these valid messages that we are not going to process are dropped
  1561. // silently.
  1562. if ((type != DHCPDISCOVER) && (type != DHCPREQUEST) &&
  1563. (type != DHCPRELEASE) && (type != DHCPDECLINE) &&
  1564. (type != DHCPINFORM)) {
  1565. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL,
  1566. DHCP4_UNSUPPORTED_RCVD_PACKET_TYPE)
  1567. .arg(type)
  1568. .arg(query->getTransid());
  1569. return (false);
  1570. }
  1571. return (true);
  1572. }
  1573. bool
  1574. Dhcpv4Srv::acceptServerId(const Pkt4Ptr& query) const {
  1575. // This function is meant to be called internally by the server class, so
  1576. // we rely on the caller to sanity check the pointer and we don't check
  1577. // it here.
  1578. // Check if server identifier option is present. If it is not present
  1579. // we accept the message because it is targeted to all servers.
  1580. // Note that we don't check cases that server identifier is mandatory
  1581. // but not present. This is meant to be sanity checked in other
  1582. // functions.
  1583. OptionPtr option = query->getOption(DHO_DHCP_SERVER_IDENTIFIER);
  1584. if (!option) {
  1585. return (true);
  1586. }
  1587. // Server identifier is present. Let's convert it to 4-byte address
  1588. // and try to match with server identifiers used by the server.
  1589. OptionCustomPtr option_custom =
  1590. boost::dynamic_pointer_cast<OptionCustom>(option);
  1591. // Unable to convert the option to the option type which encapsulates it.
  1592. // We treat this as non-matching server id.
  1593. if (!option_custom) {
  1594. return (false);
  1595. }
  1596. // The server identifier option should carry exactly one IPv4 address.
  1597. // If the option definition for the server identifier doesn't change,
  1598. // the OptionCustom object should have exactly one IPv4 address and
  1599. // this check is somewhat redundant. On the other hand, if someone
  1600. // breaks option it may be better to check that here.
  1601. if (option_custom->getDataFieldsNum() != 1) {
  1602. return (false);
  1603. }
  1604. // The server identifier MUST be an IPv4 address. If given address is
  1605. // v6, it is wrong.
  1606. IOAddress server_id = option_custom->readAddress();
  1607. if (!server_id.isV4()) {
  1608. return (false);
  1609. }
  1610. // This function iterates over all interfaces on which the
  1611. // server is listening to find the one which has a socket bound
  1612. // to the address carried in the server identifier option.
  1613. // This has some performance implications. However, given that
  1614. // typically there will be just a few active interfaces the
  1615. // performance hit should be acceptable. If it turns out to
  1616. // be significant, we will have to cache server identifiers
  1617. // when sockets are opened.
  1618. return (IfaceMgr::instance().hasOpenSocket(server_id));
  1619. }
  1620. void
  1621. Dhcpv4Srv::sanityCheck(const Dhcpv4Exchange& ex, RequirementLevel serverid) {
  1622. OptionPtr server_id = ex.getQuery()->getOption(DHO_DHCP_SERVER_IDENTIFIER);
  1623. switch (serverid) {
  1624. case FORBIDDEN:
  1625. if (server_id) {
  1626. isc_throw(RFCViolation, "Server-id option was not expected, but "
  1627. << "received in "
  1628. << serverReceivedPacketName(ex.getQuery()->getType()));
  1629. }
  1630. break;
  1631. case MANDATORY:
  1632. if (!server_id) {
  1633. isc_throw(RFCViolation, "Server-id option was expected, but not "
  1634. " received in message "
  1635. << serverReceivedPacketName(ex.getQuery()->getType()));
  1636. }
  1637. break;
  1638. case OPTIONAL:
  1639. // do nothing here
  1640. ;
  1641. }
  1642. // If there is HWAddress set and it is non-empty, then we're good
  1643. if (ex.getQuery()->getHWAddr() && !ex.getQuery()->getHWAddr()->hwaddr_.empty()) {
  1644. return;
  1645. }
  1646. // There has to be something to uniquely identify the client:
  1647. // either non-zero MAC address or client-id option present (or both)
  1648. OptionPtr client_id = ex.getQuery()->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
  1649. // If there's no client-id (or a useless one is provided, i.e. 0 length)
  1650. if (!client_id || client_id->len() == client_id->getHeaderLen()) {
  1651. isc_throw(RFCViolation, "Missing or useless client-id and no HW address "
  1652. " provided in message "
  1653. << serverReceivedPacketName(ex.getQuery()->getType()));
  1654. }
  1655. }
  1656. size_t
  1657. Dhcpv4Srv::unpackOptions(const OptionBuffer& buf,
  1658. const std::string& option_space,
  1659. isc::dhcp::OptionCollection& options) {
  1660. size_t offset = 0;
  1661. OptionDefContainer option_defs;
  1662. if (option_space == "dhcp4") {
  1663. // Get the list of standard option definitions.
  1664. option_defs = LibDHCP::getOptionDefs(Option::V4);
  1665. } else if (!option_space.empty()) {
  1666. OptionDefContainerPtr option_defs_ptr = CfgMgr::instance()
  1667. .getCurrentCfg()->getCfgOptionDef()->getAll(option_space);
  1668. if (option_defs_ptr != NULL) {
  1669. option_defs = *option_defs_ptr;
  1670. }
  1671. }
  1672. // Get the search index #1. It allows to search for option definitions
  1673. // using option code.
  1674. const OptionDefContainerTypeIndex& idx = option_defs.get<1>();
  1675. // The buffer being read comprises a set of options, each starting with
  1676. // a one-byte type code and a one-byte length field.
  1677. while (offset + 1 <= buf.size()) {
  1678. uint8_t opt_type = buf[offset++];
  1679. // DHO_END is a special, one octet long option
  1680. if (opt_type == DHO_END)
  1681. return (offset); // just return. Don't need to add DHO_END option
  1682. // DHO_PAD is just a padding after DHO_END. Let's continue parsing
  1683. // in case we receive a message without DHO_END.
  1684. if (opt_type == DHO_PAD)
  1685. continue;
  1686. if (offset + 1 > buf.size()) {
  1687. // opt_type must be cast to integer so as it is not treated as
  1688. // unsigned char value (a number is presented in error message).
  1689. isc_throw(OutOfRange, "Attempt to parse truncated option "
  1690. << static_cast<int>(opt_type));
  1691. }
  1692. uint8_t opt_len = buf[offset++];
  1693. if (offset + opt_len > buf.size()) {
  1694. // We peeked at the option header of the next option, but discovered
  1695. // that it would end up beyond buffer end, so the option is
  1696. // truncated. Hence we can't parse it. Therefore we revert
  1697. // back by two bytes (as if we never parsed them).
  1698. return (offset - 2);
  1699. // isc_throw(OutOfRange, "Option parse failed. Tried to parse "
  1700. // << offset + opt_len << " bytes from " << buf.size()
  1701. // << "-byte long buffer.");
  1702. }
  1703. // Get all definitions with the particular option code. Note that option code
  1704. // is non-unique within this container however at this point we expect
  1705. // to get one option definition with the particular code. If more are
  1706. // returned we report an error.
  1707. const OptionDefContainerTypeRange& range = idx.equal_range(opt_type);
  1708. // Get the number of returned option definitions for the option code.
  1709. size_t num_defs = distance(range.first, range.second);
  1710. OptionPtr opt;
  1711. if (num_defs > 1) {
  1712. // Multiple options of the same code are not supported right now!
  1713. isc_throw(isc::Unexpected, "Internal error: multiple option definitions"
  1714. " for option type " << static_cast<int>(opt_type)
  1715. << " returned. Currently it is not supported to initialize"
  1716. << " multiple option definitions for the same option code."
  1717. << " This will be supported once support for option spaces"
  1718. << " is implemented");
  1719. } else if (num_defs == 0) {
  1720. opt = OptionPtr(new Option(Option::V4, opt_type,
  1721. buf.begin() + offset,
  1722. buf.begin() + offset + opt_len));
  1723. opt->setEncapsulatedSpace("dhcp4");
  1724. } else {
  1725. // The option definition has been found. Use it to create
  1726. // the option instance from the provided buffer chunk.
  1727. const OptionDefinitionPtr& def = *(range.first);
  1728. assert(def);
  1729. opt = def->optionFactory(Option::V4, opt_type,
  1730. buf.begin() + offset,
  1731. buf.begin() + offset + opt_len,
  1732. boost::bind(&Dhcpv4Srv::unpackOptions,
  1733. this, _1, _2, _3));
  1734. }
  1735. options.insert(std::make_pair(opt_type, opt));
  1736. offset += opt_len;
  1737. }
  1738. return (offset);
  1739. }
  1740. void
  1741. Dhcpv4Srv::ifaceMgrSocket4ErrorHandler(const std::string& errmsg) {
  1742. // Log the reason for socket opening failure and return.
  1743. LOG_WARN(dhcp4_logger, DHCP4_OPEN_SOCKET_FAIL).arg(errmsg);
  1744. }
  1745. void Dhcpv4Srv::classifyPacket(const Pkt4Ptr& pkt) {
  1746. boost::shared_ptr<OptionString> vendor_class =
  1747. boost::dynamic_pointer_cast<OptionString>(pkt->getOption(DHO_VENDOR_CLASS_IDENTIFIER));
  1748. string classes = "";
  1749. if (!vendor_class) {
  1750. return;
  1751. }
  1752. // DOCSIS specific section
  1753. // Let's keep this as a series of checks. So far we're supporting only
  1754. // docsis3.0, but there are also docsis2.0, docsis1.1 and docsis1.0. We
  1755. // may come up with adding several classes, e.g. for docsis2.0 we would
  1756. // add classes docsis2.0, docsis1.1 and docsis1.0.
  1757. // Also we are using find, because we have at least one traffic capture
  1758. // where the user class was followed by a space ("docsis3.0 ").
  1759. // For now, the code is very simple, but it is expected to get much more
  1760. // complex soon. One specific case is that the vendor class is an option
  1761. // sent by the client, so we should not trust it. To confirm that the device
  1762. // is indeed a modem, John B. suggested to check whether chaddr field
  1763. // quals subscriber-id option that was inserted by the relay (CMTS).
  1764. // This kind of logic will appear here soon.
  1765. if (vendor_class->getValue().find(DOCSIS3_CLASS_MODEM) != std::string::npos) {
  1766. pkt->addClass(VENDOR_CLASS_PREFIX + DOCSIS3_CLASS_MODEM);
  1767. classes += string(VENDOR_CLASS_PREFIX + DOCSIS3_CLASS_MODEM) + " ";
  1768. } else
  1769. if (vendor_class->getValue().find(DOCSIS3_CLASS_EROUTER) != std::string::npos) {
  1770. pkt->addClass(VENDOR_CLASS_PREFIX + DOCSIS3_CLASS_EROUTER);
  1771. classes += string(VENDOR_CLASS_PREFIX + DOCSIS3_CLASS_EROUTER) + " ";
  1772. } else {
  1773. classes += VENDOR_CLASS_PREFIX + vendor_class->getValue();
  1774. pkt->addClass(VENDOR_CLASS_PREFIX + vendor_class->getValue());
  1775. }
  1776. if (!classes.empty()) {
  1777. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_BASIC, DHCP4_CLASS_ASSIGNED)
  1778. .arg(classes);
  1779. }
  1780. }
  1781. bool Dhcpv4Srv::classSpecificProcessing(const Pkt4Ptr& query, const Pkt4Ptr& rsp) {
  1782. Subnet4Ptr subnet = Dhcpv4Exchange::selectSubnet(query);
  1783. if (!subnet) {
  1784. return (true);
  1785. }
  1786. if (query->inClass(VENDOR_CLASS_PREFIX + DOCSIS3_CLASS_MODEM)) {
  1787. // Set next-server. This is TFTP server address. Cable modems will
  1788. // download their configuration from that server.
  1789. rsp->setSiaddr(subnet->getSiaddr());
  1790. // Now try to set up file field in DHCPv4 packet. We will just copy
  1791. // content of the boot-file option, which contains the same information.
  1792. OptionDescriptor desc = subnet->getCfgOption()->
  1793. get("dhcp4", DHO_BOOT_FILE_NAME);
  1794. if (desc.option_) {
  1795. boost::shared_ptr<OptionString> boot =
  1796. boost::dynamic_pointer_cast<OptionString>(desc.option_);
  1797. if (boot) {
  1798. std::string filename = boot->getValue();
  1799. rsp->setFile((const uint8_t*)filename.c_str(), filename.size());
  1800. }
  1801. }
  1802. }
  1803. if (query->inClass(VENDOR_CLASS_PREFIX + DOCSIS3_CLASS_EROUTER)) {
  1804. // Do not set TFTP server address for eRouter devices.
  1805. rsp->setSiaddr(IOAddress::IPV4_ZERO_ADDRESS());
  1806. }
  1807. return (true);
  1808. }
  1809. void
  1810. Dhcpv4Srv::startD2() {
  1811. D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
  1812. if (d2_mgr.ddnsEnabled()) {
  1813. // Updates are enabled, so lets start the sender, passing in
  1814. // our error handler.
  1815. // This may throw so wherever this is called needs to ready.
  1816. d2_mgr.startSender(boost::bind(&Dhcpv4Srv::d2ClientErrorHandler,
  1817. this, _1, _2));
  1818. }
  1819. }
  1820. void
  1821. Dhcpv4Srv::d2ClientErrorHandler(const
  1822. dhcp_ddns::NameChangeSender::Result result,
  1823. dhcp_ddns::NameChangeRequestPtr& ncr) {
  1824. LOG_ERROR(dhcp4_logger, DHCP4_DDNS_REQUEST_SEND_FAILED).
  1825. arg(result).arg((ncr ? ncr->toText() : " NULL "));
  1826. // We cannot communicate with kea-dhcp-ddns, suspend further updates.
  1827. /// @todo We may wish to revisit this, but for now we will simply turn
  1828. /// them off.
  1829. CfgMgr::instance().getD2ClientMgr().suspendUpdates();
  1830. }
  1831. std::string
  1832. Daemon::getVersion(bool extended) {
  1833. std::stringstream tmp;
  1834. tmp << VERSION;
  1835. if (extended) {
  1836. tmp << endl << EXTENDED_VERSION;
  1837. // @todo print more details (is it Botan or OpenSSL build,
  1838. // with or without MySQL/Postgres? What compilation options were
  1839. // used? etc)
  1840. }
  1841. return (tmp.str());
  1842. }
  1843. } // namespace dhcp
  1844. } // namespace isc