dhcp4_srv.cc 87 KB

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