Kea 1.9.11
dhcp4_srv.cc
Go to the documentation of this file.
1// Copyright (C) 2011-2021 Internet Systems Consortium, Inc. ("ISC")
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7#include <config.h>
8#include <kea_version.h>
9
10#include <dhcp/dhcp4.h>
11#include <dhcp/duid.h>
12#include <dhcp/hwaddr.h>
13#include <dhcp/iface_mgr.h>
14#include <dhcp/libdhcp++.h>
16#include <dhcp/option_custom.h>
17#include <dhcp/option_int.h>
19#include <dhcp/option_vendor.h>
20#include <dhcp/option_string.h>
21#include <dhcp/pkt4.h>
22#include <dhcp/pkt4o6.h>
23#include <dhcp/pkt6.h>
26#include <dhcp4/dhcp4to6_ipc.h>
27#include <dhcp4/dhcp4_log.h>
28#include <dhcp4/dhcp4_srv.h>
30#include <dhcpsrv/cfgmgr.h>
32#include <dhcpsrv/cfg_iface.h>
35#include <dhcpsrv/fuzz.h>
36#include <dhcpsrv/lease_mgr.h>
40#include <dhcpsrv/subnet.h>
42#include <dhcpsrv/utils.h>
43#include <eval/evaluate.h>
44#include <eval/eval_messages.h>
46#include <hooks/hooks_log.h>
47#include <hooks/hooks_manager.h>
48#include <stats/stats_mgr.h>
49#include <util/strutil.h>
50#include <log/logger.h>
53
54#ifdef HAVE_MYSQL
56#endif
57#ifdef HAVE_PGSQL
59#endif
60#ifdef HAVE_CQL
62#endif
64
65#include <boost/algorithm/string.hpp>
66#include <boost/foreach.hpp>
67#include <boost/pointer_cast.hpp>
68#include <boost/shared_ptr.hpp>
69
70#include <functional>
71#include <iomanip>
72#include <set>
73#include <cstdlib>
74
75using namespace isc;
76using namespace isc::asiolink;
77using namespace isc::cryptolink;
78using namespace isc::dhcp;
79using namespace isc::dhcp_ddns;
80using namespace isc::hooks;
81using namespace isc::log;
82using namespace isc::stats;
83using namespace isc::util;
84using namespace std;
85namespace ph = std::placeholders;
86
87namespace {
88
90struct Dhcp4Hooks {
91 int hook_index_buffer4_receive_;
92 int hook_index_pkt4_receive_;
93 int hook_index_subnet4_select_;
94 int hook_index_leases4_committed_;
95 int hook_index_lease4_release_;
96 int hook_index_pkt4_send_;
97 int hook_index_buffer4_send_;
98 int hook_index_lease4_decline_;
99 int hook_index_host4_identifier_;
100
102 Dhcp4Hooks() {
103 hook_index_buffer4_receive_ = HooksManager::registerHook("buffer4_receive");
104 hook_index_pkt4_receive_ = HooksManager::registerHook("pkt4_receive");
105 hook_index_subnet4_select_ = HooksManager::registerHook("subnet4_select");
106 hook_index_leases4_committed_ = HooksManager::registerHook("leases4_committed");
107 hook_index_lease4_release_ = HooksManager::registerHook("lease4_release");
108 hook_index_pkt4_send_ = HooksManager::registerHook("pkt4_send");
109 hook_index_buffer4_send_ = HooksManager::registerHook("buffer4_send");
110 hook_index_lease4_decline_ = HooksManager::registerHook("lease4_decline");
111 hook_index_host4_identifier_ = HooksManager::registerHook("host4_identifier");
112 }
113};
114
117std::set<std::string> dhcp4_statistics = {
118 "pkt4-received",
119 "pkt4-discover-received",
120 "pkt4-offer-received",
121 "pkt4-request-received",
122 "pkt4-ack-received",
123 "pkt4-nak-received",
124 "pkt4-release-received",
125 "pkt4-decline-received",
126 "pkt4-inform-received",
127 "pkt4-unknown-received",
128 "pkt4-sent",
129 "pkt4-offer-sent",
130 "pkt4-ack-sent",
131 "pkt4-nak-sent",
132 "pkt4-parse-failed",
133 "pkt4-receive-drop"
134};
135
136} // end of anonymous namespace
137
138// Declare a Hooks object. As this is outside any function or method, it
139// will be instantiated (and the constructor run) when the module is loaded.
140// As a result, the hook indexes will be defined before any method in this
141// module is called.
142Dhcp4Hooks Hooks;
143
144namespace isc {
145namespace dhcp {
146
148 const Pkt4Ptr& query,
149 const Subnet4Ptr& subnet,
150 bool& drop)
151 : alloc_engine_(alloc_engine), query_(query), resp_(),
152 context_(new AllocEngine::ClientContext4()) {
153
154 if (!alloc_engine_) {
155 isc_throw(BadValue, "alloc_engine value must not be NULL"
156 " when creating an instance of the Dhcpv4Exchange");
157 }
158
159 if (!query_) {
160 isc_throw(BadValue, "query value must not be NULL when"
161 " creating an instance of the Dhcpv4Exchange");
162 }
163 // Create response message.
164 initResponse();
165 // Select subnet for the query message.
166 context_->subnet_ = subnet;
167 // Hardware address.
168 context_->hwaddr_ = query->getHWAddr();
169 // Pointer to client's query.
170 context_->query_ = query;
171
172 // If subnet found, retrieve client identifier which will be needed
173 // for allocations and search for reservations associated with a
174 // subnet/shared network.
176 if (subnet) {
177 OptionPtr opt_clientid = query->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
178 if (opt_clientid) {
179 context_->clientid_.reset(new ClientId(opt_clientid->getData()));
180 }
181
182 // Find static reservations if not disabled for our subnet.
183 if (subnet->getReservationsInSubnet() ||
184 subnet->getReservationsGlobal()) {
185 // Before we can check for static reservations, we need to prepare a set
186 // of identifiers to be used for this.
187 setHostIdentifiers();
188
189 // Check for static reservations.
190 alloc_engine->findReservation(*context_);
191
192 // Get shared network to see if it is set for a subnet.
193 subnet->getSharedNetwork(sn);
194 }
195 }
196
197 // Global host reservations are independent of a selected subnet. If the
198 // global reservations contain client classes we should use them in case
199 // they are meant to affect pool selection. Also, if the subnet does not
200 // belong to a shared network we can use the reserved client classes
201 // because there is no way our subnet could change. Such classes may
202 // affect selection of a pool within the selected subnet.
203 auto global_host = context_->globalHost();
204 auto current_host = context_->currentHost();
205 if ((global_host && !global_host->getClientClasses4().empty()) ||
206 (!sn && current_host && !current_host->getClientClasses4().empty())) {
207 // We have already evaluated client classes and some of them may
208 // be in conflict with the reserved classes. Suppose there are
209 // two classes defined in the server configuration: first_class
210 // and second_class and the test for the second_class it looks
211 // like this: "not member('first_class')". If the first_class
212 // initially evaluates to false, the second_class evaluates to
213 // true. If the first_class is now set within the hosts reservations
214 // and we don't remove the previously evaluated second_class we'd
215 // end up with both first_class and second_class evaluated to
216 // true. In order to avoid that, we have to remove the classes
217 // evaluated in the first pass and evaluate them again. As
218 // a result, the first_class set via the host reservation will
219 // replace the second_class because the second_class will this
220 // time evaluate to false as desired.
221 const ClientClassDictionaryPtr& dict =
222 CfgMgr::instance().getCurrentCfg()->getClientClassDictionary();
223 const ClientClassDefListPtr& defs_ptr = dict->getClasses();
224 for (auto def : *defs_ptr) {
225 // Only remove evaluated classes. Other classes can be
226 // assigned via hooks libraries and we should not remove
227 // them because there is no way they can be added back.
228 if (def->getMatchExpr()) {
229 context_->query_->classes_.erase(def->getName());
230 }
231 }
232 setReservedClientClasses(context_);
233 evaluateClasses(context_->query_, false);
234 }
235
236 // Set KNOWN builtin class if something was found, UNKNOWN if not.
237 if (!context_->hosts_.empty()) {
238 query->addClass("KNOWN");
240 .arg(query->getLabel())
241 .arg("KNOWN");
242 } else {
243 query->addClass("UNKNOWN");
245 .arg(query->getLabel())
246 .arg("UNKNOWN");
247 }
248
249 // Perform second pass of classification.
250 evaluateClasses(query, true);
251
252 const ClientClasses& classes = query_->getClasses();
253 if (!classes.empty()) {
255 .arg(query_->getLabel())
256 .arg(classes.toText());
257 }
258
259 // Check the DROP special class.
260 if (query_->inClass("DROP")) {
262 .arg(query_->toText());
263 isc::stats::StatsMgr::instance().addValue("pkt4-receive-drop",
264 static_cast<int64_t>(1));
265 drop = true;
266 }
267}
268
269void
271 uint8_t resp_type = 0;
272 switch (getQuery()->getType()) {
273 case DHCPDISCOVER:
274 resp_type = DHCPOFFER;
275 break;
276 case DHCPREQUEST:
277 case DHCPINFORM:
278 resp_type = DHCPACK;
279 break;
280 default:
281 ;
282 }
283 // Only create a response if one is required.
284 if (resp_type > 0) {
285 resp_.reset(new Pkt4(resp_type, getQuery()->getTransid()));
286 copyDefaultFields();
287 copyDefaultOptions();
288
289 if (getQuery()->isDhcp4o6()) {
291 }
292 }
293}
294
295void
297 Pkt4o6Ptr query = boost::dynamic_pointer_cast<Pkt4o6>(getQuery());
298 if (!query) {
299 return;
300 }
301 const Pkt6Ptr& query6 = query->getPkt6();
302 Pkt6Ptr resp6(new Pkt6(DHCPV6_DHCPV4_RESPONSE, query6->getTransid()));
303 // Don't add client-id or server-id
304 // But copy relay info
305 if (!query6->relay_info_.empty()) {
306 resp6->copyRelayInfo(query6);
307 }
308 // Copy interface, and remote address and port
309 resp6->setIface(query6->getIface());
310 resp6->setIndex(query6->getIndex());
311 resp6->setRemoteAddr(query6->getRemoteAddr());
312 resp6->setRemotePort(query6->getRemotePort());
313 resp_.reset(new Pkt4o6(resp_, resp6));
314}
315
316void
317Dhcpv4Exchange::copyDefaultFields() {
318 resp_->setIface(query_->getIface());
319 resp_->setIndex(query_->getIndex());
320
321 // explicitly set this to 0
322 resp_->setSiaddr(IOAddress::IPV4_ZERO_ADDRESS());
323 // ciaddr is always 0, except for the Renew/Rebind state and for
324 // Inform when it may be set to the ciaddr sent by the client.
325 if (query_->getType() == DHCPINFORM) {
326 resp_->setCiaddr(query_->getCiaddr());
327 } else {
328 resp_->setCiaddr(IOAddress::IPV4_ZERO_ADDRESS());
329 }
330 resp_->setHops(query_->getHops());
331
332 // copy MAC address
333 resp_->setHWAddr(query_->getHWAddr());
334
335 // relay address
336 resp_->setGiaddr(query_->getGiaddr());
337
338 // If src/dest HW addresses are used by the packet filtering class
339 // we need to copy them as well. There is a need to check that the
340 // address being set is not-NULL because an attempt to set the NULL
341 // HW would result in exception. If these values are not set, the
342 // the default HW addresses (zeroed) should be generated by the
343 // packet filtering class when creating Ethernet header for
344 // outgoing packet.
345 HWAddrPtr src_hw_addr = query_->getLocalHWAddr();
346 if (src_hw_addr) {
347 resp_->setLocalHWAddr(src_hw_addr);
348 }
349 HWAddrPtr dst_hw_addr = query_->getRemoteHWAddr();
350 if (dst_hw_addr) {
351 resp_->setRemoteHWAddr(dst_hw_addr);
352 }
353
354 // Copy flags from the request to the response per RFC 2131
355 resp_->setFlags(query_->getFlags());
356}
357
358void
359Dhcpv4Exchange::copyDefaultOptions() {
360 // Let's copy client-id to response. See RFC6842.
361 // It is possible to disable RFC6842 to keep backward compatibility
362 bool echo = CfgMgr::instance().getCurrentCfg()->getEchoClientId();
363 OptionPtr client_id = query_->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
364 if (client_id && echo) {
365 resp_->addOption(client_id);
366 }
367
368 // If this packet is relayed, we want to copy Relay Agent Info option
369 // when it is not empty.
370 OptionPtr rai = query_->getOption(DHO_DHCP_AGENT_OPTIONS);
371 if (rai && (rai->len() > Option::OPTION4_HDR_LEN)) {
372 resp_->addOption(rai);
373 }
374
375 // RFC 3011 states about the Subnet Selection Option
376
377 // "Servers configured to support this option MUST return an
378 // identical copy of the option to any client that sends it,
379 // regardless of whether or not the client requests the option in
380 // a parameter request list. Clients using this option MUST
381 // discard DHCPOFFER or DHCPACK packets that do not contain this
382 // option."
383 OptionPtr subnet_sel = query_->getOption(DHO_SUBNET_SELECTION);
384 if (subnet_sel) {
385 resp_->addOption(subnet_sel);
386 }
387}
388
389void
390Dhcpv4Exchange::setHostIdentifiers() {
391 const ConstCfgHostOperationsPtr cfg =
392 CfgMgr::instance().getCurrentCfg()->getCfgHostOperations4();
393
394 // Collect host identifiers. The identifiers are stored in order of preference.
395 // The server will use them in that order to search for host reservations.
396 BOOST_FOREACH(const Host::IdentifierType& id_type,
397 cfg->getIdentifierTypes()) {
398 switch (id_type) {
400 if (context_->hwaddr_ && !context_->hwaddr_->hwaddr_.empty()) {
401 context_->addHostIdentifier(id_type, context_->hwaddr_->hwaddr_);
402 }
403 break;
404
405 case Host::IDENT_DUID:
406 if (context_->clientid_) {
407 const std::vector<uint8_t>& vec = context_->clientid_->getDuid();
408 if (!vec.empty()) {
409 // Client identifier type = DUID? Client identifier holding a DUID
410 // comprises Type (1 byte), IAID (4 bytes), followed by the actual
411 // DUID. Thus, the minimal length is 6.
412 if ((vec[0] == CLIENT_ID_OPTION_TYPE_DUID) && (vec.size() > 5)) {
413 // Extract DUID, skip IAID.
414 context_->addHostIdentifier(id_type,
415 std::vector<uint8_t>(vec.begin() + 5,
416 vec.end()));
417 }
418 }
419 }
420 break;
421
423 {
424 OptionPtr rai = query_->getOption(DHO_DHCP_AGENT_OPTIONS);
425 if (rai) {
426 OptionPtr circuit_id_opt = rai->getOption(RAI_OPTION_AGENT_CIRCUIT_ID);
427 if (circuit_id_opt) {
428 const OptionBuffer& circuit_id_vec = circuit_id_opt->getData();
429 if (!circuit_id_vec.empty()) {
430 context_->addHostIdentifier(id_type, circuit_id_vec);
431 }
432 }
433 }
434 }
435 break;
436
438 if (context_->clientid_) {
439 const std::vector<uint8_t>& vec = context_->clientid_->getDuid();
440 if (!vec.empty()) {
441 context_->addHostIdentifier(id_type, vec);
442 }
443 }
444 break;
445 case Host::IDENT_FLEX:
446 {
447 if (!HooksManager::calloutsPresent(Hooks.hook_index_host4_identifier_)) {
448 break;
449 }
450
451 CalloutHandlePtr callout_handle = getCalloutHandle(context_->query_);
452
454 std::vector<uint8_t> id;
455
456 // Use the RAII wrapper to make sure that the callout handle state is
457 // reset when this object goes out of scope. All hook points must do
458 // it to prevent possible circular dependency between the callout
459 // handle and its arguments.
460 ScopedCalloutHandleState callout_handle_state(callout_handle);
461
462 // Pass incoming packet as argument
463 callout_handle->setArgument("query4", context_->query_);
464 callout_handle->setArgument("id_type", type);
465 callout_handle->setArgument("id_value", id);
466
467 // Call callouts
468 HooksManager::callCallouts(Hooks.hook_index_host4_identifier_,
469 *callout_handle);
470
471 callout_handle->getArgument("id_type", type);
472 callout_handle->getArgument("id_value", id);
473
474 if ((callout_handle->getStatus() == CalloutHandle::NEXT_STEP_CONTINUE) &&
475 !id.empty()) {
476
478 .arg(Host::getIdentifierAsText(type, &id[0], id.size()));
479
480 context_->addHostIdentifier(type, id);
481 }
482 break;
483 }
484 default:
485 ;
486 }
487 }
488}
489
490void
492 if (context->currentHost() && context->query_) {
493 const ClientClasses& classes = context->currentHost()->getClientClasses4();
494 for (ClientClasses::const_iterator cclass = classes.cbegin();
495 cclass != classes.cend(); ++cclass) {
496 context->query_->addClass(*cclass);
497 }
498 }
499}
500
501void
503 if (context_->subnet_) {
504 SharedNetwork4Ptr shared_network;
505 context_->subnet_->getSharedNetwork(shared_network);
506 if (shared_network) {
507 ConstHostPtr host = context_->currentHost();
508 if (host && (host->getIPv4SubnetID() != SUBNET_ID_GLOBAL)) {
509 setReservedClientClasses(context_);
510 }
511 }
512 }
513}
514
515void
517 ConstHostPtr host = context_->currentHost();
518 // Nothing to do if host reservations not specified for this client.
519 if (host) {
520 if (!host->getNextServer().isV4Zero()) {
521 resp_->setSiaddr(host->getNextServer());
522 }
523
524 std::string sname = host->getServerHostname();
525 if (!sname.empty()) {
526 resp_->setSname(reinterpret_cast<const uint8_t*>(sname.c_str()),
527 sname.size());
528 }
529
530 std::string bootfile = host->getBootFileName();
531 if (!bootfile.empty()) {
532 resp_->setFile(reinterpret_cast<const uint8_t*>(bootfile.c_str()),
533 bootfile.size());
534 }
535 }
536}
537
539 // Built-in vendor class processing
540 boost::shared_ptr<OptionString> vendor_class =
541 boost::dynamic_pointer_cast<OptionString>(pkt->getOption(DHO_VENDOR_CLASS_IDENTIFIER));
542
543 if (!vendor_class) {
544 return;
545 }
546
547 pkt->addClass(Dhcpv4Srv::VENDOR_CLASS_PREFIX + vendor_class->getValue());
548}
549
551 // All packets belongs to ALL.
552 pkt->addClass("ALL");
553
554 // First: built-in vendor class processing.
555 classifyByVendor(pkt);
556
557 // Run match expressions on classes not depending on KNOWN/UNKNOWN.
558 evaluateClasses(pkt, false);
559}
560
561void Dhcpv4Exchange::evaluateClasses(const Pkt4Ptr& pkt, bool depend_on_known) {
562 // Note getClientClassDictionary() cannot be null
563 const ClientClassDictionaryPtr& dict =
564 CfgMgr::instance().getCurrentCfg()->getClientClassDictionary();
565 const ClientClassDefListPtr& defs_ptr = dict->getClasses();
566 for (ClientClassDefList::const_iterator it = defs_ptr->cbegin();
567 it != defs_ptr->cend(); ++it) {
568 // Note second cannot be null
569 const ExpressionPtr& expr_ptr = (*it)->getMatchExpr();
570 // Nothing to do without an expression to evaluate
571 if (!expr_ptr) {
572 continue;
573 }
574 // Not the right time if only when required
575 if ((*it)->getRequired()) {
576 continue;
577 }
578 // Not the right pass.
579 if ((*it)->getDependOnKnown() != depend_on_known) {
580 continue;
581 }
582 // Evaluate the expression which can return false (no match),
583 // true (match) or raise an exception (error)
584 try {
585 bool status = evaluateBool(*expr_ptr, *pkt);
586 if (status) {
588 .arg((*it)->getName())
589 .arg(status);
590 // Matching: add the class
591 pkt->addClass((*it)->getName());
592 } else {
594 .arg((*it)->getName())
595 .arg(status);
596 }
597 } catch (const Exception& ex) {
599 .arg((*it)->getName())
600 .arg(ex.what());
601 } catch (...) {
603 .arg((*it)->getName())
604 .arg("get exception?");
605 }
606 }
607}
608
609const std::string Dhcpv4Srv::VENDOR_CLASS_PREFIX("VENDOR_CLASS_");
610
611Dhcpv4Srv::Dhcpv4Srv(uint16_t server_port, uint16_t client_port,
612 const bool use_bcast, const bool direct_response_desired)
613 : io_service_(new IOService()), server_port_(server_port),
614 client_port_(client_port), shutdown_(true),
615 alloc_engine_(), use_bcast_(use_bcast),
616 network_state_(new NetworkState(NetworkState::DHCPv4)),
617 cb_control_(new CBControlDHCPv4()),
618 test_send_responses_to_source_(false) {
619
620 const char* env = std::getenv("KEA_TEST_SEND_RESPONSES_TO_SOURCE");
621 if (env) {
623 test_send_responses_to_source_ = true;
624 }
625
627 .arg(server_port);
628
629 try {
630 // Port 0 is used for testing purposes where we don't open broadcast
631 // capable sockets. So, set the packet filter handling direct traffic
632 // only if we are in non-test mode.
633 if (server_port) {
634 // First call to instance() will create IfaceMgr (it's a singleton)
635 // it may throw something if things go wrong.
636 // The 'true' value of the call to setMatchingPacketFilter imposes
637 // that IfaceMgr will try to use the mechanism to respond directly
638 // to the client which doesn't have address assigned. This capability
639 // may be lacking on some OSes, so there is no guarantee that server
640 // will be able to respond directly.
641 IfaceMgr::instance().setMatchingPacketFilter(direct_response_desired);
642 }
643
644 // Instantiate allocation engine. The number of allocation attempts equal
645 // to zero indicates that the allocation engine will use the number of
646 // attempts depending on the pool size.
648 false /* false = IPv4 */));
649
651
652 } catch (const std::exception &e) {
654 shutdown_ = true;
655 return;
656 }
657
658 // Initializing all observations with default value
660 shutdown_ = false;
661}
662
665
666 // Iterate over set of observed statistics
667 for (auto it = dhcp4_statistics.begin(); it != dhcp4_statistics.end(); ++it) {
668 // Initialize them with default value 0
669 stats_mgr.setValue((*it), static_cast<int64_t>(0));
670 }
671}
672
674 // Discard any parked packets
676
677 try {
678 stopD2();
679 } catch (const std::exception& ex) {
680 // Highly unlikely, but lets Report it but go on
682 }
683
684 try {
686 } catch (const std::exception& ex) {
687 // Highly unlikely, but lets Report it but go on
689 }
690
692
693 // The lease manager was instantiated during DHCPv4Srv configuration,
694 // so we should clean up after ourselves.
696
697 // Explicitly unload hooks
698 HooksManager::prepareUnloadLibraries();
699 if (!HooksManager::unloadLibraries()) {
700 auto names = HooksManager::getLibraryNames();
701 std::string msg;
702 if (!names.empty()) {
703 msg = names[0];
704 for (size_t i = 1; i < names.size(); ++i) {
705 msg += std::string(", ") + names[i];
706 }
707 }
709 }
710}
711
712void
715 shutdown_ = true;
716}
717
719Dhcpv4Srv::selectSubnet(const Pkt4Ptr& query, bool& drop,
720 bool sanity_only) const {
721
722 // DHCPv4-over-DHCPv6 is a special (and complex) case
723 if (query->isDhcp4o6()) {
724 return (selectSubnet4o6(query, drop, sanity_only));
725 }
726
727 Subnet4Ptr subnet;
728
729 const SubnetSelector& selector = CfgSubnets4::initSelector(query);
730
731 CfgMgr& cfgmgr = CfgMgr::instance();
732 subnet = cfgmgr.getCurrentCfg()->getCfgSubnets4()->selectSubnet(selector);
733
734 // Let's execute all callouts registered for subnet4_select
735 // (skip callouts if the selectSubnet was called to do sanity checks only)
736 if (!sanity_only &&
737 HooksManager::calloutsPresent(Hooks.hook_index_subnet4_select_)) {
738 CalloutHandlePtr callout_handle = getCalloutHandle(query);
739
740 // Use the RAII wrapper to make sure that the callout handle state is
741 // reset when this object goes out of scope. All hook points must do
742 // it to prevent possible circular dependency between the callout
743 // handle and its arguments.
744 ScopedCalloutHandleState callout_handle_state(callout_handle);
745
746 // Enable copying options from the packet within hook library.
747 ScopedEnableOptionsCopy<Pkt4> query4_options_copy(query);
748
749 // Set new arguments
750 callout_handle->setArgument("query4", query);
751 callout_handle->setArgument("subnet4", subnet);
752 callout_handle->setArgument("subnet4collection",
753 cfgmgr.getCurrentCfg()->
754 getCfgSubnets4()->getAll());
755
756 // Call user (and server-side) callouts
757 HooksManager::callCallouts(Hooks.hook_index_subnet4_select_,
758 *callout_handle);
759
760 // Callouts decided to skip this step. This means that no subnet
761 // will be selected. Packet processing will continue, but it will
762 // be severely limited (i.e. only global options will be assigned)
763 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
766 .arg(query->getLabel());
767 return (Subnet4Ptr());
768 }
769
770 // Callouts decided to drop the packet. It is a superset of the
771 // skip case so no subnet will be selected.
772 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP) {
775 .arg(query->getLabel());
776 drop = true;
777 return (Subnet4Ptr());
778 }
779
780 // Use whatever subnet was specified by the callout
781 callout_handle->getArgument("subnet4", subnet);
782 }
783
784 if (subnet) {
785 // Log at higher debug level that subnet has been found.
787 .arg(query->getLabel())
788 .arg(subnet->getID());
789 // Log detailed information about the selected subnet at the
790 // lower debug level.
792 .arg(query->getLabel())
793 .arg(subnet->toText());
794
795 } else {
798 .arg(query->getLabel());
799 }
800
801 return (subnet);
802}
803
805Dhcpv4Srv::selectSubnet4o6(const Pkt4Ptr& query, bool& drop,
806 bool sanity_only) const {
807
808 Subnet4Ptr subnet;
809
810 SubnetSelector selector;
811 selector.ciaddr_ = query->getCiaddr();
812 selector.giaddr_ = query->getGiaddr();
813 selector.local_address_ = query->getLocalAddr();
814 selector.client_classes_ = query->classes_;
815 selector.iface_name_ = query->getIface();
816 // Mark it as DHCPv4-over-DHCPv6
817 selector.dhcp4o6_ = true;
818 // Now the DHCPv6 part
819 selector.remote_address_ = query->getRemoteAddr();
820 selector.first_relay_linkaddr_ = IOAddress("::");
821
822 // Handle a DHCPv6 relayed query
823 Pkt4o6Ptr query4o6 = boost::dynamic_pointer_cast<Pkt4o6>(query);
824 if (!query4o6) {
825 isc_throw(Unexpected, "Can't get DHCP4o6 message");
826 }
827 const Pkt6Ptr& query6 = query4o6->getPkt6();
828
829 // Initialize fields specific to relayed messages.
830 if (query6 && !query6->relay_info_.empty()) {
831 BOOST_REVERSE_FOREACH(Pkt6::RelayInfo relay, query6->relay_info_) {
832 if (!relay.linkaddr_.isV6Zero() &&
833 !relay.linkaddr_.isV6LinkLocal()) {
834 selector.first_relay_linkaddr_ = relay.linkaddr_;
835 break;
836 }
837 }
838 selector.interface_id_ =
839 query6->getAnyRelayOption(D6O_INTERFACE_ID,
841 }
842
843 // If the Subnet Selection option is present, extract its value.
844 OptionPtr sbnsel = query->getOption(DHO_SUBNET_SELECTION);
845 if (sbnsel) {
846 OptionCustomPtr oc = boost::dynamic_pointer_cast<OptionCustom>(sbnsel);
847 if (oc) {
848 selector.option_select_ = oc->readAddress();
849 }
850 }
851
852 CfgMgr& cfgmgr = CfgMgr::instance();
853 subnet = cfgmgr.getCurrentCfg()->getCfgSubnets4()->selectSubnet4o6(selector);
854
855 // Let's execute all callouts registered for subnet4_select.
856 // (skip callouts if the selectSubnet was called to do sanity checks only)
857 if (!sanity_only &&
858 HooksManager::calloutsPresent(Hooks.hook_index_subnet4_select_)) {
859 CalloutHandlePtr callout_handle = getCalloutHandle(query);
860
861 // Use the RAII wrapper to make sure that the callout handle state is
862 // reset when this object goes out of scope. All hook points must do
863 // it to prevent possible circular dependency between the callout
864 // handle and its arguments.
865 ScopedCalloutHandleState callout_handle_state(callout_handle);
866
867 // Set new arguments
868 callout_handle->setArgument("query4", query);
869 callout_handle->setArgument("subnet4", subnet);
870 callout_handle->setArgument("subnet4collection",
871 cfgmgr.getCurrentCfg()->
872 getCfgSubnets4()->getAll());
873
874 // Call user (and server-side) callouts
875 HooksManager::callCallouts(Hooks.hook_index_subnet4_select_,
876 *callout_handle);
877
878 // Callouts decided to skip this step. This means that no subnet
879 // will be selected. Packet processing will continue, but it will
880 // be severely limited (i.e. only global options will be assigned)
881 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
884 .arg(query->getLabel());
885 return (Subnet4Ptr());
886 }
887
888 // Callouts decided to drop the packet. It is a superset of the
889 // skip case so no subnet will be selected.
890 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP) {
893 .arg(query->getLabel());
894 drop = true;
895 return (Subnet4Ptr());
896 }
897
898 // Use whatever subnet was specified by the callout
899 callout_handle->getArgument("subnet4", subnet);
900 }
901
902 if (subnet) {
903 // Log at higher debug level that subnet has been found.
905 .arg(query->getLabel())
906 .arg(subnet->getID());
907 // Log detailed information about the selected subnet at the
908 // lower debug level.
910 .arg(query->getLabel())
911 .arg(subnet->toText());
912
913 } else {
916 .arg(query->getLabel());
917 }
918
919 return (subnet);
920}
921
924 return (IfaceMgr::instance().receive4(timeout));
925}
926
927void
929 IfaceMgr::instance().send(packet);
930}
931
932int
934#ifdef ENABLE_AFL
935 // Set up structures needed for fuzzing.
936 Fuzz fuzzer(4, server_port_);
937 //
938 // The next line is needed as a signature for AFL to recognize that we are
939 // running persistent fuzzing. This has to be in the main image file.
940 while (__AFL_LOOP(fuzzer.maxLoopCount())) {
941 // Read from stdin and put the data read into an address/port on which
942 // Kea is listening, read for Kea to read it via asynchronous I/O.
943 fuzzer.transfer();
944#else
945 while (!shutdown_) {
946#endif // ENABLE_AFL
947 try {
948 run_one();
949 getIOService()->poll();
950 } catch (const std::exception& e) {
951 // General catch-all exception that are not caught by more specific
952 // catches. This one is for exceptions derived from std::exception.
954 .arg(e.what());
955 } catch (...) {
956 // General catch-all exception that are not caught by more specific
957 // catches. This one is for other exceptions, not derived from
958 // std::exception.
960 }
961 }
962
963 // Stop everything before we change into single-threaded mode.
965
966 // destroying the thread pool
967 MultiThreadingMgr::instance().apply(false, 0, 0);
968
969 return (getExitValue());
970}
971
972void
974 // client's message and server's response
975 Pkt4Ptr query;
976
977 try {
978 // Set select() timeout to 1s. This value should not be modified
979 // because it is important that the select() returns control
980 // frequently so as the IOService can be polled for ready handlers.
981 uint32_t timeout = 1;
982 query = receivePacket(timeout);
983
984 // Log if packet has arrived. We can't log the detailed information
985 // about the DHCP message because it hasn't been unpacked/parsed
986 // yet, and it can't be parsed at this point because hooks will
987 // have to process it first. The only information available at this
988 // point are: the interface, source address and destination addresses
989 // and ports.
990 if (query) {
992 .arg(query->getRemoteAddr().toText())
993 .arg(query->getRemotePort())
994 .arg(query->getLocalAddr().toText())
995 .arg(query->getLocalPort())
996 .arg(query->getIface());
997 }
998
999 // We used to log that the wait was interrupted, but this is no longer
1000 // the case. Our wait time is 1s now, so the lack of query packet more
1001 // likely means that nothing new appeared within a second, rather than
1002 // we were interrupted. And we don't want to print a message every
1003 // second.
1004
1005 } catch (const SignalInterruptOnSelect&) {
1006 // Packet reception interrupted because a signal has been received.
1007 // This is not an error because we might have received a SIGTERM,
1008 // SIGINT, SIGHUP or SIGCHLD which are handled by the server. For
1009 // signals that are not handled by the server we rely on the default
1010 // behavior of the system.
1012 } catch (const std::exception& e) {
1013 // Log all other errors.
1015 }
1016
1017 // Timeout may be reached or signal received, which breaks select()
1018 // with no reception occurred. No need to log anything here because
1019 // we have logged right after the call to receivePacket().
1020 if (!query) {
1021 return;
1022 }
1023
1024 // If the DHCP service has been globally disabled, drop the packet.
1025 if (!network_state_->isServiceEnabled()) {
1027 .arg(query->getLabel());
1028 return;
1029 } else {
1030 if (MultiThreadingMgr::instance().getMode()) {
1031 typedef function<void()> CallBack;
1032 boost::shared_ptr<CallBack> call_back =
1033 boost::make_shared<CallBack>(std::bind(&Dhcpv4Srv::processPacketAndSendResponseNoThrow,
1034 this, query));
1035 if (!MultiThreadingMgr::instance().getThreadPool().add(call_back)) {
1037 }
1038 } else {
1040 }
1041 }
1042}
1043
1044void
1046 try {
1048 } catch (const std::exception& e) {
1050 .arg(e.what());
1051 } catch (...) {
1053 }
1054}
1055
1056void
1058 Pkt4Ptr rsp;
1059 processPacket(query, rsp);
1060 if (!rsp) {
1061 return;
1062 }
1063
1064 CalloutHandlePtr callout_handle = getCalloutHandle(query);
1065 processPacketBufferSend(callout_handle, rsp);
1066}
1067
1068void
1069Dhcpv4Srv::processPacket(Pkt4Ptr& query, Pkt4Ptr& rsp, bool allow_packet_park) {
1070 // Log reception of the packet. We need to increase it early, as any
1071 // failures in unpacking will cause the packet to be dropped. We
1072 // will increase type specific statistic further down the road.
1073 // See processStatsReceived().
1074 isc::stats::StatsMgr::instance().addValue("pkt4-received",
1075 static_cast<int64_t>(1));
1076
1077 bool skip_unpack = false;
1078
1079 // The packet has just been received so contains the uninterpreted wire
1080 // data; execute callouts registered for buffer4_receive.
1081 if (HooksManager::calloutsPresent(Hooks.hook_index_buffer4_receive_)) {
1082 CalloutHandlePtr callout_handle = getCalloutHandle(query);
1083
1084 // Use the RAII wrapper to make sure that the callout handle state is
1085 // reset when this object goes out of scope. All hook points must do
1086 // it to prevent possible circular dependency between the callout
1087 // handle and its arguments.
1088 ScopedCalloutHandleState callout_handle_state(callout_handle);
1089
1090 // Enable copying options from the packet within hook library.
1091 ScopedEnableOptionsCopy<Pkt4> query4_options_copy(query);
1092
1093 // Pass incoming packet as argument
1094 callout_handle->setArgument("query4", query);
1095
1096 // Call callouts
1097 HooksManager::callCallouts(Hooks.hook_index_buffer4_receive_,
1098 *callout_handle);
1099
1100 // Callouts decided to drop the received packet.
1101 // The response (rsp) is null so the caller (run_one) will
1102 // immediately return too.
1103 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP) {
1106 .arg(query->getRemoteAddr().toText())
1107 .arg(query->getLocalAddr().toText())
1108 .arg(query->getIface());
1109 return;
1110 }
1111
1112 // Callouts decided to skip the next processing step. The next
1113 // processing step would to parse the packet, so skip at this
1114 // stage means that callouts did the parsing already, so server
1115 // should skip parsing.
1116 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
1119 .arg(query->getRemoteAddr().toText())
1120 .arg(query->getLocalAddr().toText())
1121 .arg(query->getIface());
1122 skip_unpack = true;
1123 }
1124
1125 callout_handle->getArgument("query4", query);
1126 }
1127
1128 // Unpack the packet information unless the buffer4_receive callouts
1129 // indicated they did it
1130 if (!skip_unpack) {
1131 try {
1133 .arg(query->getRemoteAddr().toText())
1134 .arg(query->getLocalAddr().toText())
1135 .arg(query->getIface());
1136 query->unpack();
1137 } catch (const SkipRemainingOptionsError& e) {
1138 // An option failed to unpack but we are to attempt to process it
1139 // anyway. Log it and let's hope for the best.
1142 .arg(e.what());
1143 } catch (const std::exception& e) {
1144 // Failed to parse the packet.
1146 .arg(query->getRemoteAddr().toText())
1147 .arg(query->getLocalAddr().toText())
1148 .arg(query->getIface())
1149 .arg(e.what());
1150
1151 // Increase the statistics of parse failures and dropped packets.
1152 isc::stats::StatsMgr::instance().addValue("pkt4-parse-failed",
1153 static_cast<int64_t>(1));
1154 isc::stats::StatsMgr::instance().addValue("pkt4-receive-drop",
1155 static_cast<int64_t>(1));
1156 return;
1157 }
1158 }
1159
1160 // Update statistics accordingly for received packet.
1161 processStatsReceived(query);
1162
1163 // Assign this packet to one or more classes if needed. We need to do
1164 // this before calling accept(), because getSubnet4() may need client
1165 // class information.
1166 classifyPacket(query);
1167
1168 // Now it is classified the deferred unpacking can be done.
1169 deferredUnpack(query);
1170
1171 // Check whether the message should be further processed or discarded.
1172 // There is no need to log anything here. This function logs by itself.
1173 if (!accept(query)) {
1174 // Increase the statistic of dropped packets.
1175 isc::stats::StatsMgr::instance().addValue("pkt4-receive-drop",
1176 static_cast<int64_t>(1));
1177 return;
1178 }
1179
1180 // We have sanity checked (in accept() that the Message Type option
1181 // exists, so we can safely get it here.
1182 int type = query->getType();
1184 .arg(query->getLabel())
1185 .arg(query->getName())
1186 .arg(type)
1187 .arg(query->getRemoteAddr())
1188 .arg(query->getLocalAddr())
1189 .arg(query->getIface());
1191 .arg(query->getLabel())
1192 .arg(query->toText());
1193
1194 // Let's execute all callouts registered for pkt4_receive
1195 if (HooksManager::calloutsPresent(Hooks.hook_index_pkt4_receive_)) {
1196 CalloutHandlePtr callout_handle = getCalloutHandle(query);
1197
1198 // Use the RAII wrapper to make sure that the callout handle state is
1199 // reset when this object goes out of scope. All hook points must do
1200 // it to prevent possible circular dependency between the callout
1201 // handle and its arguments.
1202 ScopedCalloutHandleState callout_handle_state(callout_handle);
1203
1204 // Enable copying options from the packet within hook library.
1205 ScopedEnableOptionsCopy<Pkt4> query4_options_copy(query);
1206
1207 // Pass incoming packet as argument
1208 callout_handle->setArgument("query4", query);
1209
1210 // Call callouts
1211 HooksManager::callCallouts(Hooks.hook_index_pkt4_receive_,
1212 *callout_handle);
1213
1214 // Callouts decided to skip the next processing step. The next
1215 // processing step would to process the packet, so skip at this
1216 // stage means drop.
1217 if ((callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) ||
1218 (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP)) {
1221 .arg(query->getLabel());
1222 return;
1223 }
1224
1225 callout_handle->getArgument("query4", query);
1226 }
1227
1228 // Check the DROP special class.
1229 if (query->inClass("DROP")) {
1231 .arg(query->toText());
1232 isc::stats::StatsMgr::instance().addValue("pkt4-receive-drop",
1233 static_cast<int64_t>(1));
1234 return;
1235 }
1236
1237 processDhcp4Query(query, rsp, allow_packet_park);
1238}
1239
1240void
1242 bool allow_packet_park) {
1243 try {
1244 processDhcp4Query(query, rsp, allow_packet_park);
1245 if (!rsp) {
1246 return;
1247 }
1248
1249 CalloutHandlePtr callout_handle = getCalloutHandle(query);
1250 processPacketBufferSend(callout_handle, rsp);
1251 } catch (const std::exception& e) {
1253 .arg(e.what());
1254 } catch (...) {
1256 }
1257}
1258
1259void
1261 bool allow_packet_park) {
1262 // Create a client race avoidance RAII handler.
1263 ClientHandler client_handler;
1264
1265 // Check for lease modifier queries from the same client being processed.
1266 if (MultiThreadingMgr::instance().getMode() &&
1267 ((query->getType() == DHCPDISCOVER) ||
1268 (query->getType() == DHCPREQUEST) ||
1269 (query->getType() == DHCPRELEASE) ||
1270 (query->getType() == DHCPDECLINE))) {
1271 ContinuationPtr cont =
1273 this, query, rsp, allow_packet_park));
1274 if (!client_handler.tryLock(query, cont)) {
1275 return;
1276 }
1277 }
1278
1280
1281 try {
1282 switch (query->getType()) {
1283 case DHCPDISCOVER:
1284 rsp = processDiscover(query);
1285 break;
1286
1287 case DHCPREQUEST:
1288 // Note that REQUEST is used for many things in DHCPv4: for
1289 // requesting new leases, renewing existing ones and even
1290 // for rebinding.
1291 rsp = processRequest(query, ctx);
1292 break;
1293
1294 case DHCPRELEASE:
1295 processRelease(query, ctx);
1296 break;
1297
1298 case DHCPDECLINE:
1299 processDecline(query, ctx);
1300 break;
1301
1302 case DHCPINFORM:
1303 rsp = processInform(query);
1304 break;
1305
1306 default:
1307 // Only action is to output a message if debug is enabled,
1308 // and that is covered by the debug statement before the
1309 // "switch" statement.
1310 ;
1311 }
1312 } catch (const std::exception& e) {
1313
1314 // Catch-all exception (we used to call only isc::Exception, but
1315 // std::exception could potentially be raised and if we don't catch
1316 // it here, it would be caught in main() and the process would
1317 // terminate). Just log the problem and ignore the packet.
1318 // (The problem is logged as a debug message because debug is
1319 // disabled by default - it prevents a DDOS attack based on the
1320 // sending of problem packets.)
1322 .arg(query->getLabel())
1323 .arg(e.what());
1324
1325 // Increase the statistic of dropped packets.
1326 isc::stats::StatsMgr::instance().addValue("pkt4-receive-drop",
1327 static_cast<int64_t>(1));
1328 }
1329
1330 CalloutHandlePtr callout_handle = getCalloutHandle(query);
1331 if (ctx && HooksManager::calloutsPresent(Hooks.hook_index_leases4_committed_)) {
1332 // Use the RAII wrapper to make sure that the callout handle state is
1333 // reset when this object goes out of scope. All hook points must do
1334 // it to prevent possible circular dependency between the callout
1335 // handle and its arguments.
1336 ScopedCalloutHandleState callout_handle_state(callout_handle);
1337
1338 ScopedEnableOptionsCopy<Pkt4> query4_options_copy(query);
1339
1340 // Also pass the corresponding query packet as argument
1341 callout_handle->setArgument("query4", query);
1342
1343 Lease4CollectionPtr new_leases(new Lease4Collection());
1344 // Filter out the new lease if it was reused so not committed.
1345 if (ctx->new_lease_ && (ctx->new_lease_->reuseable_valid_lft_ == 0)) {
1346 new_leases->push_back(ctx->new_lease_);
1347 }
1348 callout_handle->setArgument("leases4", new_leases);
1349
1350 Lease4CollectionPtr deleted_leases(new Lease4Collection());
1351 if (ctx->old_lease_) {
1352 if ((!ctx->new_lease_) || (ctx->new_lease_->addr_ != ctx->old_lease_->addr_)) {
1353 deleted_leases->push_back(ctx->old_lease_);
1354 }
1355 }
1356 callout_handle->setArgument("deleted_leases4", deleted_leases);
1357
1358 if (allow_packet_park) {
1359 // We proactively park the packet. We'll unpark it without invoking
1360 // the callback (i.e. drop) unless the callout status is set to
1361 // NEXT_STEP_PARK. Otherwise the callback we bind here will be
1362 // executed when the hook library unparks the packet.
1363 HooksManager::park("leases4_committed", query,
1364 [this, callout_handle, query, rsp]() mutable {
1365 if (MultiThreadingMgr::instance().getMode()) {
1366 typedef function<void()> CallBack;
1367 boost::shared_ptr<CallBack> call_back =
1368 boost::make_shared<CallBack>(std::bind(&Dhcpv4Srv::sendResponseNoThrow,
1369 this, callout_handle, query, rsp));
1370 MultiThreadingMgr::instance().getThreadPool().add(call_back);
1371 } else {
1372 processPacketPktSend(callout_handle, query, rsp);
1373 processPacketBufferSend(callout_handle, rsp);
1374 }
1375 });
1376 }
1377
1378 try {
1379 // Call all installed callouts
1380 HooksManager::callCallouts(Hooks.hook_index_leases4_committed_,
1381 *callout_handle);
1382 } catch (...) {
1383 // Make sure we don't orphan a parked packet.
1384 if (allow_packet_park) {
1385 HooksManager::drop("leases4_committed", query);
1386 }
1387
1388 throw;
1389 }
1390
1391 if ((callout_handle->getStatus() == CalloutHandle::NEXT_STEP_PARK)
1392 && allow_packet_park) {
1394 .arg(query->getLabel());
1395 // Since the hook library(ies) are going to do the unparking, then
1396 // reset the pointer to the response to indicate to the caller that
1397 // it should return, as the packet processing will continue via
1398 // the callback.
1399 rsp.reset();
1400 } else {
1401 // Drop the park job on the packet, it isn't needed.
1402 HooksManager::drop("leases4_committed", query);
1403 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP) {
1405 .arg(query->getLabel());
1406 rsp.reset();
1407 }
1408 }
1409 }
1410
1411 // If we have a response prep it for shipment.
1412 if (rsp) {
1413 processPacketPktSend(callout_handle, query, rsp);
1414 }
1415}
1416
1417void
1419 Pkt4Ptr& query, Pkt4Ptr& rsp) {
1420 try {
1421 processPacketPktSend(callout_handle, query, rsp);
1422 processPacketBufferSend(callout_handle, rsp);
1423 } catch (const std::exception& e) {
1425 .arg(e.what());
1426 } catch (...) {
1428 }
1429}
1430
1431void
1433 Pkt4Ptr& query, Pkt4Ptr& rsp) {
1434 if (!rsp) {
1435 return;
1436 }
1437
1438 // Specifies if server should do the packing
1439 bool skip_pack = false;
1440
1441 // Execute all callouts registered for pkt4_send
1442 if (HooksManager::calloutsPresent(Hooks.hook_index_pkt4_send_)) {
1443
1444 // Use the RAII wrapper to make sure that the callout handle state is
1445 // reset when this object goes out of scope. All hook points must do
1446 // it to prevent possible circular dependency between the callout
1447 // handle and its arguments.
1448 ScopedCalloutHandleState callout_handle_state(callout_handle);
1449
1450 // Enable copying options from the query and response packets within
1451 // hook library.
1452 ScopedEnableOptionsCopy<Pkt4> query_resp_options_copy(query, rsp);
1453
1454 // Pass incoming packet as argument
1455 callout_handle->setArgument("query4", query);
1456
1457 // Set our response
1458 callout_handle->setArgument("response4", rsp);
1459
1460 // Call all installed callouts
1461 HooksManager::callCallouts(Hooks.hook_index_pkt4_send_,
1462 *callout_handle);
1463
1464 // Callouts decided to skip the next processing step. The next
1465 // processing step would to pack the packet (create wire data).
1466 // That step will be skipped if any callout sets skip flag.
1467 // It essentially means that the callout already did packing,
1468 // so the server does not have to do it again.
1469 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
1471 .arg(query->getLabel());
1472 skip_pack = true;
1473 }
1474
1476 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP) {
1478 .arg(rsp->getLabel());
1479 rsp.reset();
1480 return;
1481 }
1482 }
1483
1484 if (!skip_pack) {
1485 try {
1487 .arg(rsp->getLabel());
1488 rsp->pack();
1489 } catch (const std::exception& e) {
1491 .arg(rsp->getLabel())
1492 .arg(e.what());
1493 }
1494 }
1495}
1496
1497void
1499 Pkt4Ptr& rsp) {
1500 if (!rsp) {
1501 return;
1502 }
1503
1504 try {
1505 // Now all fields and options are constructed into output wire buffer.
1506 // Option objects modification does not make sense anymore. Hooks
1507 // can only manipulate wire buffer at this stage.
1508 // Let's execute all callouts registered for buffer4_send
1509 if (HooksManager::calloutsPresent(Hooks.hook_index_buffer4_send_)) {
1510
1511 // Use the RAII wrapper to make sure that the callout handle state is
1512 // reset when this object goes out of scope. All hook points must do
1513 // it to prevent possible circular dependency between the callout
1514 // handle and its arguments.
1515 ScopedCalloutHandleState callout_handle_state(callout_handle);
1516
1517 // Enable copying options from the packet within hook library.
1518 ScopedEnableOptionsCopy<Pkt4> resp4_options_copy(rsp);
1519
1520 // Pass incoming packet as argument
1521 callout_handle->setArgument("response4", rsp);
1522
1523 // Call callouts
1524 HooksManager::callCallouts(Hooks.hook_index_buffer4_send_,
1525 *callout_handle);
1526
1527 // Callouts decided to skip the next processing step. The next
1528 // processing step would to parse the packet, so skip at this
1529 // stage means drop.
1530 if ((callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) ||
1531 (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP)) {
1534 .arg(rsp->getLabel());
1535 return;
1536 }
1537
1538 callout_handle->getArgument("response4", rsp);
1539 }
1540
1542 .arg(rsp->getLabel())
1543 .arg(rsp->getName())
1544 .arg(static_cast<int>(rsp->getType()))
1545 .arg(rsp->getLocalAddr().isV4Zero() ? "*" : rsp->getLocalAddr().toText())
1546 .arg(rsp->getLocalPort())
1547 .arg(rsp->getRemoteAddr())
1548 .arg(rsp->getRemotePort())
1549 .arg(rsp->getIface().empty() ? "to be determined from routing" :
1550 rsp->getIface());
1551
1554 .arg(rsp->getLabel())
1555 .arg(rsp->getName())
1556 .arg(static_cast<int>(rsp->getType()))
1557 .arg(rsp->toText());
1558 sendPacket(rsp);
1559
1560 // Update statistics accordingly for sent packet.
1561 processStatsSent(rsp);
1562
1563 } catch (const std::exception& e) {
1565 .arg(rsp->getLabel())
1566 .arg(e.what());
1567 }
1568}
1569
1570string
1572 if (!srvid) {
1573 isc_throw(BadValue, "NULL pointer passed to srvidToString()");
1574 }
1575 boost::shared_ptr<Option4AddrLst> generated =
1576 boost::dynamic_pointer_cast<Option4AddrLst>(srvid);
1577 if (!srvid) {
1578 isc_throw(BadValue, "Pointer to invalid option passed to srvidToString()");
1579 }
1580
1581 Option4AddrLst::AddressContainer addrs = generated->getAddresses();
1582 if (addrs.size() != 1) {
1583 isc_throw(BadValue, "Malformed option passed to srvidToString(). "
1584 << "Expected to contain a single IPv4 address.");
1585 }
1586
1587 return (addrs[0].toText());
1588}
1589
1590void
1592
1593 // Do not append generated server identifier if there is one appended already.
1594 // This is when explicitly configured server identifier option is present.
1595 if (ex.getResponse()->getOption(DHO_DHCP_SERVER_IDENTIFIER)) {
1596 return;
1597 }
1598
1599 // Use local address on which the packet has been received as a
1600 // server identifier. In some cases it may be a different address,
1601 // e.g. broadcast packet or DHCPv4o6 packet.
1602 IOAddress local_addr = ex.getQuery()->getLocalAddr();
1603 Pkt4Ptr query = ex.getQuery();
1604
1605 if (local_addr.isV4Bcast() || query->isDhcp4o6()) {
1606 local_addr = IfaceMgr::instance().getSocket(query).addr_;
1607 }
1608
1610 local_addr));
1611 ex.getResponse()->addOption(opt_srvid);
1612}
1613
1614void
1616 CfgOptionList& co_list = ex.getCfgOptionList();
1617
1618 // Retrieve subnet.
1619 Subnet4Ptr subnet = ex.getContext()->subnet_;
1620 if (!subnet) {
1621 // All methods using the CfgOptionList object return soon when
1622 // there is no subnet so do the same
1623 return;
1624 }
1625
1626 // Firstly, host specific options.
1627 const ConstHostPtr& host = ex.getContext()->currentHost();
1628 if (host && !host->getCfgOption4()->empty()) {
1629 co_list.push_back(host->getCfgOption4());
1630 }
1631
1632 // Secondly, pool specific options.
1633 Pkt4Ptr resp = ex.getResponse();
1635 if (resp) {
1636 addr = resp->getYiaddr();
1637 }
1638 if (!addr.isV4Zero()) {
1639 PoolPtr pool = subnet->getPool(Lease::TYPE_V4, addr, false);
1640 if (pool && !pool->getCfgOption()->empty()) {
1641 co_list.push_back(pool->getCfgOption());
1642 }
1643 }
1644
1645 // Thirdly, subnet configured options.
1646 if (!subnet->getCfgOption()->empty()) {
1647 co_list.push_back(subnet->getCfgOption());
1648 }
1649
1650 // Fourthly, shared network specific options.
1651 SharedNetwork4Ptr network;
1652 subnet->getSharedNetwork(network);
1653 if (network && !network->getCfgOption()->empty()) {
1654 co_list.push_back(network->getCfgOption());
1655 }
1656
1657 // Each class in the incoming packet
1658 const ClientClasses& classes = ex.getQuery()->getClasses();
1659 for (ClientClasses::const_iterator cclass = classes.cbegin();
1660 cclass != classes.cend(); ++cclass) {
1661 // Find the client class definition for this class
1663 getClientClassDictionary()->findClass(*cclass);
1664 if (!ccdef) {
1665 // Not found: the class is built-in or not configured
1666 if (!isClientClassBuiltIn(*cclass)) {
1668 .arg(ex.getQuery()->getLabel())
1669 .arg(*cclass);
1670 }
1671 // Skip it
1672 continue;
1673 }
1674
1675 if (ccdef->getCfgOption()->empty()) {
1676 // Skip classes which don't configure options
1677 continue;
1678 }
1679
1680 co_list.push_back(ccdef->getCfgOption());
1681 }
1682
1683 // Last global options
1684 if (!CfgMgr::instance().getCurrentCfg()->getCfgOption()->empty()) {
1685 co_list.push_back(CfgMgr::instance().getCurrentCfg()->getCfgOption());
1686 }
1687}
1688
1689void
1691 // Get the subnet relevant for the client. We will need it
1692 // to get the options associated with it.
1693 Subnet4Ptr subnet = ex.getContext()->subnet_;
1694 // If we can't find the subnet for the client there is no way
1695 // to get the options to be sent to a client. We don't log an
1696 // error because it will be logged by the assignLease method
1697 // anyway.
1698 if (!subnet) {
1699 return;
1700 }
1701
1702 // Unlikely short cut
1703 const CfgOptionList& co_list = ex.getCfgOptionList();
1704 if (co_list.empty()) {
1705 return;
1706 }
1707
1708 Pkt4Ptr query = ex.getQuery();
1709 Pkt4Ptr resp = ex.getResponse();
1710 std::vector<uint8_t> requested_opts;
1711
1712 // try to get the 'Parameter Request List' option which holds the
1713 // codes of requested options.
1714 OptionUint8ArrayPtr option_prl = boost::dynamic_pointer_cast<
1716 // Get the codes of requested options.
1717 if (option_prl) {
1718 requested_opts = option_prl->getValues();
1719 }
1720 // Iterate on the configured option list to add persistent options
1721 for (CfgOptionList::const_iterator copts = co_list.begin();
1722 copts != co_list.end(); ++copts) {
1723 const OptionContainerPtr& opts = (*copts)->getAll(DHCP4_OPTION_SPACE);
1724 if (!opts) {
1725 continue;
1726 }
1727 // Get persistent options
1728 const OptionContainerPersistIndex& idx = opts->get<2>();
1729 const OptionContainerPersistRange& range = idx.equal_range(true);
1730 for (OptionContainerPersistIndex::const_iterator desc = range.first;
1731 desc != range.second; ++desc) {
1732 // Add the persistent option code to requested options
1733 if (desc->option_) {
1734 uint8_t code = static_cast<uint8_t>(desc->option_->getType());
1735 requested_opts.push_back(code);
1736 }
1737 }
1738 }
1739
1740 // For each requested option code get the instance of the option
1741 // to be returned to the client.
1742 for (std::vector<uint8_t>::const_iterator opt = requested_opts.begin();
1743 opt != requested_opts.end(); ++opt) {
1744 // Add nothing when it is already there
1745 if (!resp->getOption(*opt)) {
1746 // Iterate on the configured option list
1747 for (CfgOptionList::const_iterator copts = co_list.begin();
1748 copts != co_list.end(); ++copts) {
1749 OptionDescriptor desc = (*copts)->get(DHCP4_OPTION_SPACE, *opt);
1750 // Got it: add it and jump to the outer loop
1751 if (desc.option_) {
1752 resp->addOption(desc.option_);
1753 break;
1754 }
1755 }
1756 }
1757 }
1758}
1759
1760void
1762 // Get the configured subnet suitable for the incoming packet.
1763 Subnet4Ptr subnet = ex.getContext()->subnet_;
1764 // Leave if there is no subnet matching the incoming packet.
1765 // There is no need to log the error message here because
1766 // it will be logged in the assignLease() when it fails to
1767 // pick the suitable subnet. We don't want to duplicate
1768 // error messages in such case.
1769 if (!subnet) {
1770 return;
1771 }
1772
1773 // Unlikely short cut
1774 const CfgOptionList& co_list = ex.getCfgOptionList();
1775 if (co_list.empty()) {
1776 return;
1777 }
1778
1779 uint32_t vendor_id = 0;
1780
1781 // Try to get the vendor option from the client packet. This is how it's
1782 // supposed to be done. Client sends vivso, we look at the vendor-id and
1783 // then send back the vendor options specific to that client.
1784 boost::shared_ptr<OptionVendor> vendor_req = boost::dynamic_pointer_cast<
1785 OptionVendor>(ex.getQuery()->getOption(DHO_VIVSO_SUBOPTIONS));
1786 if (vendor_req) {
1787 vendor_id = vendor_req->getVendorId();
1788 }
1789
1790 // Something is fishy. Client was supposed to send vivso, but didn't.
1791 // Let's try an alternative. It's possible that the server already
1792 // inserted vivso in the response message, (e.g. by using client
1793 // classification or perhaps a hook inserted it).
1794 boost::shared_ptr<OptionVendor> vendor_rsp = boost::dynamic_pointer_cast<
1796 if (vendor_rsp) {
1797 vendor_id = vendor_rsp->getVendorId();
1798 }
1799
1800 if (!vendor_req && !vendor_rsp) {
1801 // Ok, we're out of luck today. Neither client nor server packets
1802 // have vivso. There is no way to figure out vendor-id here.
1803 // We give up.
1804 return;
1805 }
1806
1807 std::vector<uint8_t> requested_opts;
1808
1809 // Let's try to get ORO within that vendor-option.
1810 // This is specific to vendor-id=4491 (Cable Labs). Other vendors may have
1811 // different policies.
1813 if (vendor_id == VENDOR_ID_CABLE_LABS && vendor_req) {
1814 OptionPtr oro_generic = vendor_req->getOption(DOCSIS3_V4_ORO);
1815 if (oro_generic) {
1816 // Vendor ID 4491 makes Kea look at DOCSIS3_V4_OPTION_DEFINITIONS
1817 // when parsing options. Based on that, oro_generic will have been
1818 // created as an OptionUint8Array, but might not be for other
1819 // vendor IDs.
1820 oro = boost::dynamic_pointer_cast<OptionUint8Array>(oro_generic);
1821 // Get the list of options that client requested.
1822 if (oro) {
1823 requested_opts = oro->getValues();
1824 }
1825 }
1826 }
1827
1828 // Iterate on the configured option list to add persistent options
1829 for (CfgOptionList::const_iterator copts = co_list.begin();
1830 copts != co_list.end(); ++copts) {
1831 const OptionContainerPtr& opts = (*copts)->getAll(vendor_id);
1832 if (!opts) {
1833 continue;
1834 }
1835
1836 // Get persistent options
1837 const OptionContainerPersistIndex& idx = opts->get<2>();
1838 const OptionContainerPersistRange& range = idx.equal_range(true);
1839 for (OptionContainerPersistIndex::const_iterator desc = range.first;
1840 desc != range.second; ++desc) {
1841 // Add the persistent option code to requested options
1842 if (desc->option_) {
1843 uint8_t code = static_cast<uint8_t>(desc->option_->getType());
1844 requested_opts.push_back(code);
1845 }
1846 }
1847 }
1848
1849 // If there is nothing to add don't do anything then.
1850 if (requested_opts.empty()) {
1851 return;
1852 }
1853
1854 if (!vendor_rsp) {
1855 // It's possible that vivso was inserted already by client class or
1856 // a hook. If that is so, let's use it.
1857 vendor_rsp.reset(new OptionVendor(Option::V4, vendor_id));
1858 }
1859
1860 // Get the list of options that client requested.
1861 bool added = false;
1862 for (std::vector<uint8_t>::const_iterator code = requested_opts.begin();
1863 code != requested_opts.end(); ++code) {
1864 if (!vendor_rsp->getOption(*code)) {
1865 for (CfgOptionList::const_iterator copts = co_list.begin();
1866 copts != co_list.end(); ++copts) {
1867 OptionDescriptor desc = (*copts)->get(vendor_id, *code);
1868 if (desc.option_) {
1869 vendor_rsp->addOption(desc.option_);
1870 added = true;
1871 break;
1872 }
1873 }
1874 }
1875 }
1876
1877 // If we added some sub-options and the vivso option is not in
1878 // the response already, then add it.
1879 if (added && !ex.getResponse()->getOption(DHO_VIVSO_SUBOPTIONS)) {
1880 ex.getResponse()->addOption(vendor_rsp);
1881 }
1882}
1883
1884void
1886 // Identify options that we always want to send to the
1887 // client (if they are configured).
1888 static const uint16_t required_options[] = {
1893
1894 static size_t required_options_size =
1895 sizeof(required_options) / sizeof(required_options[0]);
1896
1897 // Get the subnet.
1898 Subnet4Ptr subnet = ex.getContext()->subnet_;
1899 if (!subnet) {
1900 return;
1901 }
1902
1903 // Unlikely short cut
1904 const CfgOptionList& co_list = ex.getCfgOptionList();
1905 if (co_list.empty()) {
1906 return;
1907 }
1908
1909 Pkt4Ptr resp = ex.getResponse();
1910
1911 // Try to find all 'required' options in the outgoing
1912 // message. Those that are not present will be added.
1913 for (int i = 0; i < required_options_size; ++i) {
1914 OptionPtr opt = resp->getOption(required_options[i]);
1915 if (!opt) {
1916 // Check whether option has been configured.
1917 for (CfgOptionList::const_iterator copts = co_list.begin();
1918 copts != co_list.end(); ++copts) {
1919 OptionDescriptor desc = (*copts)->get(DHCP4_OPTION_SPACE,
1920 required_options[i]);
1921 if (desc.option_) {
1922 resp->addOption(desc.option_);
1923 break;
1924 }
1925 }
1926 }
1927 }
1928}
1929
1930void
1932 // It is possible that client has sent both Client FQDN and Hostname
1933 // option. In that the server should prefer Client FQDN option and
1934 // ignore the Hostname option.
1935 try {
1936 Pkt4Ptr resp = ex.getResponse();
1937 Option4ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<Option4ClientFqdn>
1938 (ex.getQuery()->getOption(DHO_FQDN));
1939 if (fqdn) {
1941 .arg(ex.getQuery()->getLabel());
1942 processClientFqdnOption(ex);
1943
1944 } else {
1947 .arg(ex.getQuery()->getLabel());
1948 processHostnameOption(ex);
1949 }
1950
1951 // Based on the output option added to the response above, we figure out
1952 // the values for the hostname and dns flags to set in the context. These
1953 // will be used to populate the lease.
1954 std::string hostname;
1955 bool fqdn_fwd = false;
1956 bool fqdn_rev = false;
1957 OptionStringPtr opt_hostname;
1958 fqdn = boost::dynamic_pointer_cast<Option4ClientFqdn>(resp->getOption(DHO_FQDN));
1959 if (fqdn) {
1960 hostname = fqdn->getDomainName();
1961 CfgMgr::instance().getD2ClientMgr().getUpdateDirections(*fqdn, fqdn_fwd, fqdn_rev);
1962 } else {
1963 opt_hostname = boost::dynamic_pointer_cast<OptionString>
1964 (resp->getOption(DHO_HOST_NAME));
1965
1966 if (opt_hostname) {
1967 hostname = opt_hostname->getValue();
1968 // DHO_HOST_NAME is string option which cannot be blank,
1969 // we use "." to know we should replace it with a fully
1970 // generated name. The local string variable needs to be
1971 // blank in logic below.
1972 if (hostname == ".") {
1973 hostname = "";
1974 }
1975
1978 if (ex.getContext()->getDdnsParams()->getEnableUpdates()) {
1979 fqdn_fwd = true;
1980 fqdn_rev = true;
1981 }
1982 }
1983 }
1984
1985 // Update the context
1986 auto ctx = ex.getContext();
1987 ctx->fwd_dns_update_ = fqdn_fwd;
1988 ctx->rev_dns_update_ = fqdn_rev;
1989 ctx->hostname_ = hostname;
1990
1991 } catch (const Exception& e) {
1992 // In some rare cases it is possible that the client's name processing
1993 // fails. For example, the Hostname option may be malformed, or there
1994 // may be an error in the server's logic which would cause multiple
1995 // attempts to add the same option to the response message. This
1996 // error message aggregates all these errors so they can be diagnosed
1997 // from the log. We don't want to throw an exception here because,
1998 // it will impact the processing of the whole packet. We rather want
1999 // the processing to continue, even if the client's name is wrong.
2001 .arg(ex.getQuery()->getLabel())
2002 .arg(e.what());
2003 }
2004
2005}
2006
2007void
2008Dhcpv4Srv::processClientFqdnOption(Dhcpv4Exchange& ex) {
2009 // Obtain the FQDN option from the client's message.
2010 Option4ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<
2011 Option4ClientFqdn>(ex.getQuery()->getOption(DHO_FQDN));
2012
2014 .arg(ex.getQuery()->getLabel())
2015 .arg(fqdn->toText());
2016
2017 // Create the DHCPv4 Client FQDN Option to be included in the server's
2018 // response to a client.
2019 Option4ClientFqdnPtr fqdn_resp(new Option4ClientFqdn(*fqdn));
2020
2021 // Set the server S, N, and O flags based on client's flags and
2022 // current configuration.
2024 d2_mgr.adjustFqdnFlags<Option4ClientFqdn>(*fqdn, *fqdn_resp,
2025 *(ex.getContext()->getDdnsParams()));
2026 // Carry over the client's E flag.
2029
2030 if (ex.getContext()->currentHost() &&
2031 !ex.getContext()->currentHost()->getHostname().empty()) {
2033 fqdn_resp->setDomainName(d2_mgr.qualifyName(ex.getContext()->currentHost()->getHostname(),
2034 *(ex.getContext()->getDdnsParams()), true),
2036
2037 } else {
2038 // Adjust the domain name based on domain name value and type sent by the
2039 // client and current configuration.
2040 d2_mgr.adjustDomainName<Option4ClientFqdn>(*fqdn, *fqdn_resp,
2041 *(ex.getContext()->getDdnsParams()));
2042 }
2043
2044 // Add FQDN option to the response message. Note that, there may be some
2045 // cases when server may choose not to include the FQDN option in a
2046 // response to a client. In such cases, the FQDN should be removed from the
2047 // outgoing message. In theory we could cease to include the FQDN option
2048 // in this function until it is confirmed that it should be included.
2049 // However, we include it here for simplicity. Functions used to acquire
2050 // lease for a client will scan the response message for FQDN and if it
2051 // is found they will take necessary actions to store the FQDN information
2052 // in the lease database as well as to generate NameChangeRequests to DNS.
2053 // If we don't store the option in the response message, we will have to
2054 // propagate it in the different way to the functions which acquire the
2055 // lease. This would require modifications to the API of this class.
2057 .arg(ex.getQuery()->getLabel())
2058 .arg(fqdn_resp->toText());
2059 ex.getResponse()->addOption(fqdn_resp);
2060}
2061
2062void
2063Dhcpv4Srv::processHostnameOption(Dhcpv4Exchange& ex) {
2064 // Fetch D2 configuration.
2066
2067 // Obtain the Hostname option from the client's message.
2068 OptionStringPtr opt_hostname = boost::dynamic_pointer_cast<OptionString>
2069 (ex.getQuery()->getOption(DHO_HOST_NAME));
2070
2071 if (opt_hostname) {
2073 .arg(ex.getQuery()->getLabel())
2074 .arg(opt_hostname->getValue());
2075 }
2076
2078
2079 // Hostname reservations take precedence over any other configuration,
2080 // i.e. DDNS configuration. If we have a reserved hostname we should
2081 // use it and send it back.
2082 if (ctx->currentHost() && !ctx->currentHost()->getHostname().empty()) {
2083 // Qualify if there is an a suffix configured.
2084 std::string hostname = d2_mgr.qualifyName(ctx->currentHost()->getHostname(),
2085 *(ex.getContext()->getDdnsParams()), false);
2086 // Convert it to lower case.
2087 boost::algorithm::to_lower(hostname);
2089 .arg(ex.getQuery()->getLabel())
2090 .arg(hostname);
2091
2092 // Add it to the response
2093 OptionStringPtr opt_hostname_resp(new OptionString(Option::V4, DHO_HOST_NAME, hostname));
2094 ex.getResponse()->addOption(opt_hostname_resp);
2095
2096 // We're done here.
2097 return;
2098 }
2099
2100 // There is no reservation for this client however there is still a
2101 // possibility that we'll have to send hostname option to this client
2102 // if the client has included hostname option or the configuration of
2103 // the server requires that we send the option regardless.
2104 D2ClientConfig::ReplaceClientNameMode replace_name_mode =
2105 ex.getContext()->getDdnsParams()->getReplaceClientNameMode();
2106
2107 // If we don't have a hostname then either we'll supply it or do nothing.
2108 if (!opt_hostname) {
2109 // If we're configured to supply it then add it to the response.
2110 // Use the root domain to signal later on that we should replace it.
2111 if (replace_name_mode == D2ClientConfig::RCM_ALWAYS ||
2112 replace_name_mode == D2ClientConfig::RCM_WHEN_NOT_PRESENT) {
2115 .arg(ex.getQuery()->getLabel());
2116 OptionStringPtr opt_hostname_resp(new OptionString(Option::V4,
2118 "."));
2119 ex.getResponse()->addOption(opt_hostname_resp);
2120 }
2121
2122 return;
2123 }
2124
2125 // Client sent us a hostname option so figure out what to do with it.
2127 .arg(ex.getQuery()->getLabel())
2128 .arg(opt_hostname->getValue());
2129
2130 std::string hostname = isc::util::str::trim(opt_hostname->getValue());
2131 unsigned int label_count;
2132
2133 try {
2134 // Parsing into labels can throw on malformed content so we're
2135 // going to explicitly catch that here.
2136 label_count = OptionDataTypeUtil::getLabelCount(hostname);
2137 } catch (const std::exception& exc) {
2139 .arg(ex.getQuery()->getLabel())
2140 .arg(exc.what());
2141 return;
2142 }
2143
2144 // The hostname option sent by the client should be at least 1 octet long.
2145 // If it isn't we ignore this option. (Per RFC 2131, section 3.14)
2148 if (label_count == 0) {
2150 .arg(ex.getQuery()->getLabel());
2151 return;
2152 }
2153
2154 // Stores the value we eventually use, so we can send it back.
2155 OptionStringPtr opt_hostname_resp;
2156
2157 // The hostname option may be unqualified or fully qualified. The lab_count
2158 // holds the number of labels for the name. The number of 1 means that
2159 // there is only root label "." (even for unqualified names, as the
2160 // getLabelCount function treats each name as a fully qualified one).
2161 // By checking the number of labels present in the hostname we may infer
2162 // whether client has sent the fully qualified or unqualified hostname.
2163
2164 if ((replace_name_mode == D2ClientConfig::RCM_ALWAYS ||
2165 replace_name_mode == D2ClientConfig::RCM_WHEN_PRESENT)
2166 || label_count < 2) {
2167 // Set to root domain to signal later on that we should replace it.
2168 // DHO_HOST_NAME is a string option which cannot be empty.
2176 opt_hostname_resp.reset(new OptionString(Option::V4, DHO_HOST_NAME, "."));
2177 } else {
2178 // Sanitize the name the client sent us, if we're configured to do so.
2180 ex.getContext()->getDdnsParams()->getHostnameSanitizer();
2181
2182 if (sanitizer) {
2183 hostname = sanitizer->scrub(hostname);
2184 }
2185
2186 // Convert hostname to lower case.
2187 boost::algorithm::to_lower(hostname);
2188
2189 if (label_count == 2) {
2190 // If there are two labels, it means that the client has specified
2191 // the unqualified name. We have to concatenate the unqualified name
2192 // with the domain name. The false value passed as a second argument
2193 // indicates that the trailing dot should not be appended to the
2194 // hostname. We don't want to append the trailing dot because
2195 // we don't know whether the hostname is partial or not and some
2196 // clients do not handle the hostnames with the trailing dot.
2197 opt_hostname_resp.reset(
2199 d2_mgr.qualifyName(hostname, *(ex.getContext()->getDdnsParams()),
2200 false)));
2201 } else {
2202 opt_hostname_resp.reset(new OptionString(Option::V4, DHO_HOST_NAME, hostname));
2203 }
2204 }
2205
2207 .arg(ex.getQuery()->getLabel())
2208 .arg(opt_hostname_resp->getValue());
2209 ex.getResponse()->addOption(opt_hostname_resp);
2210}
2211
2212void
2214 const Lease4Ptr& old_lease,
2215 const DdnsParams& ddns_params) {
2216 if (!lease) {
2218 "NULL lease specified when creating NameChangeRequest");
2219 }
2220
2221 // Nothing to do if updates are not enabled.
2222 if (!ddns_params.getEnableUpdates()) {
2223 return;
2224 }
2225
2226 if (!old_lease || ddns_params.getUpdateOnRenew() || !lease->hasIdenticalFqdn(*old_lease)) {
2227 if (old_lease) {
2228 // Queue's up a remove of the old lease's DNS (if needed)
2229 queueNCR(CHG_REMOVE, old_lease);
2230 }
2231
2232 // We may need to generate the NameChangeRequest for the new lease. It
2233 // will be generated only if hostname is set and if forward or reverse
2234 // update has been requested.
2235 queueNCR(CHG_ADD, lease);
2236 }
2237}
2238
2239void
2241 // Get the pointers to the query and the response messages.
2242 Pkt4Ptr query = ex.getQuery();
2243 Pkt4Ptr resp = ex.getResponse();
2244
2245 // Get the context.
2247
2248 // Subnet should have been already selected when the context was created.
2249 Subnet4Ptr subnet = ctx->subnet_;
2250 if (!subnet) {
2251 // This particular client is out of luck today. We do not have
2252 // information about the subnet he is connected to. This likely means
2253 // misconfiguration of the server (or some relays).
2254
2255 // Perhaps this should be logged on some higher level?
2257 .arg(query->getLabel())
2258 .arg(query->getRemoteAddr().toText())
2259 .arg(query->getName());
2260 resp->setType(DHCPNAK);
2261 resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
2262 return;
2263 }
2264
2265 // Get the server identifier. It will be used to determine the state
2266 // of the client.
2267 OptionCustomPtr opt_serverid = boost::dynamic_pointer_cast<
2268 OptionCustom>(query->getOption(DHO_DHCP_SERVER_IDENTIFIER));
2269
2270 // Check if the client has sent a requested IP address option or
2271 // ciaddr.
2272 OptionCustomPtr opt_requested_address = boost::dynamic_pointer_cast<
2273 OptionCustom>(query->getOption(DHO_DHCP_REQUESTED_ADDRESS));
2275 if (opt_requested_address) {
2276 hint = opt_requested_address->readAddress();
2277
2278 } else if (!query->getCiaddr().isV4Zero()) {
2279 hint = query->getCiaddr();
2280
2281 }
2282
2283 HWAddrPtr hwaddr = query->getHWAddr();
2284
2285 // "Fake" allocation is processing of DISCOVER message. We pretend to do an
2286 // allocation, but we do not put the lease in the database. That is ok,
2287 // because we do not guarantee that the user will get that exact lease. If
2288 // the user selects this server to do actual allocation (i.e. sends REQUEST)
2289 // it should include this hint. That will help us during the actual lease
2290 // allocation.
2291 bool fake_allocation = (query->getType() == DHCPDISCOVER);
2292
2293 // Get client-id. It is not mandatory in DHCPv4.
2294 ClientIdPtr client_id = ex.getContext()->clientid_;
2295
2296 // If there is no server id and there is a Requested IP Address option
2297 // the client is in the INIT-REBOOT state in which the server has to
2298 // determine whether the client's notion of the address is correct
2299 // and whether the client is known, i.e., has a lease.
2300 if (!fake_allocation && !opt_serverid && opt_requested_address) {
2301
2303 .arg(query->getLabel())
2304 .arg(hint.toText());
2305
2306 Lease4Ptr lease;
2307 Subnet4Ptr original_subnet = subnet;
2308
2309 // We used to issue a separate query (two actually: one for client-id
2310 // and another one for hw-addr for) each subnet in the shared network.
2311 // That was horribly inefficient if the client didn't have any lease
2312 // (or there were many subnets and the client happened to be in one
2313 // of the last subnets).
2314 //
2315 // We now issue at most two queries: get all the leases for specific
2316 // client-id and then get all leases for specific hw-address.
2317 if (client_id) {
2318
2319 // Get all the leases for this client-id
2320 Lease4Collection leases_client_id = LeaseMgrFactory::instance().getLease4(*client_id);
2321 if (!leases_client_id.empty()) {
2322 Subnet4Ptr s = original_subnet;
2323
2324 // Among those returned try to find a lease that belongs to
2325 // current shared network.
2326 while (s) {
2327 for (auto l = leases_client_id.begin(); l != leases_client_id.end(); ++l) {
2328 if ((*l)->subnet_id_ == s->getID()) {
2329 lease = *l;
2330 break;
2331 }
2332 }
2333
2334 if (lease) {
2335 break;
2336
2337 } else {
2338 s = s->getNextSubnet(original_subnet, query->getClasses());
2339 }
2340 }
2341 }
2342 }
2343
2344 // If we haven't found a lease yet, try again by hardware-address.
2345 // The logic is the same.
2346 if (!lease && hwaddr) {
2347
2348 // Get all leases for this particular hw-address.
2349 Lease4Collection leases_hwaddr = LeaseMgrFactory::instance().getLease4(*hwaddr);
2350 if (!leases_hwaddr.empty()) {
2351 Subnet4Ptr s = original_subnet;
2352
2353 // Pick one that belongs to a subnet in this shared network.
2354 while (s) {
2355 for (auto l = leases_hwaddr.begin(); l != leases_hwaddr.end(); ++l) {
2356 if ((*l)->subnet_id_ == s->getID()) {
2357 lease = *l;
2358 break;
2359 }
2360 }
2361
2362 if (lease) {
2363 break;
2364
2365 } else {
2366 s = s->getNextSubnet(original_subnet, query->getClasses());
2367 }
2368 }
2369 }
2370 }
2371
2372 // Check the first error case: unknown client. We check this before
2373 // validating the address sent because we don't want to respond if
2374 // we don't know this client, except if we're authoritative.
2375 bool authoritative = original_subnet->getAuthoritative();
2376 bool known_client = lease && lease->belongsToClient(hwaddr, client_id);
2377 if (!authoritative && !known_client) {
2380 .arg(query->getLabel())
2381 .arg(hint.toText());
2382
2383 ex.deleteResponse();
2384 return;
2385 }
2386
2387 // If we know this client, check if his notion of the IP address is
2388 // correct, if we don't know him, check if we are authoritative.
2389 if ((known_client && (lease->addr_ != hint)) ||
2390 (!known_client && authoritative)) {
2393 .arg(query->getLabel())
2394 .arg(hint.toText());
2395
2396 resp->setType(DHCPNAK);
2397 resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
2398 return;
2399 }
2400 }
2401
2402 CalloutHandlePtr callout_handle = getCalloutHandle(query);
2403
2404 // We need to set these values in the context as they haven't been set yet.
2405 ctx->requested_address_ = hint;
2406 ctx->fake_allocation_ = fake_allocation;
2407 ctx->callout_handle_ = callout_handle;
2408
2409 // If client query contains an FQDN or Hostname option, server
2410 // should respond to the client with the appropriate FQDN or Hostname
2411 // option to indicate if it takes responsibility for the DNS updates.
2412 // This is also the source for the hostname and dns flags that are
2413 // initially added to the lease. In most cases, this information is
2414 // good now. If we end up changing subnets in allocation we'll have to
2415 // do it again and then update the lease.
2417
2418 // Get a lease.
2419 Lease4Ptr lease = alloc_engine_->allocateLease4(*ctx);
2420
2421 // Tracks whether or not the client name (FQDN or host) has changed since
2422 // the lease was allocated.
2423 bool client_name_changed = false;
2424
2425 // Subnet may be modified by the allocation engine, if the initial subnet
2426 // belongs to a shared network.
2427 if (subnet->getID() != ctx->subnet_->getID()) {
2428 SharedNetwork4Ptr network;
2429 subnet->getSharedNetwork(network);
2431 .arg(query->getLabel())
2432 .arg(subnet->toText())
2433 .arg(ctx->subnet_->toText())
2434 .arg(network ? network->getName() : "<no network?>");
2435
2436 subnet = ctx->subnet_;
2437
2438 if (lease) {
2439 // We changed subnets and that means DDNS parameters might be different
2440 // so we need to rerun client name processing logic. Arguably we could
2441 // compare DDNS parameters for both subnets and then decide if we need
2442 // to rerun the name logic, but that's not likely to be any faster than
2443 // just re-running the name logic. @todo When inherited parameter
2444 // performance is improved this argument could be revisited.
2445 // Another case is the new subnet has a reserved hostname.
2446
2447 // First, we need to remove the prior values from the response and reset
2448 // those in context, to give processClientName a clean slate.
2449 resp->delOption(DHO_FQDN);
2450 resp->delOption(DHO_HOST_NAME);
2451 ctx->hostname_ = "";
2452 ctx->fwd_dns_update_ = false;
2453 ctx->rev_dns_update_ = false;
2454
2455 // Regenerate the name and dns flags.
2457
2458 // If the results are different from the values already on the
2459 // lease, flag it so the lease gets updated down below.
2460 if ((lease->hostname_ != ctx->hostname_) ||
2461 (lease->fqdn_fwd_ != ctx->fwd_dns_update_) ||
2462 (lease->fqdn_rev_ != ctx->rev_dns_update_)) {
2463 lease->hostname_ = ctx->hostname_;
2464 lease->fqdn_fwd_ = ctx->fwd_dns_update_;
2465 lease->fqdn_rev_ = ctx->rev_dns_update_;
2466 client_name_changed = true;
2467 }
2468 }
2469 }
2470
2471 if (lease) {
2472 // We have a lease! Let's set it in the packet and send it back to
2473 // the client.
2474 if (fake_allocation) {
2476 .arg(query->getLabel())
2477 .arg(lease->addr_.toText());
2478 } else {
2480 .arg(query->getLabel())
2481 .arg(lease->addr_.toText())
2482 .arg(Lease::lifetimeToText(lease->valid_lft_));
2483 }
2484
2485 // We're logging this here, because this is the place where we know
2486 // which subnet has been actually used for allocation. If the
2487 // client identifier matching is disabled, we want to make sure that
2488 // the user is notified.
2489 if (!ctx->subnet_->getMatchClientId()) {
2491 .arg(ctx->query_->getLabel())
2492 .arg(ctx->subnet_->getID());
2493 }
2494
2495 resp->setYiaddr(lease->addr_);
2496
2501 if (!fake_allocation) {
2502 // If this is a renewing client it will set a ciaddr which the
2503 // server may include in the response. If this is a new allocation
2504 // the client will set ciaddr to 0 and this will also be propagated
2505 // to the server's resp.
2506 resp->setCiaddr(query->getCiaddr());
2507 }
2508
2509 // We may need to update FQDN or hostname if the server is to generate
2510 // a new name from the allocated IP address or if the allocation engine
2511 // switched to a different subnet within a shared network.
2512 postAllocateNameUpdate(ctx, lease, query, resp, client_name_changed);
2513
2514 // Reuse the lease if possible.
2515 if (lease->reuseable_valid_lft_ > 0) {
2516 lease->valid_lft_ = lease->reuseable_valid_lft_;
2518 .arg(query->getLabel())
2519 .arg(lease->addr_.toText())
2520 .arg(Lease::lifetimeToText(lease->valid_lft_));
2521 }
2522
2523 // IP Address Lease time (type 51)
2525 lease->valid_lft_));
2526 resp->addOption(opt);
2527
2528 // Subnet mask (type 1)
2529 resp->addOption(getNetmaskOption(subnet));
2530
2531 // Set T1 and T2 per configuration.
2532 setTeeTimes(lease, subnet, resp);
2533
2534 // Create NameChangeRequests if this is a real allocation.
2535 if (!fake_allocation) {
2536 try {
2538 .arg(query->getLabel());
2539 createNameChangeRequests(lease, ctx->old_lease_,
2540 *ex.getContext()->getDdnsParams());
2541 } catch (const Exception& ex) {
2543 .arg(query->getLabel())
2544 .arg(ex.what());
2545 }
2546 }
2547
2548 } else {
2549 // Allocation engine did not allocate a lease. The engine logged
2550 // cause of that failure.
2553 .arg(query->getLabel())
2554 .arg(query->getCiaddr().toText())
2555 .arg(opt_requested_address ?
2556 opt_requested_address->readAddress().toText() : "(no address)");
2557
2558 resp->setType(DHCPNAK);
2559 resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
2560
2561 resp->delOption(DHO_FQDN);
2562 resp->delOption(DHO_HOST_NAME);
2563 }
2564}
2565
2566void
2568 const Pkt4Ptr& query, const Pkt4Ptr& resp, bool client_name_changed) {
2569 // We may need to update FQDN or hostname if the server is to generate
2570 // new name from the allocated IP address or if the allocation engine
2571 // has switched to a different subnet within a shared network. Get
2572 // FQDN and hostname options from the response.
2573 OptionStringPtr opt_hostname;
2574 Option4ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<
2575 Option4ClientFqdn>(resp->getOption(DHO_FQDN));
2576 if (!fqdn) {
2577 opt_hostname = boost::dynamic_pointer_cast<OptionString>(resp->getOption(DHO_HOST_NAME));
2578 if (!opt_hostname) {
2579 // We don't have either one, nothing to do.
2580 return;
2581 }
2582 }
2583
2584 // Empty hostname on the lease means we need to generate it.
2585 if (lease->hostname_.empty()) {
2586 // Note that if we have received the hostname option, rather than
2587 // Client FQDN the trailing dot is not appended to the generated
2588 // hostname because some clients don't handle the trailing dot in
2589 // the hostname. Whether the trailing dot is appended or not is
2590 // controlled by the second argument to the generateFqdn().
2591 lease->hostname_ = CfgMgr::instance().getD2ClientMgr()
2592 .generateFqdn(lease->addr_, *(ctx->getDdnsParams()), static_cast<bool>(fqdn));
2593
2595 .arg(query->getLabel())
2596 .arg(lease->hostname_);
2597
2598 client_name_changed = true;
2599 }
2600
2601 if (client_name_changed) {
2602 // The operations below are rather safe, but we want to catch
2603 // any potential exceptions (e.g. invalid lease database backend
2604 // implementation) and log an error.
2605 try {
2606 if (!ctx->fake_allocation_) {
2607 // The lease can't be reused.
2608 lease->reuseable_valid_lft_ = 0;
2609
2610 // The lease update should be safe, because the lease should
2611 // be already in the database. In most cases the exception
2612 // would be thrown if the lease was missing.
2614 }
2615
2616 // The name update in the outbound option should be also safe,
2617 // because the generated name is well formed.
2618 if (fqdn) {
2619 fqdn->setDomainName(lease->hostname_, Option4ClientFqdn::FULL);
2620 } else {
2621 opt_hostname->setValue(lease->hostname_);
2622 }
2623 } catch (const Exception& ex) {
2625 .arg(query->getLabel())
2626 .arg(lease->hostname_)
2627 .arg(ex.what());
2628 }
2629 }
2630}
2631
2633void
2634Dhcpv4Srv::setTeeTimes(const Lease4Ptr& lease, const Subnet4Ptr& subnet, Pkt4Ptr resp) {
2635
2636 uint32_t t2_time = 0;
2637 // If T2 is explicitly configured we'll use try value.
2638 if (!subnet->getT2().unspecified()) {
2639 t2_time = subnet->getT2();
2640 } else if (subnet->getCalculateTeeTimes()) {
2641 // Calculating tee times is enabled, so calculated it.
2642 t2_time = static_cast<uint32_t>(round(subnet->getT2Percent() * (lease->valid_lft_)));
2643 }
2644
2645 // Send the T2 candidate value only if it's sane: to be sane it must be less than
2646 // the valid life time.
2647 uint32_t timer_ceiling = lease->valid_lft_;
2648 if (t2_time > 0 && t2_time < timer_ceiling) {
2650 resp->addOption(t2);
2651 // When we send T2, timer ceiling for T1 becomes T2.
2652 timer_ceiling = t2_time;
2653 }
2654
2655 uint32_t t1_time = 0;
2656 // If T1 is explicitly configured we'll use try value.
2657 if (!subnet->getT1().unspecified()) {
2658 t1_time = subnet->getT1();
2659 } else if (subnet->getCalculateTeeTimes()) {
2660 // Calculating tee times is enabled, so calculate it.
2661 t1_time = static_cast<uint32_t>(round(subnet->getT1Percent() * (lease->valid_lft_)));
2662 }
2663
2664 // Send T1 if it's sane: If we sent T2, T1 must be less than that. If not it must be
2665 // less than the valid life time.
2666 if (t1_time > 0 && t1_time < timer_ceiling) {
2668 resp->addOption(t1);
2669 }
2670}
2671
2672uint16_t
2674
2675 // Look for a relay-port RAI sub-option in the query.
2676 const Pkt4Ptr& query = ex.getQuery();
2677 const OptionPtr& rai = query->getOption(DHO_DHCP_AGENT_OPTIONS);
2678 if (rai && rai->getOption(RAI_OPTION_RELAY_PORT)) {
2679 // Got the sub-option so use the remote port set by the relay.
2680 return (query->getRemotePort());
2681 }
2682 return (0);
2683}
2684
2685void
2687 adjustRemoteAddr(ex);
2688
2689 // Initialize the pointers to the client's message and the server's
2690 // response.
2691 Pkt4Ptr query = ex.getQuery();
2692 Pkt4Ptr response = ex.getResponse();
2693
2694 // The DHCPINFORM is generally unicast to the client. The only situation
2695 // when the server is unable to unicast to the client is when the client
2696 // doesn't include ciaddr and the message is relayed. In this case the
2697 // server has to reply via relay agent. For other messages we send back
2698 // through relay if message is relayed, and unicast to the client if the
2699 // message is not relayed.
2700 // If client port was set from the command line enforce all responses
2701 // to it. Of course it is only for testing purposes.
2702 // Note that the call to this function may throw if invalid combination
2703 // of hops and giaddr is found (hops = 0 if giaddr = 0 and hops != 0 if
2704 // giaddr != 0). The exception will propagate down and eventually cause the
2705 // packet to be discarded.
2706 if (client_port_) {
2707 response->setRemotePort(client_port_);
2708 } else if (((query->getType() == DHCPINFORM) &&
2709 ((!query->getCiaddr().isV4Zero()) ||
2710 (!query->isRelayed() && !query->getRemoteAddr().isV4Zero()))) ||
2711 ((query->getType() != DHCPINFORM) && !query->isRelayed())) {
2712 response->setRemotePort(DHCP4_CLIENT_PORT);
2713
2714 } else {
2715 // RFC 8357 section 5.1
2716 uint16_t relay_port = checkRelayPort(ex);
2717 response->setRemotePort(relay_port ? relay_port : DHCP4_SERVER_PORT);
2718 }
2719
2720 CfgIfacePtr cfg_iface = CfgMgr::instance().getCurrentCfg()->getCfgIface();
2721 if (query->isRelayed() &&
2722 (cfg_iface->getSocketType() == CfgIface::SOCKET_UDP) &&
2723 (cfg_iface->getOutboundIface() == CfgIface::USE_ROUTING)) {
2724
2725 // Mark the response to follow routing
2726 response->setLocalAddr(IOAddress::IPV4_ZERO_ADDRESS());
2727 response->resetIndex();
2728 // But keep the interface name
2729 response->setIface(query->getIface());
2730
2731 } else {
2732
2733 IOAddress local_addr = query->getLocalAddr();
2734
2735 // In many cases the query is sent to a broadcast address. This address
2736 // appears as a local address in the query message. We can't simply copy
2737 // this address to a response message and use it as a source address.
2738 // Instead we will need to use the address assigned to the interface
2739 // on which the query has been received. In other cases, we will just
2740 // use this address as a source address for the response.
2741 // Do the same for DHCPv4-over-DHCPv6 exchanges.
2742 if (local_addr.isV4Bcast() || query->isDhcp4o6()) {
2743 local_addr = IfaceMgr::instance().getSocket(query).addr_;
2744 }
2745
2746 // We assume that there is an appropriate socket bound to this address
2747 // and that the address is correct. This is safe assumption because
2748 // the local address of the query is set when the query is received.
2749 // The query sent to an incorrect address wouldn't have been received.
2750 // However, if socket is closed for this address between the reception
2751 // of the query and sending a response, the IfaceMgr should detect it
2752 // and return an error.
2753 response->setLocalAddr(local_addr);
2754 // In many cases the query is sent to a broadcast address. This address
2755 // appears as a local address in the query message. Therefore we can't
2756 // simply copy local address from the query and use it as a source
2757 // address for the response. Instead, we have to check what address our
2758 // socket is bound to and use it as a source address. This operation
2759 // may throw if for some reason the socket is closed.
2762 response->setIndex(query->getIndex());
2763 response->setIface(query->getIface());
2764 }
2765
2766 if (server_port_) {
2767 response->setLocalPort(server_port_);
2768 } else {
2769 response->setLocalPort(DHCP4_SERVER_PORT);
2770 }
2771}
2772
2773void
2775 // Initialize the pointers to the client's message and the server's
2776 // response.
2777 Pkt4Ptr query = ex.getQuery();
2778 Pkt4Ptr response = ex.getResponse();
2779
2780 // DHCPv4-over-DHCPv6 is simple
2781 if (query->isDhcp4o6()) {
2782 response->setRemoteAddr(query->getRemoteAddr());
2783 return;
2784 }
2785
2786 // The DHCPINFORM is slightly different than other messages in a sense
2787 // that the server should always unicast the response to the ciaddr.
2788 // It appears however that some clients don't set the ciaddr. We still
2789 // want to provision these clients and we do what we can't to send the
2790 // packet to the address where client can receive it.
2791 if (query->getType() == DHCPINFORM) {
2792 // If client adheres to RFC2131 it will set the ciaddr and in this
2793 // case we always unicast our response to this address.
2794 if (!query->getCiaddr().isV4Zero()) {
2795 response->setRemoteAddr(query->getCiaddr());
2796
2797 // If we received DHCPINFORM via relay and the ciaddr is not set we
2798 // will try to send the response via relay. The caveat is that the
2799 // relay will not have any idea where to forward the packet because
2800 // the yiaddr is likely not set. So, the broadcast flag is set so
2801 // as the response may be broadcast.
2802 } else if (query->isRelayed()) {
2803 response->setRemoteAddr(query->getGiaddr());
2804 response->setFlags(response->getFlags() | BOOTP_BROADCAST);
2805
2806 // If there is no ciaddr and no giaddr the only thing we can do is
2807 // to use the source address of the packet.
2808 } else {
2809 response->setRemoteAddr(query->getRemoteAddr());
2810 }
2811 // Remote address is now set so return.
2812 return;
2813 }
2814
2815 // If received relayed message, server responds to the relay address.
2816 if (query->isRelayed()) {
2817 // The client should set the ciaddr when sending the DHCPINFORM
2818 // but in case he didn't, the relay may not be able to determine the
2819 // address of the client, because yiaddr is not set when responding
2820 // to Confirm and the only address available was the source address
2821 // of the client. The source address is however not used here because
2822 // the message is relayed. Therefore, we set the BROADCAST flag so
2823 // as the relay can broadcast the packet.
2824 if ((query->getType() == DHCPINFORM) &&
2825 query->getCiaddr().isV4Zero()) {
2826 response->setFlags(BOOTP_BROADCAST);
2827 }
2828 response->setRemoteAddr(query->getGiaddr());
2829
2830 // If giaddr is 0 but client set ciaddr, server should unicast the
2831 // response to ciaddr.
2832 } else if (!query->getCiaddr().isV4Zero()) {
2833 response->setRemoteAddr(query->getCiaddr());
2834
2835 // We can't unicast the response to the client when sending NAK,
2836 // because we haven't allocated address for him. Therefore,
2837 // NAK is broadcast.
2838 } else if (response->getType() == DHCPNAK) {
2839 response->setRemoteAddr(IOAddress::IPV4_BCAST_ADDRESS());
2840
2841 // If yiaddr is set it means that we have created a lease for a client.
2842 } else if (!response->getYiaddr().isV4Zero()) {
2843 // If the broadcast bit is set in the flags field, we have to
2844 // send the response to broadcast address. Client may have requested it
2845 // because it doesn't support reception of messages on the interface
2846 // which doesn't have an address assigned. The other case when response
2847 // must be broadcasted is when our server does not support responding
2848 // directly to a client without address assigned.
2849 const bool bcast_flag = ((query->getFlags() & Pkt4::FLAG_BROADCAST_MASK) != 0);
2850 if (!IfaceMgr::instance().isDirectResponseSupported() || bcast_flag) {
2851 response->setRemoteAddr(IOAddress::IPV4_BCAST_ADDRESS());
2852
2853 // Client cleared the broadcast bit and we support direct responses
2854 // so we should unicast the response to a newly allocated address -
2855 // yiaddr.
2856 } else {
2857 response->setRemoteAddr(response ->getYiaddr());
2858
2859 }
2860
2861 // In most cases, we should have the remote address found already. If we
2862 // found ourselves at this point, the rational thing to do is to respond
2863 // to the address we got the query from.
2864 } else {
2865 response->setRemoteAddr(query->getRemoteAddr());
2866 }
2867
2868 // For testing *only*.
2870 response->setRemoteAddr(query->getRemoteAddr());
2871 }
2872}
2873
2874void
2876 Pkt4Ptr query = ex.getQuery();
2877 Pkt4Ptr response = ex.getResponse();
2878
2879 // Step 1: Start with fixed fields defined on subnet level.
2880 Subnet4Ptr subnet = ex.getContext()->subnet_;
2881 if (subnet) {
2882 IOAddress subnet_next_server = subnet->getSiaddr();
2883 if (!subnet_next_server.isV4Zero()) {
2884 response->setSiaddr(subnet_next_server);
2885 }
2886
2887 const string& sname = subnet->getSname();
2888 if (!sname.empty()) {
2889 // Converting string to (const uint8_t*, size_t len) format is
2890 // tricky. reinterpret_cast is not the most elegant solution,
2891 // but it does avoid us making unnecessary copy. We will convert
2892 // sname and file fields in Pkt4 to string one day and life
2893 // will be easier.
2894 response->setSname(reinterpret_cast<const uint8_t*>(sname.c_str()),
2895 sname.size());
2896 }
2897
2898 const string& filename = subnet->getFilename();
2899 if (!filename.empty()) {
2900 // Converting string to (const uint8_t*, size_t len) format is
2901 // tricky. reinterpret_cast is not the most elegant solution,
2902 // but it does avoid us making unnecessary copy. We will convert
2903 // sname and file fields in Pkt4 to string one day and life
2904 // will be easier.
2905 response->setFile(reinterpret_cast<const uint8_t*>(filename.c_str()),
2906 filename.size());
2907 }
2908 }
2909
2910 // Step 2: Try to set the values based on classes.
2911 // Any values defined in classes will override those from subnet level.
2912 const ClientClasses classes = query->getClasses();
2913 if (!classes.empty()) {
2914
2915 // Let's get class definitions
2916 const ClientClassDictionaryPtr& dict =
2917 CfgMgr::instance().getCurrentCfg()->getClientClassDictionary();
2918
2919 // Now we need to iterate over the classes assigned to the
2920 // query packet and find corresponding class definitions for it.
2921 // We want the first value found for each field. We track how
2922 // many we've found so we can stop if we have all three.
2924 string sname;
2925 string filename;
2926 size_t found_cnt = 0; // How many fields we have found.
2927 for (ClientClasses::const_iterator name = classes.cbegin();
2928 name != classes.cend() && found_cnt < 3; ++name) {
2929
2930 ClientClassDefPtr cl = dict->findClass(*name);
2931 if (!cl) {
2932 // Let's skip classes that don't have definitions. Currently
2933 // these are automatic classes VENDOR_CLASS_something, but there
2934 // may be other classes assigned under other circumstances, e.g.
2935 // by hooks.
2936 continue;
2937 }
2938
2939 if (next_server == IOAddress::IPV4_ZERO_ADDRESS()) {
2940 next_server = cl->getNextServer();
2941 if (!next_server.isV4Zero()) {
2942 response->setSiaddr(next_server);
2943 found_cnt++;
2944 }
2945 }
2946
2947 if (sname.empty()) {
2948 sname = cl->getSname();
2949 if (!sname.empty()) {
2950 // Converting string to (const uint8_t*, size_t len) format is
2951 // tricky. reinterpret_cast is not the most elegant solution,
2952 // but it does avoid us making unnecessary copy. We will convert
2953 // sname and file fields in Pkt4 to string one day and life
2954 // will be easier.
2955 response->setSname(reinterpret_cast<const uint8_t*>(sname.c_str()),
2956 sname.size());
2957 found_cnt++;
2958 }
2959 }
2960
2961 if (filename.empty()) {
2962 filename = cl->getFilename();
2963 if (!filename.empty()) {
2964 // Converting string to (const uint8_t*, size_t len) format is
2965 // tricky. reinterpret_cast is not the most elegant solution,
2966 // but it does avoid us making unnecessary copy. We will convert
2967 // sname and file fields in Pkt4 to string one day and life
2968 // will be easier.
2969 response->setFile(reinterpret_cast<const uint8_t*>(filename.c_str()),
2970 filename.size());
2971 found_cnt++;
2972 }
2973 }
2974 }
2975 }
2976
2977 // Step 3: try to set values using HR. Any values coming from there will override
2978 // the subnet or class values.
2980}
2981
2983Dhcpv4Srv::getNetmaskOption(const Subnet4Ptr& subnet) {
2984 uint32_t netmask = getNetmask4(subnet->get().second).toUint32();
2985
2987 DHO_SUBNET_MASK, netmask));
2988
2989 return (opt);
2990}
2991
2992Pkt4Ptr
2994 // server-id is forbidden.
2995 sanityCheck(discover, FORBIDDEN);
2996
2997 bool drop = false;
2998 Subnet4Ptr subnet = selectSubnet(discover, drop);
2999
3000 // Stop here if selectSubnet decided to drop the packet
3001 if (drop) {
3002 return (Pkt4Ptr());
3003 }
3004
3005 Dhcpv4Exchange ex(alloc_engine_, discover, subnet, drop);
3006
3007 // Stop here if Dhcpv4Exchange constructor decided to drop the packet
3008 if (drop) {
3009 return (Pkt4Ptr());
3010 }
3011
3012 if (MultiThreadingMgr::instance().getMode()) {
3013 // The lease reclamation cannot run at the same time.
3014 ReadLockGuard share(alloc_engine_->getReadWriteMutex());
3015
3016 assignLease(ex);
3017 } else {
3018 assignLease(ex);
3019 }
3020
3021 if (!ex.getResponse()) {
3022 // The offer is empty so return it *now*!
3023 return (Pkt4Ptr());
3024 }
3025
3026 // Adding any other options makes sense only when we got the lease.
3027 if (!ex.getResponse()->getYiaddr().isV4Zero()) {
3028 // If this is global reservation or the subnet doesn't belong to a shared
3029 // network we have already fetched it and evaluated the classes.
3031
3032 // Required classification
3033 requiredClassify(ex);
3034
3038 // There are a few basic options that we always want to
3039 // include in the response. If client did not request
3040 // them we append them for him.
3042
3043 // Set fixed fields (siaddr, sname, filename) if defined in
3044 // the reservation, class or subnet specific configuration.
3045 setFixedFields(ex);
3046
3047 } else {
3048 // If the server can't offer an address, it drops the packet.
3049 return (Pkt4Ptr());
3050
3051 }
3052
3053 // Set the src/dest IP address, port and interface for the outgoing
3054 // packet.
3055 adjustIfaceData(ex);
3056
3057 appendServerID(ex);
3058
3059 return (ex.getResponse());
3060}
3061
3062Pkt4Ptr
3064 // Since we cannot distinguish between client states
3065 // we'll make server-id is optional for REQUESTs.
3066 sanityCheck(request, OPTIONAL);
3067
3068 bool drop = false;
3069 Subnet4Ptr subnet = selectSubnet(request, drop);
3070
3071 // Stop here if selectSubnet decided to drop the packet
3072 if (drop) {
3073 return (Pkt4Ptr());
3074 }
3075
3076 Dhcpv4Exchange ex(alloc_engine_, request, subnet, drop);
3077
3078 // Stop here if Dhcpv4Exchange constructor decided to drop the packet
3079 if (drop) {
3080 return (Pkt4Ptr());
3081 }
3082
3083 // Note that we treat REQUEST message uniformly, regardless if this is a
3084 // first request (requesting for new address), renewing existing address
3085 // or even rebinding.
3086 if (MultiThreadingMgr::instance().getMode()) {
3087 // The lease reclamation cannot run at the same time.
3088 ReadLockGuard share(alloc_engine_->getReadWriteMutex());
3089
3090 assignLease(ex);
3091 } else {
3092 assignLease(ex);
3093 }
3094
3095 Pkt4Ptr response = ex.getResponse();
3096 if (!response) {
3097 // The ack is empty so return it *now*!
3098 return (Pkt4Ptr());
3099 } else if (request->inClass("BOOTP")) {
3100 // Put BOOTP responses in the BOOTP class.
3101 response->addClass("BOOTP");
3102 }
3103
3104 // Adding any other options makes sense only when we got the lease.
3105 if (!response->getYiaddr().isV4Zero()) {
3106 // If this is global reservation or the subnet doesn't belong to a shared
3107 // network we have already fetched it and evaluated the classes.
3109
3110 // Required classification
3111 requiredClassify(ex);
3112
3116 // There are a few basic options that we always want to
3117 // include in the response. If client did not request
3118 // them we append them for him.
3120
3121 // Set fixed fields (siaddr, sname, filename) if defined in
3122 // the reservation, class or subnet specific configuration.
3123 setFixedFields(ex);
3124 }
3125
3126 // Set the src/dest IP address, port and interface for the outgoing
3127 // packet.
3128 adjustIfaceData(ex);
3129
3130 appendServerID(ex);
3131
3132 // Return the pointer to the context, which will be required by the
3133 // leases4_committed callouts.
3134 context = ex.getContext();
3135
3136 return (ex.getResponse());
3137}
3138
3139void
3141 // Server-id is mandatory in DHCPRELEASE (see table 5, RFC2131)
3142 // but ISC DHCP does not enforce this, so we'll follow suit.
3143 sanityCheck(release, OPTIONAL);
3144
3145 // Try to find client-id. Note that for the DHCPRELEASE we don't check if the
3146 // match-client-id configuration parameter is disabled because this parameter
3147 // is configured for subnets and we don't select subnet for the DHCPRELEASE.
3148 // Bogus clients usually generate new client identifiers when they first
3149 // connect to the network, so whatever client identifier has been used to
3150 // acquire the lease, the client identifier carried in the DHCPRELEASE is
3151 // likely to be the same and the lease will be correctly identified in the
3152 // lease database. If supplied client identifier differs from the one used
3153 // to acquire the lease then the lease will remain in the database and
3154 // simply expire.
3155 ClientIdPtr client_id;
3156 OptionPtr opt = release->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
3157 if (opt) {
3158 client_id = ClientIdPtr(new ClientId(opt->getData()));
3159 }
3160
3161 try {
3162 // Do we have a lease for that particular address?
3163 Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(release->getCiaddr());
3164
3165 if (!lease) {
3166 // No such lease - bogus release
3168 .arg(release->getLabel())
3169 .arg(release->getCiaddr().toText());
3170 return;
3171 }
3172
3173 if (!lease->belongsToClient(release->getHWAddr(), client_id)) {
3175 .arg(release->getLabel())
3176 .arg(release->getCiaddr().toText());
3177 return;
3178 }
3179
3180 bool skip = false;
3181
3182 // Execute all callouts registered for lease4_release
3183 if (HooksManager::calloutsPresent(Hooks.hook_index_lease4_release_)) {
3184 CalloutHandlePtr callout_handle = getCalloutHandle(release);
3185
3186 // Use the RAII wrapper to make sure that the callout handle state is
3187 // reset when this object goes out of scope. All hook points must do
3188 // it to prevent possible circular dependency between the callout
3189 // handle and its arguments.
3190 ScopedCalloutHandleState callout_handle_state(callout_handle);
3191
3192 // Enable copying options from the packet within hook library.
3193 ScopedEnableOptionsCopy<Pkt4> query4_options_copy(release);
3194
3195 // Pass the original packet
3196 callout_handle->setArgument("query4", release);
3197
3198 // Pass the lease to be updated
3199 callout_handle->setArgument("lease4", lease);
3200
3201 // Call all installed callouts
3202 HooksManager::callCallouts(Hooks.hook_index_lease4_release_,
3203 *callout_handle);
3204
3205 // Callouts decided to skip the next processing step. The next
3206 // processing step would to send the packet, so skip at this
3207 // stage means "drop response".
3208 if ((callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) ||
3209 (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP)) {
3210 skip = true;
3213 .arg(release->getLabel());
3214 }
3215 }
3216
3217 // Callout didn't indicate to skip the release process. Let's release
3218 // the lease.
3219 if (!skip) {
3220 bool success = LeaseMgrFactory::instance().deleteLease(lease);
3221
3222 if (success) {
3223
3224 context.reset(new AllocEngine::ClientContext4());
3225 context->old_lease_ = lease;
3226
3227 // Release successful
3229 .arg(release->getLabel())
3230 .arg(lease->addr_.toText());
3231
3232 // Need to decrease statistic for assigned addresses.
3233 StatsMgr::instance().addValue(
3234 StatsMgr::generateName("subnet", lease->subnet_id_, "assigned-addresses"),
3235 static_cast<int64_t>(-1));
3236
3237 // Remove existing DNS entries for the lease, if any.
3238 queueNCR(CHG_REMOVE, lease);
3239
3240 } else {
3241 // Release failed
3243 .arg(release->getLabel())
3244 .arg(lease->addr_.toText());
3245 }
3246 }
3247 } catch (const isc::Exception& ex) {
3249 .arg(release->getLabel())
3250 .arg(release->getCiaddr())
3251 .arg(ex.what());
3252 }
3253}
3254
3255void
3257 // Server-id is mandatory in DHCPDECLINE (see table 5, RFC2131)
3258 // but ISC DHCP does not enforce this, so we'll follow suit.
3259 sanityCheck(decline, OPTIONAL);
3260
3261 // Client is supposed to specify the address being declined in
3262 // Requested IP address option, but must not set its ciaddr.
3263 // (again, see table 5 in RFC2131).
3264
3265 OptionCustomPtr opt_requested_address = boost::dynamic_pointer_cast<
3266 OptionCustom>(decline->getOption(DHO_DHCP_REQUESTED_ADDRESS));
3267 if (!opt_requested_address) {
3268
3269 isc_throw(RFCViolation, "Mandatory 'Requested IP address' option missing"
3270 " in DHCPDECLINE sent from " << decline->getLabel());
3271 }
3272 IOAddress addr(opt_requested_address->readAddress());
3273
3274 // We could also extract client's address from ciaddr, but that's clearly
3275 // against RFC2131.
3276
3277 // Now we need to check whether this address really belongs to the client
3278 // that attempts to decline it.
3279 const Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(addr);
3280
3281 if (!lease) {
3282 // Client tried to decline an address, but we don't have a lease for
3283 // that address. Let's ignore it.
3284 //
3285 // We could assume that we're recovering from a mishandled migration
3286 // to a new server and mark the address as declined, but the window of
3287 // opportunity for that to be useful is small and the attack vector
3288 // would be pretty severe.
3290 .arg(addr.toText()).arg(decline->getLabel());
3291 return;
3292 }
3293
3294 // Get client-id, if available.
3295 OptionPtr opt_clientid = decline->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
3296 ClientIdPtr client_id;
3297 if (opt_clientid) {
3298 client_id.reset(new ClientId(opt_clientid->getData()));
3299 }
3300
3301 // Check if the client attempted to decline a lease it doesn't own.
3302 if (!lease->belongsToClient(decline->getHWAddr(), client_id)) {
3303
3304 // Get printable hardware addresses
3305 string client_hw = decline->getHWAddr() ?
3306 decline->getHWAddr()->toText(false) : "(none)";
3307 string lease_hw = lease->hwaddr_ ?
3308 lease->hwaddr_->toText(false) : "(none)";
3309
3310 // Get printable client-ids
3311 string client_id_txt = client_id ? client_id->toText() : "(none)";
3312 string lease_id_txt = lease->client_id_ ?
3313 lease->client_id_->toText() : "(none)";
3314
3315 // Print the warning and we're done here.
3317 .arg(addr.toText()).arg(decline->getLabel())
3318 .arg(client_hw).arg(lease_hw).arg(client_id_txt).arg(lease_id_txt);
3319
3320 return;
3321 }
3322
3323 // Ok, all is good. The client is reporting its own address. Let's
3324 // process it.
3325 declineLease(lease, decline, context);
3326}
3327
3328void
3329Dhcpv4Srv::declineLease(const Lease4Ptr& lease, const Pkt4Ptr& decline,
3331
3332 // Let's check if there are hooks installed for decline4 hook point.
3333 // If they are, let's pass the lease and client's packet. If the hook
3334 // sets status to drop, we reject this Decline.
3335 if (HooksManager::calloutsPresent(Hooks.hook_index_lease4_decline_)) {
3336 CalloutHandlePtr callout_handle = getCalloutHandle(decline);
3337
3338 // Use the RAII wrapper to make sure that the callout handle state is
3339 // reset when this object goes out of scope. All hook points must do
3340 // it to prevent possible circular dependency between the callout
3341 // handle and its arguments.
3342 ScopedCalloutHandleState callout_handle_state(callout_handle);
3343
3344 // Enable copying options from the packet within hook library.
3345 ScopedEnableOptionsCopy<Pkt4> query4_options_copy(decline);
3346
3347 // Pass the original packet
3348 callout_handle->setArgument("query4", decline);
3349
3350 // Pass the lease to be updated
3351 callout_handle->setArgument("lease4", lease);
3352
3353 // Call callouts
3354 HooksManager::callCallouts(Hooks.hook_index_lease4_decline_,
3355 *callout_handle);
3356
3357 // Check if callouts decided to skip the next processing step.
3358 // If any of them did, we will drop the packet.
3359 if ((callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) ||
3360 (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP)) {
3362 .arg(decline->getLabel()).arg(lease->addr_.toText());
3363 return;
3364 }
3365 }
3366
3367 Lease4Ptr old_values = boost::make_shared<Lease4>(*lease);
3368
3369 // @todo: Call hooks.
3370
3371 // We need to disassociate the lease from the client. Once we move a lease
3372 // to declined state, it is no longer associated with the client in any
3373 // way.
3374 lease->decline(CfgMgr::instance().getCurrentCfg()->getDeclinePeriod());
3375
3376 try {
3378 } catch (const Exception& ex) {
3379 // Update failed.
3381 .arg(decline->getLabel())
3382 .arg(lease->addr_.toText())
3383 .arg(ex.what());
3384 return;
3385 }
3386
3387 // Remove existing DNS entries for the lease, if any.
3388 // queueNCR will do the necessary checks and will skip the update, if not needed.
3389 queueNCR(CHG_REMOVE, old_values);
3390
3391 // Bump up the statistics.
3392
3393 // Per subnet declined addresses counter.
3394 StatsMgr::instance().addValue(
3395 StatsMgr::generateName("subnet", lease->subnet_id_, "declined-addresses"),
3396 static_cast<int64_t>(1));
3397
3398 // Global declined addresses counter.
3399 StatsMgr::instance().addValue("declined-addresses", static_cast<int64_t>(1));
3400
3401 // We do not want to decrease the assigned-addresses at this time. While
3402 // technically a declined address is no longer allocated, the primary usage
3403 // of the assigned-addresses statistic is to monitor pool utilization. Most
3404 // people would forget to include declined-addresses in the calculation,
3405 // and simply do assigned-addresses/total-addresses. This would have a bias
3406 // towards under-representing pool utilization, if we decreased allocated
3407 // immediately after receiving DHCPDECLINE, rather than later when we recover
3408 // the address.
3409
3410 context.reset(new AllocEngine::ClientContext4());
3411 context->new_lease_ = lease;
3412
3413 LOG_INFO(lease4_logger, DHCP4_DECLINE_LEASE).arg(lease->addr_.toText())
3414 .arg(decline->getLabel()).arg(lease->valid_lft_);
3415}
3416
3417Pkt4Ptr
3419 // server-id is supposed to be forbidden (as is requested address)
3420 // but ISC DHCP does not enforce either. So neither will we.
3421 sanityCheck(inform, OPTIONAL);
3422
3423 bool drop = false;
3424 Subnet4Ptr subnet = selectSubnet(inform, drop);
3425
3426 // Stop here if selectSubnet decided to drop the packet
3427 if (drop) {
3428 return (Pkt4Ptr());
3429 }
3430
3431 Dhcpv4Exchange ex(alloc_engine_, inform, subnet, drop);
3432
3433 // Stop here if Dhcpv4Exchange constructor decided to drop the packet
3434 if (drop) {
3435 return (Pkt4Ptr());
3436 }
3437
3438 Pkt4Ptr ack = ex.getResponse();
3439
3440 // If this is global reservation or the subnet doesn't belong to a shared
3441 // network we have already fetched it and evaluated the classes.
3443
3444 requiredClassify(ex);
3445
3450 adjustIfaceData(ex);
3451
3452 // Set fixed fields (siaddr, sname, filename) if defined in
3453 // the reservation, class or subnet specific configuration.
3454 setFixedFields(ex);
3455
3456 // There are cases for the DHCPINFORM that the server receives it via
3457 // relay but will send the response to the client's unicast address
3458 // carried in the ciaddr. In this case, the giaddr and hops field should
3459 // be cleared (these fields were copied by the copyDefaultFields function).
3460 // Also Relay Agent Options should be removed if present.
3461 if (ack->getRemoteAddr() != inform->getGiaddr()) {
3463 .arg(inform->getLabel())
3464 .arg(ack->getRemoteAddr())
3465 .arg(ack->getIface());
3466 ack->setHops(0);
3467 ack->setGiaddr(IOAddress::IPV4_ZERO_ADDRESS());
3468 ack->delOption(DHO_DHCP_AGENT_OPTIONS);
3469 }
3470
3471 // The DHCPACK must contain server id.
3472 appendServerID(ex);
3473
3474 return (ex.getResponse());
3475}
3476
3477bool
3478Dhcpv4Srv::accept(const Pkt4Ptr& query) const {
3479 // Check that the message type is accepted by the server. We rely on the
3480 // function called to log a message if needed.
3481 if (!acceptMessageType(query)) {
3482 return (false);
3483 }
3484 // Check if the message from directly connected client (if directly
3485 // connected) should be dropped or processed.
3486 if (!acceptDirectRequest(query)) {
3488 .arg(query->getLabel())
3489 .arg(query->getIface());
3490 return (false);
3491 }
3492
3493 // Check if the DHCPv4 packet has been sent to us or to someone else.
3494 // If it hasn't been sent to us, drop it!
3495 if (!acceptServerId(query)) {
3497 .arg(query->getLabel())
3498 .arg(query->getIface());
3499 return (false);
3500 }
3501
3502 return (true);
3503}
3504
3505bool
3507 // Accept all relayed messages.
3508 if (pkt->isRelayed()) {
3509 return (true);
3510 }
3511
3512 // Accept all DHCPv4-over-DHCPv6 messages.
3513 if (pkt->isDhcp4o6()) {
3514 return (true);
3515 }
3516
3517 // The source address must not be zero for the DHCPINFORM message from
3518 // the directly connected client because the server will not know where
3519 // to respond if the ciaddr was not present.
3520 try {
3521 if (pkt->getType() == DHCPINFORM) {
3522 if (pkt->getRemoteAddr().isV4Zero() &&
3523 pkt->getCiaddr().isV4Zero()) {
3524 return (false);
3525 }
3526 }
3527 } catch (...) {
3528 // If we got here, it is probably because the message type hasn't
3529 // been set. But, this should not really happen assuming that
3530 // we validate the message type prior to calling this function.
3531 return (false);
3532 }
3533 bool drop = false;
3534 bool result = (!pkt->getLocalAddr().isV4Bcast() ||
3535 selectSubnet(pkt, drop, true));
3536 if (drop) {
3537 // The packet must be dropped but as sanity_only is true it is dead code.
3538 return (false);
3539 }
3540 return (result);
3541}
3542
3543bool
3545 // When receiving a packet without message type option, getType() will
3546 // throw.
3547 int type;
3548 try {
3549 type = query->getType();
3550
3551 } catch (...) {
3553 .arg(query->getLabel())
3554 .arg(query->getIface());
3555 return (false);
3556 }
3557
3558 // Once we know that the message type is within a range of defined DHCPv4
3559 // messages, we do a detailed check to make sure that the received message
3560 // is targeted at server. Note that we could have received some Offer
3561 // message broadcasted by the other server to a relay. Even though, the
3562 // server would rather unicast its response to a relay, let's be on the
3563 // safe side. Also, we want to drop other messages which we don't support.
3564 // All these valid messages that we are not going to process are dropped
3565 // silently.
3566
3567 switch(type) {
3568 case DHCPDISCOVER:
3569 case DHCPREQUEST:
3570 case DHCPRELEASE:
3571 case DHCPDECLINE:
3572 case DHCPINFORM:
3573 return (true);
3574 break;
3575
3576 case DHCP_NOTYPE:
3578 .arg(query->getLabel());
3579 break;
3580
3581 default:
3582 // If we receive a message with a non-existing type, we are logging it.
3583 if (type >= DHCP_TYPES_EOF) {
3585 .arg(query->getLabel())
3586 .arg(type);
3587 } else {
3588 // Exists but we don't support it.
3590 .arg(query->getLabel())
3591 .arg(type);
3592 }
3593 break;
3594 }
3595
3596 return (false);
3597}
3598
3599bool
3601 // This function is meant to be called internally by the server class, so
3602 // we rely on the caller to sanity check the pointer and we don't check
3603 // it here.
3604
3605 // Check if server identifier option is present. If it is not present
3606 // we accept the message because it is targeted to all servers.
3607 // Note that we don't check cases that server identifier is mandatory
3608 // but not present. This is meant to be sanity checked in other
3609 // functions.
3610 OptionPtr option = query->getOption(DHO_DHCP_SERVER_IDENTIFIER);
3611 if (!option) {
3612 return (true);
3613 }
3614 // Server identifier is present. Let's convert it to 4-byte address
3615 // and try to match with server identifiers used by the server.
3616 OptionCustomPtr option_custom =
3617 boost::dynamic_pointer_cast<OptionCustom>(option);
3618 // Unable to convert the option to the option type which encapsulates it.
3619 // We treat this as non-matching server id.
3620 if (!option_custom) {
3621 return (false);
3622 }
3623 // The server identifier option should carry exactly one IPv4 address.
3624 // If the option definition for the server identifier doesn't change,
3625 // the OptionCustom object should have exactly one IPv4 address and
3626 // this check is somewhat redundant. On the other hand, if someone
3627 // breaks option it may be better to check that here.
3628 if (option_custom->getDataFieldsNum() != 1) {
3629 return (false);
3630 }
3631
3632 // The server identifier MUST be an IPv4 address. If given address is
3633 // v6, it is wrong.
3634 IOAddress server_id = option_custom->readAddress();
3635 if (!server_id.isV4()) {
3636 return (false);
3637 }
3638
3639 // This function iterates over all interfaces on which the
3640 // server is listening to find the one which has a socket bound
3641 // to the address carried in the server identifier option.
3642 // This has some performance implications. However, given that
3643 // typically there will be just a few active interfaces the
3644 // performance hit should be acceptable. If it turns out to
3645 // be significant, we will have to cache server identifiers
3646 // when sockets are opened.
3647 if (IfaceMgr::instance().hasOpenSocket(server_id)) {
3648 return (true);
3649 }
3650
3651 // There are some cases when an administrator explicitly sets server
3652 // identifier (option 54) that should be used for a given, subnet,
3653 // network etc. It doesn't have to be an address assigned to any of
3654 // the server interfaces. Thus, we have to check if the server
3655 // identifier received is the one that we explicitly set in the
3656 // server configuration. At this point, we don't know which subnet
3657 // the client belongs to so we can't match the server id with any
3658 // subnet. We simply check if this server identifier is configured
3659 // anywhere. This should be good enough to eliminate exchanges
3660 // with other servers in the same network.
3661
3669
3671
3672 // Check if there is at least one subnet configured with this server
3673 // identifier.
3674 ConstCfgSubnets4Ptr cfg_subnets = cfg->getCfgSubnets4();
3675 if (cfg_subnets->hasSubnetWithServerId(server_id)) {
3676 return (true);
3677 }
3678
3679 // This server identifier is not configured for any of the subnets, so
3680 // check on the shared network level.
3681 CfgSharedNetworks4Ptr cfg_networks = cfg->getCfgSharedNetworks4();
3682 if (cfg_networks->hasNetworkWithServerId(server_id)) {
3683 return (true);
3684 }
3685
3686 // Check if the server identifier is configured at client class level.
3687 const ClientClasses& classes = query->getClasses();
3688 for (ClientClasses::const_iterator cclass = classes.cbegin();
3689 cclass != classes.cend(); ++cclass) {
3690 // Find the client class definition for this class
3692 getClientClassDictionary()->findClass(*cclass);
3693 if (!ccdef) {
3694 continue;
3695 }
3696
3697 if (ccdef->getCfgOption()->empty()) {
3698 // Skip classes which don't configure options
3699 continue;
3700 }
3701
3702 OptionCustomPtr context_opt_server_id = boost::dynamic_pointer_cast<OptionCustom>
3703 (ccdef->getCfgOption()->get(DHCP4_OPTION_SPACE, DHO_DHCP_SERVER_IDENTIFIER).option_);
3704 if (context_opt_server_id && (context_opt_server_id->readAddress() == server_id)) {
3705 return (true);
3706 }
3707 }
3708
3709 // Finally, it is possible that the server identifier is specified
3710 // on the global level.
3711 ConstCfgOptionPtr cfg_global_options = cfg->getCfgOption();
3712 OptionCustomPtr opt_server_id = boost::dynamic_pointer_cast<OptionCustom>
3713 (cfg_global_options->get(DHCP4_OPTION_SPACE, DHO_DHCP_SERVER_IDENTIFIER).option_);
3714
3715 return (opt_server_id && (opt_server_id->readAddress() == server_id));
3716}
3717
3718void
3720 OptionPtr server_id = query->getOption(DHO_DHCP_SERVER_IDENTIFIER);
3721 switch (serverid) {
3722 case FORBIDDEN:
3723 if (server_id) {
3724 isc_throw(RFCViolation, "Server-id option was not expected, but"
3725 << " received in message "
3726 << query->getName());
3727 }
3728 break;
3729
3730 case MANDATORY:
3731 if (!server_id) {
3732 isc_throw(RFCViolation, "Server-id option was expected, but not"
3733 " received in message "
3734 << query->getName());
3735 }
3736 break;
3737
3738 case OPTIONAL:
3739 // do nothing here
3740 ;
3741 }
3742
3743 // If there is HWAddress set and it is non-empty, then we're good
3744 if (query->getHWAddr() && !query->getHWAddr()->hwaddr_.empty()) {
3745 return;
3746 }
3747
3748 // There has to be something to uniquely identify the client:
3749 // either non-zero MAC address or client-id option present (or both)
3750 OptionPtr client_id = query->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
3751
3752 // If there's no client-id (or a useless one is provided, i.e. 0 length)
3753 if (!client_id || client_id->len() == client_id->getHeaderLen()) {
3754 isc_throw(RFCViolation, "Missing or useless client-id and no HW address"
3755 " provided in message "
3756 << query->getName());
3757 }
3758}
3759
3762}
3763
3765 // First collect required classes
3766 Pkt4Ptr query = ex.getQuery();
3767 ClientClasses classes = query->getClasses(true);
3768 Subnet4Ptr subnet = ex.getContext()->subnet_;
3769
3770 if (subnet) {
3771 // Begin by the shared-network
3772 SharedNetwork4Ptr network;
3773 subnet->getSharedNetwork(network);
3774 if (network) {
3775 const ClientClasses& to_add = network->getRequiredClasses();
3776 for (ClientClasses::const_iterator cclass = to_add.cbegin();
3777 cclass != to_add.cend(); ++cclass) {
3778 classes.insert(*cclass);
3779 }
3780 }
3781
3782 // Followed by the subnet
3783 const ClientClasses& to_add = subnet->getRequiredClasses();
3784 for(ClientClasses::const_iterator cclass = to_add.cbegin();
3785 cclass != to_add.cend(); ++cclass) {
3786 classes.insert(*cclass);
3787 }
3788
3789 // And finish by the pool
3790 Pkt4Ptr resp = ex.getResponse();
3792 if (resp) {
3793 addr = resp->getYiaddr();
3794 }
3795 if (!addr.isV4Zero()) {
3796 PoolPtr pool = subnet->getPool(Lease::TYPE_V4, addr, false);
3797 if (pool) {
3798 const ClientClasses& to_add = pool->getRequiredClasses();
3799 for (ClientClasses::const_iterator cclass = to_add.cbegin();
3800 cclass != to_add.cend(); ++cclass) {
3801 classes.insert(*cclass);
3802 }
3803 }
3804 }
3805
3806 // host reservation???
3807 }
3808
3809 // Run match expressions
3810 // Note getClientClassDictionary() cannot be null
3811 const ClientClassDictionaryPtr& dict =
3812 CfgMgr::instance().getCurrentCfg()->getClientClassDictionary();
3813 for (ClientClasses::const_iterator cclass = classes.cbegin();
3814 cclass != classes.cend(); ++cclass) {
3815 const ClientClassDefPtr class_def = dict->findClass(*cclass);
3816 if (!class_def) {
3818 .arg(*cclass);
3819 continue;
3820 }
3821 const ExpressionPtr& expr_ptr = class_def->getMatchExpr();
3822 // Nothing to do without an expression to evaluate
3823 if (!expr_ptr) {
3825 .arg(*cclass);
3826 continue;
3827 }
3828 // Evaluate the expression which can return false (no match),
3829 // true (match) or raise an exception (error)
3830 try {
3831 bool status = evaluateBool(*expr_ptr, *query);
3832 if (status) {
3834 .arg(*cclass)
3835 .arg(status);
3836 // Matching: add the class
3837 query->addClass(*cclass);
3838 } else {
3840 .arg(*cclass)
3841 .arg(status);
3842 }
3843 } catch (const Exception& ex) {
3845 .arg(*cclass)
3846 .arg(ex.what());
3847 } catch (...) {
3849 .arg(*cclass)
3850 .arg("get exception?");
3851 }
3852 }
3853}
3854
3855void
3857 // Iterate on the list of deferred option codes
3858 BOOST_FOREACH(const uint16_t& code, query->getDeferredOptions()) {
3860 // Iterate on client classes
3861 const ClientClasses& classes = query->getClasses();
3862 for (ClientClasses::const_iterator cclass = classes.cbegin();
3863 cclass != classes.cend(); ++cclass) {
3864 // Get the client class definition for this class
3865 const ClientClassDefPtr& ccdef =
3867 getClientClassDictionary()->findClass(*cclass);
3868 // If not found skip it
3869 if (!ccdef) {
3870 continue;
3871 }
3872 // If there is no option definition skip it
3873 if (!ccdef->getCfgOptionDef()) {
3874 continue;
3875 }
3876 def = ccdef->getCfgOptionDef()->get(DHCP4_OPTION_SPACE, code);
3877 // Stop at the first client class with a definition
3878 if (def) {
3879 break;
3880 }
3881 }
3882 // If not found try the global definition
3883 if (!def) {
3885 }
3886 if (!def) {
3888 }
3889 // Finish by last resort definition
3890 if (!def) {
3892 }
3893 // If not defined go to the next option
3894 if (!def) {
3895 continue;
3896 }
3897 // Get the existing option for its content and remove all
3898 OptionPtr opt = query->getOption(code);
3899 if (!opt) {
3900 // should not happen but do not crash anyway
3903 .arg(code);
3904 continue;
3905 }
3906 const OptionBuffer buf = opt->getData();
3907 try {
3908 // Unpack the option
3909 opt = def->optionFactory(Option::V4, code, buf);
3910 } catch (const std::exception& e) {
3911 // Failed to parse the option.
3914 .arg(code)
3915 .arg(e.what());
3916 continue;
3917 }
3918 while (query->delOption(code)) {
3919 // continue
3920 }
3921 // Add the unpacked option.
3922 query->addOption(opt);
3923 }
3924}
3925
3926void
3929 if (d2_mgr.ddnsEnabled()) {
3930 // Updates are enabled, so lets start the sender, passing in
3931 // our error handler.
3932 // This may throw so wherever this is called needs to ready.
3934 this, ph::_1, ph::_2));
3935 }
3936}
3937
3938void
3941 if (d2_mgr.ddnsEnabled()) {
3942 // Updates are enabled, so lets stop the sender
3943 d2_mgr.stopSender();
3944 }
3945}
3946
3947void
3952 arg(result).arg((ncr ? ncr->toText() : " NULL "));
3953 // We cannot communicate with kea-dhcp-ddns, suspend further updates.
3957}
3958
3959// Refer to config_report so it will be embedded in the binary
3961
3962std::string
3964 std::stringstream tmp;
3965
3966 tmp << VERSION;
3967 if (extended) {
3968 tmp << endl << EXTENDED_VERSION << endl;
3969 tmp << "linked with:" << endl;
3970 tmp << Logger::getVersion() << endl;
3971 tmp << CryptoLink::getVersion() << endl;
3972 tmp << "database:" << endl;
3973#ifdef HAVE_MYSQL
3974 tmp << MySqlLeaseMgr::getDBVersion() << endl;
3975#endif
3976#ifdef HAVE_PGSQL
3977 tmp << PgSqlLeaseMgr::getDBVersion() << endl;
3978#endif
3979#ifdef HAVE_CQL
3980 tmp << CqlLeaseMgr::getDBVersion() << endl;
3981#endif
3983
3984 // @todo: more details about database runtime
3985 }
3986
3987 return (tmp.str());
3988}
3989
3991 // Note that we're not bumping pkt4-received statistic as it was
3992 // increased early in the packet reception code.
3993
3994 string stat_name = "pkt4-unknown-received";
3995 try {
3996 switch (query->getType()) {
3997 case DHCPDISCOVER:
3998 stat_name = "pkt4-discover-received";
3999 break;
4000 case DHCPOFFER:
4001 // Should not happen, but let's keep a counter for it
4002 stat_name = "pkt4-offer-received";
4003 break;
4004 case DHCPREQUEST:
4005 stat_name = "pkt4-request-received";
4006 break;
4007 case DHCPACK:
4008 // Should not happen, but let's keep a counter for it
4009 stat_name = "pkt4-ack-received";
4010 break;
4011 case DHCPNAK:
4012 // Should not happen, but let's keep a counter for it
4013 stat_name = "pkt4-nak-received";
4014 break;
4015 case DHCPRELEASE:
4016 stat_name = "pkt4-release-received";
4017 break;
4018 case DHCPDECLINE:
4019 stat_name = "pkt4-decline-received";
4020 break;
4021 case DHCPINFORM:
4022 stat_name = "pkt4-inform-received";
4023 break;
4024 default:
4025 ; // do nothing
4026 }
4027 }
4028 catch (...) {
4029 // If the incoming packet doesn't have option 53 (message type)
4030 // or a hook set pkt4_receive_skip, then Pkt4::getType() may
4031 // throw an exception. That's ok, we'll then use the default
4032 // name of pkt4-unknown-received.
4033 }
4034
4036 static_cast<int64_t>(1));
4037}
4038
4040 // Increase generic counter for sent packets.
4042 static_cast<int64_t>(1));
4043
4044 // Increase packet type specific counter for packets sent.
4045 string stat_name;
4046 switch (response->getType()) {
4047 case DHCPOFFER:
4048 stat_name = "pkt4-offer-sent";
4049 break;
4050 case DHCPACK:
4051 stat_name = "pkt4-ack-sent";
4052 break;
4053 case DHCPNAK:
4054 stat_name = "pkt4-nak-sent";
4055 break;
4056 default:
4057 // That should never happen
4058 return;
4059 }
4060
4062 static_cast<int64_t>(1));
4063}
4064
4066 return (Hooks.hook_index_buffer4_receive_);
4067}
4068
4070 return (Hooks.hook_index_pkt4_receive_);
4071}
4072
4074 return (Hooks.hook_index_subnet4_select_);
4075}
4076
4078 return (Hooks.hook_index_lease4_release_);
4079}
4080
4082 return (Hooks.hook_index_pkt4_send_);
4083}
4084
4086 return (Hooks.hook_index_buffer4_send_);
4087}
4088
4090 return (Hooks.hook_index_lease4_decline_);
4091}
4092
4094 // Dump all of our current packets, anything that is mid-stream
4095 HooksManager::clearParkingLots();
4096}
4097
4098std::list<std::list<std::string>> Dhcpv4Srv::jsonPathsToRedact() const {
4099 static std::list<std::list<std::string>> const list({
4100 {"config-control", "config-databases", "[]"},
4101 {"hooks-libraries", "[]", "parameters", "*"},
4102 {"hosts-database"},
4103 {"hosts-databases", "[]"},
4104 {"lease-database"},
4105 });
4106 return list;
4107}
4108
4109} // namespace dhcp
4110} // namespace isc
A generic exception that is thrown if a parameter given to a method is considered invalid in that con...
This is a base class for exceptions thrown from the DNS library module.
virtual const char * what() const
Returns a C-style character string of the cause of the exception.
A generic exception that is thrown when an unexpected error condition occurs.
DHCPv4 and DHCPv6 allocation engine.
Definition: alloc_engine.h:63
boost::shared_ptr< ClientContext4 > ClientContext4Ptr
Pointer to the ClientContext4.
Implementation of the mechanisms to control the use of the Configuration Backends by the DHCPv4 serve...
Definition: cb_ctl_dhcp4.h:26
@ USE_ROUTING
Server uses routing to determine the right interface to send response.
Definition: cfg_iface.h:147
@ SOCKET_UDP
Datagram socket, i.e. IP/UDP socket.
Definition: cfg_iface.h:138
Configuration Manager.
Definition: cfgmgr.h:70
D2ClientMgr & getD2ClientMgr()
Fetches the DHCP-DDNS manager.
Definition: cfgmgr.cc:66
static CfgMgr & instance()
returns a single instance of Configuration Manager
Definition: cfgmgr.cc:25
SrvConfigPtr getCurrentCfg()
Returns a pointer to the current configuration.
Definition: cfgmgr.cc:161
static SubnetSelector initSelector(const Pkt4Ptr &query)
Build selector from a client's message.
Container for storing client class names.
Definition: classify.h:43
void insert(const ClientClass &class_name)
Insert an element.
Definition: classify.h:62
std::list< ClientClass >::const_iterator const_iterator
Type of iterators.
Definition: classify.h:47
bool empty() const
Check if classes is empty.
Definition: classify.h:73
std::string toText(const std::string &separator=", ") const
Returns all class names as text.
Definition: classify.cc:40
const_iterator cbegin() const
Iterator to the first element.
Definition: classify.h:86
const_iterator cend() const
Iterator to the past the end element.
Definition: classify.h:91
Client race avoidance RAII handler.
bool tryLock(Pkt4Ptr query, ContinuationPtr cont=ContinuationPtr())
Tries to acquires a client.
Holds Client identifier or client IPv4 address.
Definition: duid.h:111
static std::string getDBVersion()
Local version of getDBVersion() class method.
ReplaceClientNameMode
Defines the client name replacement modes.
Definition: d2_client_cfg.h:75
D2ClientMgr isolates Kea from the details of being a D2 client.
Definition: d2_client_mgr.h:80
std::string generateFqdn(const asiolink::IOAddress &address, const DdnsParams &ddns_params, const bool trailing_dot=true) const
Builds a FQDN based on the configuration and given IP address.
bool ddnsEnabled()
Convenience method for checking if DHCP-DDNS is enabled.
void startSender(D2ClientErrorHandler error_handler, isc::asiolink::IOService &io_service)
Enables sending NameChangeRequests to kea-dhcp-ddns.
void getUpdateDirections(const T &fqdn_resp, bool &forward, bool &reverse)
Get directional update flags based on server FQDN flags.
void suspendUpdates()
Suspends sending requests.
void adjustDomainName(const T &fqdn, T &fqdn_resp, const DdnsParams &ddns_params)
Set server FQDN name based on configuration and a given FQDN.
void stopSender()
Disables sending NameChangeRequests to kea-dhcp-ddns.
void adjustFqdnFlags(const T &fqdn, T &fqdn_resp, const DdnsParams &ddns_params)
Set server FQDN flags based on configuration and a given FQDN.
std::string qualifyName(const std::string &partial_name, const DdnsParams &ddns_params, const bool trailing_dot) const
Adds a qualifying suffix to a given domain name.
Convenience container for conveying DDNS behavioral parameters It is intended to be created per Packe...
Definition: srv_config.h:46
bool getUpdateOnRenew() const
Returns whether or not DNS should be updated when leases renew.
Definition: srv_config.cc:1002
bool getEnableUpdates() const
Returns whether or not DHCP DDNS updating is enabled.
Definition: srv_config.cc:912
void close()
Close communication socket.
Definition: dhcp4o6_ipc.cc:118
static Dhcp4to6Ipc & instance()
Returns pointer to the sole instance of Dhcp4to6Ipc.
Definition: dhcp4to6_ipc.cc:32
DHCPv4 message exchange.
Definition: dhcp4_srv.h:62
AllocEngine::ClientContext4Ptr getContext() const
Returns the copy of the context for the Allocation engine.
Definition: dhcp4_srv.h:111
void deleteResponse()
Removes the response message by resetting the pointer to NULL.
Definition: dhcp4_srv.h:106
Pkt4Ptr getQuery() const
Returns the pointer to the query from the client.
Definition: dhcp4_srv.h:94
static void classifyByVendor(const Pkt4Ptr &pkt)
Assign class using vendor-class-identifier option.
Definition: dhcp4_srv.cc:538
void initResponse()
Initializes the instance of the response message.
Definition: dhcp4_srv.cc:270
void setReservedMessageFields()
Sets reserved values of siaddr, sname and file in the server's response.
Definition: dhcp4_srv.cc:516
CfgOptionList & getCfgOptionList()
Returns the configured option list (non-const version)
Definition: dhcp4_srv.h:116
Pkt4Ptr getResponse() const
Returns the pointer to the server's response.
Definition: dhcp4_srv.h:101
static void setReservedClientClasses(AllocEngine::ClientContext4Ptr context)
Assigns classes retrieved from host reservation database.
Definition: dhcp4_srv.cc:491
void initResponse4o6()
Initializes the DHCPv6 part of the response message.
Definition: dhcp4_srv.cc:296
static void classifyPacket(const Pkt4Ptr &pkt)
Assigns incoming packet to zero or more classes.
Definition: dhcp4_srv.cc:550
Dhcpv4Exchange(const AllocEnginePtr &alloc_engine, const Pkt4Ptr &query, const Subnet4Ptr &subnet, bool &drop)
Constructor.
Definition: dhcp4_srv.cc:147
void conditionallySetReservedClientClasses()
Assigns classes retrieved from host reservation database if they haven't been yet set.
Definition: dhcp4_srv.cc:502
int run()
Main server processing loop.
Definition: dhcp4_srv.cc:933
void declineLease(const Lease4Ptr &lease, const Pkt4Ptr &decline, AllocEngine::ClientContext4Ptr &context)
Marks lease as declined.
Definition: dhcp4_srv.cc:3329
void classifyPacket(const Pkt4Ptr &pkt)
Assigns incoming packet to zero or more classes.
Definition: dhcp4_srv.cc:3760
void appendRequestedVendorOptions(Dhcpv4Exchange &ex)
Appends requested vendor options as requested by client.
Definition: dhcp4_srv.cc:1761
void adjustIfaceData(Dhcpv4Exchange &ex)
Set IP/UDP and interface parameters for the DHCPv4 response.
Definition: dhcp4_srv.cc:2686
void run_one()
Main server processing step.
Definition: dhcp4_srv.cc:973
static uint16_t checkRelayPort(const Dhcpv4Exchange &ex)
Check if the relay port RAI sub-option was set in the query.
Definition: dhcp4_srv.cc:2673
bool acceptDirectRequest(const Pkt4Ptr &query) const
Check if a message sent by directly connected client should be accepted or discarded.
Definition: dhcp4_srv.cc:3506
virtual ~Dhcpv4Srv()
Destructor. Used during DHCPv4 service shutdown.
Definition: dhcp4_srv.cc:673
virtual Pkt4Ptr receivePacket(int timeout)
dummy wrapper around IfaceMgr::receive4
Definition: dhcp4_srv.cc:923
void processPacketAndSendResponseNoThrow(Pkt4Ptr &query)
Process a single incoming DHCPv4 packet and sends the response.
Definition: dhcp4_srv.cc:1045
static void appendServerID(Dhcpv4Exchange &ex)
Adds server identifier option to the server's response.
Definition: dhcp4_srv.cc:1591
void postAllocateNameUpdate(const AllocEngine::ClientContext4Ptr &ctx, const Lease4Ptr &lease, const Pkt4Ptr &query, const Pkt4Ptr &resp, bool client_name_changed)
Update client name and DNS flags in the lease and response.
Definition: dhcp4_srv.cc:2567
void processDhcp4QueryAndSendResponse(Pkt4Ptr &query, Pkt4Ptr &rsp, bool allow_packet_park)
Process a single incoming DHCPv4 query.
Definition: dhcp4_srv.cc:1241
void startD2()
Starts DHCP_DDNS client IO if DDNS updates are enabled.
Definition: dhcp4_srv.cc:3927
bool accept(const Pkt4Ptr &query) const
Checks whether received message should be processed or discarded.
Definition: dhcp4_srv.cc:3478
static int getHookIndexBuffer4Receive()
Returns the index for "buffer4_receive" hook point.
Definition: dhcp4_srv.cc:4065
Pkt4Ptr processRequest(Pkt4Ptr &request, AllocEngine::ClientContext4Ptr &context)
Processes incoming REQUEST and returns REPLY response.
Definition: dhcp4_srv.cc:3063
static void processStatsReceived(const Pkt4Ptr &query)
Class methods for DHCPv4-over-DHCPv6 handler.
Definition: dhcp4_srv.cc:3990
static int getHookIndexPkt4Send()
Returns the index for "pkt4_send" hook point.
Definition: dhcp4_srv.cc:4081
void processDecline(Pkt4Ptr &decline, AllocEngine::ClientContext4Ptr &context)
Process incoming DHCPDECLINE messages.
Definition: dhcp4_srv.cc:3256
Dhcpv4Srv(uint16_t server_port=DHCP4_SERVER_PORT, uint16_t client_port=0, const bool use_bcast=true, const bool direct_response_desired=true)
Default constructor.
Definition: dhcp4_srv.cc:611
static int getHookIndexSubnet4Select()
Returns the index for "subnet4_select" hook point.
Definition: dhcp4_srv.cc:4073
static void processStatsSent(const Pkt4Ptr &response)
Updates statistics for transmitted packets.
Definition: dhcp4_srv.cc:4039
void shutdown() override
Instructs the server to shut down.
Definition: dhcp4_srv.cc:713
static int getHookIndexLease4Release()
Returns the index for "lease4_release" hook point.
Definition: dhcp4_srv.cc:4077
void adjustRemoteAddr(Dhcpv4Exchange &ex)
Sets remote addresses for outgoing packet.
Definition: dhcp4_srv.cc:2774
void processDhcp4Query(Pkt4Ptr &query, Pkt4Ptr &rsp, bool allow_packet_park)
Process a single incoming DHCPv4 query.
Definition: dhcp4_srv.cc:1260
static int getHookIndexPkt4Receive()
Returns the index for "pkt4_receive" hook point.
Definition: dhcp4_srv.cc:4069
void assignLease(Dhcpv4Exchange &ex)
Assigns a lease and appends corresponding options.
Definition: dhcp4_srv.cc:2240
asiolink::IOServicePtr & getIOService()
Returns pointer to the IO service used by the server.
Definition: dhcp4_srv.h:292
void setFixedFields(Dhcpv4Exchange &ex)
Sets fixed fields of the outgoing packet.
Definition: dhcp4_srv.cc:2875
void appendBasicOptions(Dhcpv4Exchange &ex)
Append basic options if they are not present.
Definition: dhcp4_srv.cc:1885
void sendResponseNoThrow(hooks::CalloutHandlePtr &callout_handle, Pkt4Ptr &query, Pkt4Ptr &rsp)
Process an unparked DHCPv4 packet and sends the response.
Definition: dhcp4_srv.cc:1418
void processClientName(Dhcpv4Exchange &ex)
Processes Client FQDN and Hostname Options sent by a client.
Definition: dhcp4_srv.cc:1931
boost::shared_ptr< AllocEngine > alloc_engine_
Allocation Engine.
Definition: dhcp4_srv.h:1107
void requiredClassify(Dhcpv4Exchange &ex)
Assigns incoming packet to zero or more classes (required pass).
Definition: dhcp4_srv.cc:3764
uint16_t client_port_
UDP port number to which server sends all responses.
Definition: dhcp4_srv.h:1097
std::list< std::list< std::string > > jsonPathsToRedact() const final override
Return a list of all paths that contain passwords or secrets for kea-dhcp4.
Definition: dhcp4_srv.cc:4098
static std::string srvidToString(const OptionPtr &opt)
converts server-id to text Converts content of server-id option to a text representation,...
Definition: dhcp4_srv.cc:1571
bool acceptServerId(const Pkt4Ptr &pkt) const
Verifies if the server id belongs to our server.
Definition: dhcp4_srv.cc:3600
static const std::string VENDOR_CLASS_PREFIX
this is a prefix added to the content of vendor-class option
Definition: dhcp4_srv.h:798
Pkt4Ptr processInform(Pkt4Ptr &inform)
Processes incoming DHCPINFORM messages.
Definition: dhcp4_srv.cc:3418
void createNameChangeRequests(const Lease4Ptr &lease, const Lease4Ptr &old_lease, const DdnsParams &ddns_params)
Creates NameChangeRequests which correspond to the lease which has been acquired.
Definition: dhcp4_srv.cc:2213
void appendRequestedOptions(Dhcpv4Exchange &ex)
Appends options requested by client.
Definition: dhcp4_srv.cc:1690
void setPacketStatisticsDefaults()
This function sets statistics related to DHCPv4 packets processing to their initial values.
Definition: dhcp4_srv.cc:663
static std::string getVersion(bool extended)
returns Kea version on stdout and exit.
Definition: dhcp4_srv.cc:3963
isc::dhcp::Subnet4Ptr selectSubnet4o6(const Pkt4Ptr &query, bool &drop, bool sanity_only=false) const
Selects a subnet for a given client's DHCP4o6 packet.
Definition: dhcp4_srv.cc:805
void buildCfgOptionList(Dhcpv4Exchange &ex)
Build the configured option list.
Definition: dhcp4_srv.cc:1615
volatile bool shutdown_
Indicates if shutdown is in progress.
Definition: dhcp4_srv.h:1101
uint16_t server_port_
UDP port number on which server listens.
Definition: dhcp4_srv.h:1094
NetworkStatePtr network_state_
Holds information about disabled DHCP service and/or disabled subnet/network scopes.
Definition: dhcp4_srv.h:1114
void setTeeTimes(const Lease4Ptr &lease, const Subnet4Ptr &subnet, Pkt4Ptr resp)
Adds the T1 and T2 timers to the outbound response as appropriate.
Definition: dhcp4_srv.cc:2634
bool getSendResponsesToSource() const
Returns value of the test_send_responses_to_source_ flag.
Definition: dhcp4_srv.h:452
void processPacketAndSendResponse(Pkt4Ptr &query)
Process a single incoming DHCPv4 packet and sends the response.
Definition: dhcp4_srv.cc:1057
isc::dhcp::Subnet4Ptr selectSubnet(const Pkt4Ptr &query, bool &drop, bool sanity_only=false) const
Selects a subnet for a given client's packet.
Definition: dhcp4_srv.cc:719
virtual void d2ClientErrorHandler(const dhcp_ddns::NameChangeSender::Result result, dhcp_ddns::NameChangeRequestPtr &ncr)
Implements the error handler for DHCP_DDNS IO errors.
Definition: dhcp4_srv.cc:3948
virtual void sendPacket(const Pkt4Ptr &pkt)
dummy wrapper around IfaceMgr::send()
Definition: dhcp4_srv.cc:928
static int getHookIndexBuffer4Send()
Returns the index for "buffer4_send" hook point.
Definition: dhcp4_srv.cc:4085
void stopD2()
Stops DHCP_DDNS client IO if DDNS updates are enabled.
Definition: dhcp4_srv.cc:3939
bool acceptMessageType(const Pkt4Ptr &query) const
Check if received message type is valid for the server to process.
Definition: dhcp4_srv.cc:3544
static void sanityCheck(const Pkt4Ptr &query, RequirementLevel serverid)
Verifies if specified packet meets RFC requirements.
Definition: dhcp4_srv.cc:3719
void processPacket(Pkt4Ptr &query, Pkt4Ptr &rsp, bool allow_packet_park=true)
Process a single incoming DHCPv4 packet.
Definition: dhcp4_srv.cc:1069
void discardPackets()
Discards parked packets Clears the packet parking lots of all packets.
Definition: dhcp4_srv.cc:4093
static int getHookIndexLease4Decline()
Returns the index for "lease4_decline" hook point.
Definition: dhcp4_srv.cc:4089
void processRelease(Pkt4Ptr &release, AllocEngine::ClientContext4Ptr &context)
Processes incoming DHCPRELEASE messages.
Definition: dhcp4_srv.cc:3140
void processPacketPktSend(hooks::CalloutHandlePtr &callout_handle, Pkt4Ptr &query, Pkt4Ptr &rsp)
Executes pkt4_send callout.
Definition: dhcp4_srv.cc:1432
Pkt4Ptr processDiscover(Pkt4Ptr &discover)
Processes incoming DISCOVER and returns response.
Definition: dhcp4_srv.cc:2993
RequirementLevel
defines if certain option may, must or must not appear
Definition: dhcp4_srv.h:250
void processPacketBufferSend(hooks::CalloutHandlePtr &callout_handle, Pkt4Ptr &rsp)
Executes buffer4_send callout and sends the response.
Definition: dhcp4_srv.cc:1498
void deferredUnpack(Pkt4Ptr &query)
Perform deferred option unpacking.
Definition: dhcp4_srv.cc:3856
IdentifierType
Type of the host identifier.
Definition: host.h:307
@ IDENT_HWADDR
Definition: host.h:308
@ IDENT_FLEX
Flexible host identifier.
Definition: host.h:312
@ IDENT_CLIENT_ID
Definition: host.h:311
@ IDENT_CIRCUIT_ID
Definition: host.h:310
std::string getIdentifierAsText() const
Returns host identifier in a textual form.
Definition: host.cc:256
static IfaceMgr & instance()
IfaceMgr is a singleton class.
Definition: iface_mgr.cc:53
bool isDirectResponseSupported() const
Check if packet be sent directly to the client having no address.
Definition: iface_mgr.cc:319
bool send(const Pkt6Ptr &pkt)
Sends an IPv6 packet.
Definition: iface_mgr.cc:1101
void closeSockets()
Closes all open sockets.
Definition: iface_mgr.cc:286
void setMatchingPacketFilter(const bool direct_response_desired=false)
Set Packet Filter object to handle send/receive packets.
uint16_t getSocket(const isc::dhcp::Pkt6Ptr &pkt)
Return most suitable socket for transmitting specified IPv6 packet.
Definition: iface_mgr.cc:1855
static void destroy()
Destroy lease manager.
static LeaseMgr & instance()
Return current lease manager.
virtual Lease4Ptr getLease4(const isc::asiolink::IOAddress &addr) const =0
Returns an IPv4 lease for specified IPv4 address.
virtual bool deleteLease(const Lease4Ptr &lease)=0
Deletes an IPv4 lease.
virtual void updateLease4(const Lease4Ptr &lease4)=0
Updates IPv4 lease.
static OptionDefinitionPtr getOptionDef(const std::string &space, const uint16_t code)
Return the first option definition matching a particular option code.
Definition: libdhcp++.cc:122
static OptionDefinitionPtr getRuntimeOptionDef(const std::string &space, const uint16_t code)
Returns runtime (non-standard) option definition by space and option code.
Definition: libdhcp++.cc:185
static OptionDefinitionPtr getLastResortOptionDef(const std::string &space, const uint16_t code)
Returns last resort option definition by space and option code.
Definition: libdhcp++.cc:245
static std::string getDBVersion()
Local version of getDBVersion() class method.
static std::string getDBVersion()
Local version of getDBVersion() class method.
Holds information about DHCP service enabling status.
Definition: network_state.h:70
DHCPv4 Option class for handling list of IPv4 addresses.
std::vector< isc::asiolink::IOAddress > AddressContainer
Defines a collection of IPv4 addresses.
Represents DHCPv4 Client FQDN Option (code 81).
bool getFlag(const uint8_t flag) const
Checks if the specified flag of the DHCPv4 Client FQDN Option is set.
void setDomainName(const std::string &domain_name, const DomainNameType domain_name_type)
Set new domain-name.
void setFlag(const uint8_t flag, const bool set)
Modifies the value of the specified DHCPv4 Client Fqdn Option flag.
static const uint8_t FLAG_E
Bit E.
virtual std::string toText(int indent=0) const
Returns string representation of the option.
Option with defined data fields represented as buffers that can be accessed using data field index.
Definition: option_custom.h:32
static unsigned int getLabelCount(const std::string &text_name)
Return the number of labels in the Name.
Option descriptor.
Definition: cfg_option.h:42
OptionPtr option_
Option instance.
Definition: cfg_option.h:45
Forward declaration to OptionIntArray.
const std::vector< T > & getValues() const
Return collection of option values.
Forward declaration to OptionInt.
Definition: option_int.h:49
Class which represents an option carrying a single string value.
Definition: option_string.h:28
This class represents vendor-specific information option.
Definition: option_vendor.h:30
uint32_t getVendorId() const
Returns enterprise identifier.
Definition: option_vendor.h:84
static const size_t OPTION4_HDR_LEN
length of the usual DHCPv4 option header (there are exceptions)
Definition: option.h:76
static std::string getDBVersion()
Local version of getDBVersion() class method.
Represents DHCPv4 packet.
Definition: pkt4.h:37
static const uint16_t FLAG_BROADCAST_MASK
Mask for the value of flags field in the DHCPv4 message to check whether client requested broadcast r...
Definition: pkt4.h:54
Represents DHCPv4-over-DHCPv6 packet.
Definition: pkt4o6.h:30
Represents a DHCPv6 packet.
Definition: pkt6.h:44
@ RELAY_GET_FIRST
Definition: pkt6.h:77
An exception that is thrown if a DHCPv6 protocol violation occurs while processing a message (e....
Definition: utils.h:17
RAII object enabling copying options retrieved from the packet.
Definition: pkt.h:40
Exception thrown when a call to select is interrupted by a signal.
Definition: iface_mgr.h:55
Exception thrown during option unpacking This exception is thrown when an error has occurred,...
Definition: option.h:51
Result
Defines the outcome of an asynchronous NCR send.
Definition: ncr_io.h:476
Wrapper class around callout handle which automatically resets handle's state.
int getExitValue()
Fetches the exit value.
Definition: daemon.h:220
Statistics Manager class.
static StatsMgr & instance()
Statistics Manager accessor method.
RAII class creating a critical section.
Read mutex RAII handler.
Contains declarations for loggers used by the DHCPv4 server component.
Dhcp4Hooks Hooks
Definition: dhcp4_srv.cc:142
Defines the Dhcp4o6Ipc class.
@ D6O_INTERFACE_ID
Definition: dhcp6.h:38
@ DHCPV6_DHCPV4_RESPONSE
Definition: dhcp6.h:228
#define DOCSIS3_V4_ORO
#define VENDOR_ID_CABLE_LABS
#define isc_throw(type, stream)
A shortcut macro to insert known values into exception arguments.
boost::shared_ptr< OptionUint8Array > OptionUint8ArrayPtr
OptionInt< uint32_t > OptionUint32
Definition: option_int.h:34
boost::shared_ptr< OptionUint32 > OptionUint32Ptr
Definition: option_int.h:35
void setValue(const std::string &name, const int64_t value)
Records absolute integer observation.
void addValue(const std::string &name, const int64_t value)
Records incremental integer observation.
An abstract API for lease database.
#define LOG_ERROR(LOGGER, MESSAGE)
Macro to conveniently test error output and log it.
Definition: macros.h:32
#define LOG_INFO(LOGGER, MESSAGE)
Macro to conveniently test info output and log it.
Definition: macros.h:20
#define LOG_WARN(LOGGER, MESSAGE)
Macro to conveniently test warn output and log it.
Definition: macros.h:26
#define LOG_DEBUG(LOGGER, LEVEL, MESSAGE)
Macro to conveniently test debug output and log it.
Definition: macros.h:14
const char *const config_report[]
Definition: config_report.h:15
boost::shared_ptr< NameChangeRequest > NameChangeRequestPtr
Defines a pointer to a NameChangeRequest.
Definition: ncr_msg.h:212
const isc::log::MessageID DHCP4_BUFFER_RECEIVE_FAIL
isc::log::Logger ddns4_logger(DHCP4_DDNS_LOGGER_NAME)
Logger for Hostname or FQDN processing.
Definition: dhcp4_log.h:115
const isc::log::MessageID DHCP4_PACKET_DROP_0004
const isc::log::MessageID DHCP4_SRV_DHCP4O6_ERROR
const isc::log::MessageID DHCP4_RELEASE_EXCEPTION
const isc::log::MessageID DHCP4_SUBNET_DATA
const isc::log::MessageID DHCP4_INIT_REBOOT
const isc::log::MessageID DHCP4_HOOK_PACKET_SEND_SKIP
const isc::log::MessageID DHCP4_FLEX_ID
const isc::log::MessageID DHCP4_PACKET_DROP_0003
const isc::log::MessageID DHCP4_DEFERRED_OPTION_UNPACK_FAIL
const isc::log::MessageID DHCP4_PACKET_DROP_0001
const isc::log::MessageID DHCP4_QUERY_DATA
boost::shared_ptr< Subnet4 > Subnet4Ptr
A pointer to a Subnet4 object.
Definition: subnet.h:522
const isc::log::MessageID DHCP4_NO_LEASE_INIT_REBOOT
const isc::log::MessageID DHCP4_INFORM_DIRECT_REPLY
boost::shared_ptr< Lease4Collection > Lease4CollectionPtr
A shared pointer to the collection of IPv4 leases.
Definition: lease.h:490
void queueNCR(const NameChangeType &chg_type, const Lease4Ptr &lease)
Creates name change request from the DHCPv4 lease.
const isc::log::MessageID DHCP4_CLIENT_FQDN_PROCESS
const isc::log::MessageID DHCP4_DEFERRED_OPTION_MISSING
const isc::log::MessageID EVAL_RESULT
Definition: eval_messages.h:51
const isc::log::MessageID DHCP4_HOOK_SUBNET4_SELECT_DROP
@ DHO_SUBNET_MASK
Definition: dhcp4.h:70
@ DHO_ROUTERS
Definition: dhcp4.h:72
@ DHO_DOMAIN_NAME
Definition: dhcp4.h:84
@ DHO_DOMAIN_NAME_SERVERS
Definition: dhcp4.h:75
@ DHO_VENDOR_CLASS_IDENTIFIER
Definition: dhcp4.h:129
@ DHO_DHCP_REBINDING_TIME
Definition: dhcp4.h:128
@ DHO_DHCP_SERVER_IDENTIFIER
Definition: dhcp4.h:123
@ DHO_HOST_NAME
Definition: dhcp4.h:81
@ DHO_DHCP_CLIENT_IDENTIFIER
Definition: dhcp4.h:130
@ DHO_DHCP_REQUESTED_ADDRESS
Definition: dhcp4.h:119
@ DHO_DHCP_AGENT_OPTIONS
Definition: dhcp4.h:151
@ DHO_SUBNET_SELECTION
Definition: dhcp4.h:180
@ DHO_DHCP_PARAMETER_REQUEST_LIST
Definition: dhcp4.h:124
@ DHO_FQDN
Definition: dhcp4.h:150
@ DHO_VIVSO_SUBOPTIONS
Definition: dhcp4.h:187
@ DHO_DHCP_RENEWAL_TIME
Definition: dhcp4.h:127
@ DHO_DHCP_LEASE_TIME
Definition: dhcp4.h:120
const isc::log::MessageID DHCP4_PACKET_DROP_0008
const isc::log::MessageID DHCP4_HOOK_LEASES4_COMMITTED_DROP
const isc::log::MessageID DHCP4_RELEASE_FAIL_WRONG_CLIENT
const isc::log::MessageID DHCP4_LEASE_ADVERT
const isc::log::MessageID DHCP4_HOOK_BUFFER_RCVD_DROP
boost::shared_ptr< OptionCustom > OptionCustomPtr
A pointer to the OptionCustom object.
const isc::log::MessageID DHCP4_HOOK_PACKET_RCVD_SKIP
const int DBG_DHCP4_BASIC_DATA
Debug level used to log the traces with some basic data.
Definition: dhcp4_log.h:45
const isc::log::MessageID DHCP4_LEASE_ALLOC
const int DBG_DHCP4_DETAIL
Debug level used to trace detailed errors.
Definition: dhcp4_log.h:53
boost::shared_ptr< Pkt4 > Pkt4Ptr
A pointer to Pkt4 object.
Definition: pkt4.h:544
isc::log::Logger lease4_logger(DHCP4_LEASE_LOGGER_NAME)
Logger for lease allocation logic.
Definition: dhcp4_log.h:120
const isc::log::MessageID DHCP4_NCR_CREATION_FAILED
isc::log::Logger options4_logger(DHCP4_OPTIONS_LOGGER_NAME)
Logger for options parser.
Definition: dhcp4_log.h:109
const isc::log::MessageID DHCP4_HOOK_SUBNET4_SELECT_SKIP
const int DBG_DHCP4_DETAIL_DATA
This level is used to log the contents of packets received and sent.
Definition: dhcp4_log.h:56
const isc::log::MessageID DHCP4_PACKET_PACK
boost::shared_ptr< AllocEngine > AllocEnginePtr
A pointer to the AllocEngine object.
ContinuationPtr makeContinuation(Continuation &&cont)
Continuation factory.
const isc::log::MessageID DHCP4_DECLINE_FAIL
const isc::log::MessageID DHCP4_LEASE_REUSE
boost::shared_ptr< const CfgHostOperations > ConstCfgHostOperationsPtr
Pointer to the const object.
boost::shared_ptr< CfgIface > CfgIfacePtr
A pointer to the CfgIface .
Definition: cfg_iface.h:387
const isc::log::MessageID DHCP4_PACKET_PACK_FAIL
boost::shared_ptr< ClientClassDef > ClientClassDefPtr
a pointer to an ClientClassDef
const isc::log::MessageID DHCP4_DDNS_REQUEST_SEND_FAILED
const isc::log::MessageID DHCP4_GENERATE_FQDN
const isc::log::MessageID DHCP4_CLASS_ASSIGNED
const isc::log::MessageID DHCP4_PACKET_PROCESS_STD_EXCEPTION
boost::shared_ptr< SrvConfig > SrvConfigPtr
Non-const pointer to the SrvConfig.
Definition: srv_config.h:1044
const isc::log::MessageID DHCP4_RESPONSE_HOSTNAME_DATA
const isc::log::MessageID DHCP4_BUFFER_WAIT_SIGNAL
const isc::log::MessageID DHCP4_HOOK_LEASE4_RELEASE_SKIP
const isc::log::MessageID DHCP4_POST_ALLOCATION_NAME_UPDATE_FAIL
const isc::log::MessageID DHCP4_PACKET_NAK_0001
const isc::log::MessageID DHCP4_HOOK_DECLINE_SKIP
const isc::log::MessageID DHCP4_DECLINE_LEASE_MISMATCH
const isc::log::MessageID DHCP4_SRV_UNLOAD_LIBRARIES_ERROR
const isc::log::MessageID DHCP4_RESPONSE_HOSTNAME_GENERATE
boost::shared_ptr< HWAddr > HWAddrPtr
Shared pointer to a hardware address structure.
Definition: hwaddr.h:154
const isc::log::MessageID DHCP4_PACKET_DROP_0013
const isc::log::MessageID DHCP4_PACKET_QUEUE_FULL
const isc::log::MessageID DHCP4_PACKET_DROP_0009
const isc::log::MessageID DHCP4_PACKET_RECEIVED
boost::shared_ptr< Pkt4o6 > Pkt4o6Ptr
A pointer to Pkt4o6 object.
Definition: pkt4o6.h:82
const isc::log::MessageID DHCP4_BUFFER_UNPACK
const isc::log::MessageID DHCP4_CLIENT_HOSTNAME_DATA
const isc::log::MessageID DHCP4_PACKET_SEND_FAIL
std::pair< OptionContainerPersistIndex::const_iterator, OptionContainerPersistIndex::const_iterator > OptionContainerPersistRange
Pair of iterators to represent the range of options having the same persistency flag.
Definition: cfg_option.h:286
boost::shared_ptr< OptionDefinition > OptionDefinitionPtr
Pointer to option definition object.
boost::shared_ptr< Option4ClientFqdn > Option4ClientFqdnPtr
A pointer to the Option4ClientFqdn object.
const isc::log::MessageID DHCP4_CLIENTID_IGNORED_FOR_LEASES
const isc::log::MessageID DHCP4_CLIENT_NAME_PROC_FAIL
const isc::log::MessageID DHCP4_CLIENT_HOSTNAME_PROCESS
const isc::log::MessageID DHCP4_SRV_CONSTRUCT_ERROR
boost::shared_ptr< Expression > ExpressionPtr
Definition: token.h:30
const isc::log::MessageID DHCP4_RELEASE_FAIL
const isc::log::MessageID DHCP4_RELEASE_FAIL_NO_LEASE
const isc::log::MessageID DHCP4_CLIENT_HOSTNAME_MALFORMED
boost::shared_ptr< Pool > PoolPtr
a pointer to either IPv4 or IPv6 Pool
Definition: pool.h:505
boost::shared_ptr< OptionString > OptionStringPtr
Pointer to the OptionString object.
isc::log::Logger bad_packet4_logger(DHCP4_BAD_PACKET_LOGGER_NAME)
Logger for rejected packets.
Definition: dhcp4_log.h:97
isc::hooks::CalloutHandlePtr getCalloutHandle(const T &pktptr)
CalloutHandle Store.
const isc::log::MessageID DHCP4_PACKET_DROP_0006
const int DBG_DHCP4_BASIC
Debug level used to trace basic operations within the code.
Definition: dhcp4_log.h:33
boost::shared_ptr< ClientClassDictionary > ClientClassDictionaryPtr
Defines a pointer to a ClientClassDictionary.
const isc::log::MessageID DHCP4_SRV_D2STOP_ERROR
const isc::log::MessageID DHCP4_RESPONSE_FQDN_DATA
boost::shared_ptr< ClientId > ClientIdPtr
Shared pointer to a Client ID.
Definition: duid.h:103
boost::shared_ptr< Continuation > ContinuationPtr
Define the type of shared pointers to continuations.
const isc::log::MessageID DHCP4_DECLINE_LEASE_NOT_FOUND
boost::shared_ptr< OptionContainer > OptionContainerPtr
Pointer to the OptionContainer object.
Definition: cfg_option.h:272
const isc::log::MessageID DHCP4_CLASS_UNTESTABLE
boost::shared_ptr< ClientClassDefList > ClientClassDefListPtr
Defines a pointer to a ClientClassDefList.
const isc::log::MessageID DHCP4_PACKET_DROP_0005
const isc::log::MessageID DHCP4_SUBNET_DYNAMICALLY_CHANGED
const isc::log::MessageID DHCP4_SHUTDOWN_REQUEST
@ DHCPREQUEST
Definition: dhcp4.h:232
@ DHCP_TYPES_EOF
Definition: dhcp4.h:248
@ DHCPOFFER
Definition: dhcp4.h:231
@ DHCPDECLINE
Definition: dhcp4.h:233
@ DHCPNAK
Definition: dhcp4.h:235
@ DHCPRELEASE
Definition: dhcp4.h:236
@ DHCPDISCOVER
Definition: dhcp4.h:230
@ DHCP_NOTYPE
Message Type option missing.
Definition: dhcp4.h:229
@ DHCPINFORM
Definition: dhcp4.h:237
@ DHCPACK
Definition: dhcp4.h:234
const char *const * dhcp4_config_report
Definition: dhcp4_srv.cc:3960
const isc::log::MessageID DHCP4_PACKET_NAK_0003
const isc::log::MessageID DHCP4_TESTING_MODE_SEND_TO_SOURCE_ENABLED
boost::shared_ptr< const CfgSubnets4 > ConstCfgSubnets4Ptr
Const pointer.
Definition: cfg_subnets4.h:335
const isc::log::MessageID DHCP4_BUFFER_RECEIVED
bool evaluateBool(const Expression &expr, Pkt &pkt)
Evaluate a RPN expression for a v4 or v6 packet and return a true or false decision.
Definition: evaluate.cc:14
const isc::log::MessageID DHCP4_SUBNET_SELECTION_FAILED
boost::shared_ptr< const Host > ConstHostPtr
Const pointer to the Host object.
Definition: host.h:788
const isc::log::MessageID DHCP4_RESPONSE_DATA
isc::log::Logger packet4_logger(DHCP4_PACKET_LOGGER_NAME)
Logger for processed packets.
Definition: dhcp4_log.h:103
OptionContainer::nth_index< 2 >::type OptionContainerPersistIndex
Type of the index #2 - option persistency flag.
Definition: cfg_option.h:281
const isc::log::MessageID DHCP4_DECLINE_LEASE
const isc::log::MessageID DHCP4_NCR_CREATE
const isc::log::MessageID DHCP4_PACKET_SEND
const isc::log::MessageID DHCP4_RELEASE
const isc::log::MessageID DHCP4_HOOK_BUFFER_RCVD_SKIP
boost::shared_ptr< Pkt6 > Pkt6Ptr
A pointer to Pkt6 packet.
Definition: pkt6.h:28
std::vector< uint8_t > OptionBuffer
buffer types used in DHCP code.
Definition: option.h:24
const isc::log::MessageID DHCP4_OPEN_SOCKET
const isc::log::MessageID DHCP4_PACKET_DROP_0007
boost::shared_ptr< CfgSharedNetworks4 > CfgSharedNetworks4Ptr
Pointer to the configuration of IPv4 shared networks.
const isc::log::MessageID DHCP4_HOOK_PACKET_SEND_DROP
const isc::log::MessageID DHCP4_RESERVED_HOSTNAME_ASSIGNED
isc::log::Logger dhcp4_logger(DHCP4_APP_LOGGER_NAME)
Base logger for DHCPv4 server.
Definition: dhcp4_log.h:90
bool isClientClassBuiltIn(const ClientClass &client_class)
Check if a client class name is builtin.
const isc::log::MessageID DHCP4_PACKET_NAK_0002
const int DBG_DHCP4_HOOKS
Debug level used to trace hook related operations.
Definition: dhcp4_log.h:36
boost::shared_ptr< SharedNetwork4 > SharedNetwork4Ptr
Pointer to SharedNetwork4 object.
std::vector< Lease4Ptr > Lease4Collection
A collection of IPv4 leases.
Definition: lease.h:487
const isc::log::MessageID DHCP4_HOOK_BUFFER_SEND_SKIP
const isc::log::MessageID DHCP4_PACKET_PROCESS_EXCEPTION
const isc::log::MessageID DHCP4_PACKET_OPTIONS_SKIPPED
const isc::log::MessageID DHCP4_EMPTY_HOSTNAME
const isc::log::MessageID DHCP4_SUBNET_SELECTED
const isc::log::MessageID DHCP4_PACKET_DROP_0010
boost::shared_ptr< Lease4 > Lease4Ptr
Pointer to a Lease4 structure.
Definition: lease.h:283
const isc::log::MessageID DHCP4_CLASS_UNCONFIGURED
boost::shared_ptr< Option > OptionPtr
Definition: option.h:36
const int DBG_DHCP4_START
Debug level used to log information during server startup.
Definition: dhcp4_log.h:24
const isc::log::MessageID DHCP4_CLASS_UNDEFINED
const isc::log::MessageID DHCP4_HOOK_LEASES4_COMMITTED_PARK
std::list< ConstCfgOptionPtr > CfgOptionList
Const pointer list.
Definition: cfg_option.h:712
boost::shared_ptr< const CfgOption > ConstCfgOptionPtr
Const pointer.
Definition: cfg_option.h:709
const isc::log::MessageID DHCP4_PACKET_NAK_0004
const isc::log::MessageID DHCP4_CLIENT_FQDN_DATA
const isc::log::MessageID DHCP4_PACKET_DROP_0002
isc::log::Logger hooks_logger("hooks")
Hooks Logger.
Definition: hooks_log.h:37
boost::shared_ptr< CalloutHandle > CalloutHandlePtr
A shared pointer to a CalloutHandle object.
const int DBGLVL_TRACE_BASIC
Trace basic operations.
Definition: log_dbglevels.h:69
const int DBGLVL_PKT_HANDLING
This debug level is reserved for logging the details of packet handling, such as dropping the packet ...
Definition: log_dbglevels.h:58
boost::shared_ptr< StringSanitizer > StringSanitizerPtr
Definition: strutil.h:348
string trim(const string &instring)
Trim Leading and Trailing Spaces.
Definition: strutil.cc:53
Definition: edns.h:19
Defines the logger used by the top-level component of kea-lfc.
#define DHCP4_OPTION_SPACE
global std option spaces
Context information for the DHCPv4 lease allocation.
static std::string lifetimeToText(uint32_t lifetime)
Print lifetime.
Definition: lease.cc:29
@ TYPE_V4
IPv4 lease.
Definition: lease.h:54
structure that describes a single relay information
Definition: pkt6.h:85
isc::asiolink::IOAddress linkaddr_
fixed field in relay-forw/relay-reply
Definition: pkt6.h:96
Subnet selector used to specify parameters used to select a subnet.
asiolink::IOAddress local_address_
Address on which the message was received.
bool dhcp4o6_
Specifies if the packet is DHCP4o6.
asiolink::IOAddress option_select_
RAI link select or subnet select option.
std::string iface_name_
Name of the interface on which the message was received.
asiolink::IOAddress ciaddr_
ciaddr from the client's message.
ClientClasses client_classes_
Classes that the client belongs to.
asiolink::IOAddress remote_address_
Source address of the message.
OptionPtr interface_id_
Interface id option.
asiolink::IOAddress first_relay_linkaddr_
First relay link address.
asiolink::IOAddress giaddr_
giaddr from the client's message.