dhcp4_srv.cc 79 KB

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