Kea 3.3.0
dhcp4_srv.cc
Go to the documentation of this file.
1// Copyright (C) 2011-2026 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
11#include <asiolink/io_address.h>
12#include <asiolink/io_service.h>
14#include <cc/data.h>
17#include <dhcp/classify.h>
18#include <dhcp/dhcp4.h>
20#include <dhcp/duid.h>
21#include <dhcp/hwaddr.h>
22#include <dhcp/iface_mgr.h>
23#include <dhcp/libdhcp++.h>
24#include <dhcp/option.h>
27#include <dhcp/option_custom.h>
30#include <dhcp/option_int.h>
32#include <dhcp/option_string.h>
33#include <dhcp/option_vendor.h>
35#include <dhcp/pkt.h>
36#include <dhcp/pkt4.h>
37#include <dhcp/pkt4o6.h>
38#include <dhcp/socket_info.h>
41#include <dhcp4/dhcp4_log.h>
42#include <dhcp4/dhcp4_srv.h>
43#include <dhcp4/dhcp4to6_ipc.h>
44#include <dhcp_ddns/ncr_io.h>
45#include <dhcp_ddns/ncr_msg.h>
51#include <dhcpsrv/cfg_globals.h>
53#include <dhcpsrv/cfg_iface.h>
54#include <dhcpsrv/cfg_option.h>
57#include <dhcpsrv/cfgmgr.h>
62#include <dhcpsrv/host.h>
64#include <dhcpsrv/host_mgr.h>
65#include <dhcpsrv/lease.h>
70#include <dhcpsrv/pool.h>
73#include <dhcpsrv/srv_config.h>
74#include <dhcpsrv/subnet.h>
75#include <dhcpsrv/subnet_id.h>
77#include <dhcpsrv/utils.h>
78#include <eval/evaluate.h>
79#include <eval/token.h>
82#include <hooks/hooks_log.h>
83#include <hooks/hooks_manager.h>
84#include <hooks/parking_lots.h>
85#include <hooks/server_hooks.h>
87#include <log/log_dbglevels.h>
88#include <log/log_formatter.h>
89#include <log/logger.h>
90#include <log/macros.h>
91#include <stats/stats_mgr.h>
93#include <util/optional.h>
95#include <util/thread_pool.h>
96#include <util/triplet.h>
97
98#include <algorithm>
99#include <cmath>
100#include <cstdint>
101#include <cstdlib>
102#include <exception>
103#include <functional>
104#include <list>
105#include <map>
106#include <memory>
107#include <set>
108#include <sstream>
109#include <string>
110#include <tuple>
111#include <utility>
112#include <vector>
113
114#include <boost/foreach.hpp>
115#include <boost/pointer_cast.hpp>
116#include <boost/range/adaptor/reversed.hpp>
117#include <boost/shared_ptr.hpp>
118
119using namespace isc;
120using namespace isc::asiolink;
121using namespace isc::cryptolink;
122using namespace isc::data;
123using namespace isc::dhcp;
124using namespace isc::dhcp_ddns;
125using namespace isc::hooks;
126using namespace isc::log;
127using namespace isc::log::interprocess;
128using namespace isc::stats;
129using namespace isc::util;
130using namespace std;
131namespace ph = std::placeholders;
132
133namespace {
134
136struct Dhcp4Hooks {
137 int hook_index_buffer4_receive_;
138 int hook_index_pkt4_receive_;
139 int hook_index_subnet4_select_;
140 int hook_index_leases4_committed_;
141 int hook_index_lease4_release_;
142 int hook_index_pkt4_send_;
143 int hook_index_buffer4_send_;
144 int hook_index_lease4_decline_;
145 int hook_index_host4_identifier_;
146 int hook_index_ddns4_update_;
147 int hook_index_lease4_offer_;
148 int hook_index_lease4_server_decline_;
149
151 Dhcp4Hooks() {
152 hook_index_buffer4_receive_ = HooksManager::registerHook("buffer4_receive");
153 hook_index_pkt4_receive_ = HooksManager::registerHook("pkt4_receive");
154 hook_index_subnet4_select_ = HooksManager::registerHook("subnet4_select");
155 hook_index_leases4_committed_ = HooksManager::registerHook("leases4_committed");
156 hook_index_lease4_release_ = HooksManager::registerHook("lease4_release");
157 hook_index_pkt4_send_ = HooksManager::registerHook("pkt4_send");
158 hook_index_buffer4_send_ = HooksManager::registerHook("buffer4_send");
159 hook_index_lease4_decline_ = HooksManager::registerHook("lease4_decline");
160 hook_index_host4_identifier_ = HooksManager::registerHook("host4_identifier");
161 hook_index_ddns4_update_ = HooksManager::registerHook("ddns4_update");
162 hook_index_lease4_offer_ = HooksManager::registerHook("lease4_offer");
163 hook_index_lease4_server_decline_ = HooksManager::registerHook("lease4_server_decline");
164 }
165};
166
169std::set<std::string> dhcp4_statistics = {
170 "pkt4-received",
171 "pkt4-discover-received",
172 "pkt4-offer-received",
173 "pkt4-request-received",
174 "pkt4-ack-received",
175 "pkt4-nak-received",
176 "pkt4-release-received",
177 "pkt4-decline-received",
178 "pkt4-inform-received",
179 "pkt4-lease-query-received",
180 "pkt4-unknown-received",
181 "pkt4-sent",
182 "pkt4-offer-sent",
183 "pkt4-ack-sent",
184 "pkt4-nak-sent",
185 "pkt4-lease-query-response-unassigned-sent",
186 "pkt4-lease-query-response-unknown-sent",
187 "pkt4-lease-query-response-active-sent",
188 "pkt4-service-disabled",
189 "pkt4-parse-failed",
190 "pkt4-queue-full",
191 "pkt4-duplicate",
192 "pkt4-rfc-violation",
193 "pkt4-admin-filtered",
194 "pkt4-not-for-us",
195 "pkt4-processing-failed",
196 "pkt4-limit-exceeded",
197 "pkt4-receive-drop",
198 "v4-allocation-fail",
199 "v4-allocation-fail-shared-network",
200 "v4-allocation-fail-subnet",
201 "v4-allocation-fail-no-pools",
202 "v4-allocation-fail-classes",
203 "v4-reservation-conflicts",
204 "v4-lease-reuses",
205};
206
207} // end of anonymous namespace
208
209// Declare a Hooks object. As this is outside any function or method, it
210// will be instantiated (and the constructor run) when the module is loaded.
211// As a result, the hook indexes will be defined before any method in this
212// module is called.
213Dhcp4Hooks Hooks;
214
215namespace isc {
216namespace dhcp {
217
219 const Pkt4Ptr& query,
221 const ConstSubnet4Ptr& subnet,
222 bool& drop)
223 : alloc_engine_(alloc_engine), query_(query), resp_(),
224 context_(context), ipv6_only_preferred_(false) {
225
226 if (!alloc_engine_) {
227 isc_throw(BadValue, "alloc_engine value must not be NULL"
228 " when creating an instance of the Dhcpv4Exchange");
229 }
230
231 if (!query_) {
232 isc_throw(BadValue, "query value must not be NULL when"
233 " creating an instance of the Dhcpv4Exchange");
234 }
235
236 // Reset the given context argument.
237 context.reset();
238
239 // Create response message.
240 initResponse();
241 // Select subnet for the query message.
242 context_->subnet_ = subnet;
243
244 // If subnet found, retrieve client identifier which will be needed
245 // for allocations and search for reservations associated with a
246 // subnet/shared network.
248 if (subnet && !context_->early_global_reservations_lookup_) {
249 OptionPtr opt_clientid = query->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
250 if (opt_clientid) {
251 context_->clientid_.reset(new ClientId(opt_clientid->getData()));
252 }
253 }
254
255 if (subnet) {
256 // Find static reservations if not disabled for our subnet.
257 if (subnet->getReservationsInSubnet() ||
258 subnet->getReservationsGlobal()) {
259 // Before we can check for static reservations, we need to prepare a set
260 // of identifiers to be used for this.
261 if (!context_->early_global_reservations_lookup_) {
262 setHostIdentifiers(context_);
263 }
264
265 // Check for static reservations.
266 alloc_engine->findReservation(*context_);
267
268 // Get shared network to see if it is set for a subnet.
269 subnet->getSharedNetwork(sn);
270 }
271 }
272
273 // Global host reservations are independent of a selected subnet. If the
274 // global reservations contain client classes we should use them in case
275 // they are meant to affect pool selection. Also, if the subnet does not
276 // belong to a shared network we can use the reserved client classes
277 // because there is no way our subnet could change. Such classes may
278 // affect selection of a pool within the selected subnet.
279 auto global_host = context_->globalHost();
280 auto current_host = context_->currentHost();
281 if ((!context_->early_global_reservations_lookup_ &&
282 global_host && !global_host->getClientClasses4().empty()) ||
283 (!sn && current_host && !current_host->getClientClasses4().empty())) {
284 // We have already evaluated client classes and some of them may
285 // be in conflict with the reserved classes. Suppose there are
286 // two classes defined in the server configuration: first_class
287 // and second_class and the test for the second_class it looks
288 // like this: "not member('first_class')". If the first_class
289 // initially evaluates to false, the second_class evaluates to
290 // true. If the first_class is now set within the hosts reservations
291 // and we don't remove the previously evaluated second_class we'd
292 // end up with both first_class and second_class evaluated to
293 // true. In order to avoid that, we have to remove the classes
294 // evaluated in the first pass and evaluate them again. As
295 // a result, the first_class set via the host reservation will
296 // replace the second_class because the second_class will this
297 // time evaluate to false as desired.
299 setReservedClientClasses(context_);
300 evaluateClasses(query, false);
301 }
302
303 // Set KNOWN builtin class if something was found, UNKNOWN if not.
304 if (!context_->hosts_.empty()) {
305 query->addClass("KNOWN");
307 .arg(query->getLabel())
308 .arg("KNOWN");
309 } else {
310 query->addClass("UNKNOWN");
312 .arg(query->getLabel())
313 .arg("UNKNOWN");
314 }
315
316 // Perform second pass of classification.
317 evaluateClasses(query, true);
318
319 const ClientClasses& classes = query_->getClasses();
321 .arg(query_->getLabel())
322 .arg(classes.toText());
323
324 // Check the DROP special class.
325 if (query_->inClass("DROP")) {
327 .arg(query_->getHWAddrLabel())
328 .arg(query_->toText());
329 StatsMgr::instance().addValue("pkt4-admin-filtered",
330 static_cast<int64_t>(1));
331 StatsMgr::instance().addValue("pkt4-receive-drop",
332 static_cast<int64_t>(1));
333 drop = true;
334 }
335}
336
337void
339 uint8_t resp_type = 0;
340 switch (getQuery()->getType()) {
341 case DHCPDISCOVER:
342 resp_type = DHCPOFFER;
343 break;
344 case DHCPREQUEST:
345 case DHCPINFORM:
346 resp_type = DHCPACK;
347 break;
348 default:
349 ;
350 }
351 // Only create a response if one is required.
352 if (resp_type > 0) {
353 resp_.reset(new Pkt4(resp_type, getQuery()->getTransid()));
354 copyDefaultFields();
355 copyDefaultOptions();
356
357 if (getQuery()->isDhcp4o6()) {
359 }
360 }
361}
362
363void
365 Pkt4o6Ptr query = boost::dynamic_pointer_cast<Pkt4o6>(getQuery());
366 if (!query) {
367 return;
368 }
369 const Pkt6Ptr& query6 = query->getPkt6();
370 Pkt6Ptr resp6(new Pkt6(DHCPV6_DHCPV4_RESPONSE, query6->getTransid()));
371 // Don't add client-id or server-id
372 // But copy relay info
373 if (!query6->relay_info_.empty()) {
374 resp6->copyRelayInfo(query6);
375 }
376 // Copy interface, and remote address and port
377 resp6->setIface(query6->getIface());
378 resp6->setIndex(query6->getIndex());
379 resp6->setRemoteAddr(query6->getRemoteAddr());
380 resp6->setRemotePort(query6->getRemotePort());
381 resp_.reset(new Pkt4o6(resp_, resp6));
382}
383
384void
385Dhcpv4Exchange::copyDefaultFields() {
386 resp_->setIface(query_->getIface());
387 resp_->setIndex(query_->getIndex());
388
389 // explicitly set this to 0
390 resp_->setSiaddr(IOAddress::IPV4_ZERO_ADDRESS());
391 // ciaddr is always 0, except for the Renew/Rebind state and for
392 // Inform when it may be set to the ciaddr sent by the client.
393 if (query_->getType() == DHCPINFORM) {
394 resp_->setCiaddr(query_->getCiaddr());
395 } else {
396 resp_->setCiaddr(IOAddress::IPV4_ZERO_ADDRESS());
397 }
398 resp_->setHops(query_->getHops());
399
400 // copy MAC address
401 resp_->setHWAddr(query_->getHWAddr());
402
403 // relay address
404 resp_->setGiaddr(query_->getGiaddr());
405
406 // If src/dest HW addresses are used by the packet filtering class
407 // we need to copy them as well. There is a need to check that the
408 // address being set is not-NULL because an attempt to set the NULL
409 // HW would result in exception. If these values are not set, the
410 // the default HW addresses (zeroed) should be generated by the
411 // packet filtering class when creating Ethernet header for
412 // outgoing packet.
413 HWAddrPtr src_hw_addr = query_->getLocalHWAddr();
414 if (src_hw_addr) {
415 resp_->setLocalHWAddr(src_hw_addr);
416 }
417 HWAddrPtr dst_hw_addr = query_->getRemoteHWAddr();
418 if (dst_hw_addr) {
419 resp_->setRemoteHWAddr(dst_hw_addr);
420 }
421
422 // Copy flags from the request to the response per RFC 2131
423 resp_->setFlags(query_->getFlags());
424}
425
426void
427Dhcpv4Exchange::copyDefaultOptions() {
428 // Let's copy client-id to response. See RFC6842.
429 // It is possible to disable RFC6842 to keep backward compatibility
430 bool echo = CfgMgr::instance().getCurrentCfg()->getEchoClientId();
431 OptionPtr client_id = query_->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
432 if (client_id && echo) {
433 resp_->addOption(client_id);
434 }
435
436 // RFC 3011 states about the Subnet Selection Option
437
438 // "Servers configured to support this option MUST return an
439 // identical copy of the option to any client that sends it,
440 // regardless of whether or not the client requests the option in
441 // a parameter request list. Clients using this option MUST
442 // discard DHCPOFFER or DHCPACK packets that do not contain this
443 // option."
444 OptionPtr subnet_sel = query_->getOption(DHO_SUBNET_SELECTION);
445 if (subnet_sel) {
446 resp_->addOption(subnet_sel);
447 }
448
449 // If this packet is relayed, we want to copy Relay Agent Info option
450 // when it is not empty.
451 OptionPtr rai = query_->getOption(DHO_DHCP_AGENT_OPTIONS);
452 if (!rai || (rai->len() <= Option::OPTION4_HDR_LEN)) {
453 return;
454 }
455 // Do not copy recovered stashed RAI.
457 getConfiguredGlobal(CfgGlobals::STASH_AGENT_OPTIONS);
458 if (sao && (sao->getType() == Element::boolean) &&
459 sao->boolValue() && query_->inClass("STASH_AGENT_OPTIONS")) {
460 return;
461 }
462 resp_->addOption(rai);
463}
464
465void
467 const ConstCfgHostOperationsPtr cfg =
468 CfgMgr::instance().getCurrentCfg()->getCfgHostOperations4();
469
470 // Collect host identifiers. The identifiers are stored in order of preference.
471 // The server will use them in that order to search for host reservations.
472 for (auto const& id_type : cfg->getIdentifierTypes()) {
473 switch (id_type) {
475 if (context->hwaddr_ && !context->hwaddr_->hwaddr_.empty()) {
476 context->addHostIdentifier(id_type, context->hwaddr_->hwaddr_);
477 }
478 break;
479
480 case Host::IDENT_DUID:
481 if (context->clientid_) {
482 const std::vector<uint8_t>& vec = context->clientid_->getClientId();
483 if (!vec.empty()) {
484 // Client identifier type = DUID? Client identifier holding a DUID
485 // comprises Type (1 byte), IAID (4 bytes), followed by the actual
486 // DUID. Thus, the minimal length is 6.
487 if ((vec[0] == CLIENT_ID_OPTION_TYPE_DUID) && (vec.size() > 5)) {
488 // Extract DUID, skip IAID.
489 context->addHostIdentifier(id_type,
490 std::vector<uint8_t>(vec.begin() + 5,
491 vec.end()));
492 }
493 }
494 }
495 break;
496
498 {
499 OptionPtr rai = context->query_->getOption(DHO_DHCP_AGENT_OPTIONS);
500 if (rai) {
501 OptionPtr circuit_id_opt = rai->getOption(RAI_OPTION_AGENT_CIRCUIT_ID);
502 if (circuit_id_opt) {
503 const OptionBuffer& circuit_id_vec = circuit_id_opt->getData();
504 if (!circuit_id_vec.empty()) {
505 context->addHostIdentifier(id_type, circuit_id_vec);
506 }
507 }
508 }
509 }
510 break;
511
513 if (context->clientid_) {
514 const std::vector<uint8_t>& vec = context->clientid_->getClientId();
515 if (!vec.empty()) {
516 context->addHostIdentifier(id_type, vec);
517 }
518 }
519 break;
520 case Host::IDENT_FLEX:
521 {
522 if (!HooksManager::calloutsPresent(Hooks.hook_index_host4_identifier_)) {
523 break;
524 }
525
526 CalloutHandlePtr callout_handle = getCalloutHandle(context->query_);
527
529 std::vector<uint8_t> id;
530
531 // Use the RAII wrapper to make sure that the callout handle state is
532 // reset when this object goes out of scope. All hook points must do
533 // it to prevent possible circular dependency between the callout
534 // handle and its arguments.
535 ScopedCalloutHandleState callout_handle_state(callout_handle);
536
537 // Pass incoming packet as argument
538 callout_handle->setArgument("query4", context->query_);
539 callout_handle->setArgument("id_type", type);
540 callout_handle->setArgument("id_value", id);
541
542 // Call callouts
543 HooksManager::callCallouts(Hooks.hook_index_host4_identifier_,
544 *callout_handle);
545
546 callout_handle->getArgument("id_type", type);
547 callout_handle->getArgument("id_value", id);
548
549 if ((callout_handle->getStatus() == CalloutHandle::NEXT_STEP_CONTINUE) &&
550 !id.empty()) {
551
553 .arg(context->query_->getLabel())
554 .arg(Host::getIdentifierAsText(type, &id[0], id.size()));
555
556 context->addHostIdentifier(type, id);
557 }
558 break;
559 }
560 default:
561 ;
562 }
563 }
564}
565
566void
568 const ClientClassDictionaryPtr& dict =
569 CfgMgr::instance().getCurrentCfg()->getClientClassDictionary();
570 const ClientClassDefListPtr& defs_ptr = dict->getClasses();
571 for (auto const& def : *defs_ptr) {
572 // Only remove evaluated classes. Other classes can be
573 // assigned via hooks libraries and we should not remove
574 // them because there is no way they can be added back.
575 if (def->getMatchExpr()) {
576 query->classes_.erase(def->getName());
577 }
578 }
579}
580
581void
583 if (context->currentHost() && context->query_) {
584 const ClientClasses& classes = context->currentHost()->getClientClasses4();
585 for (auto const& cclass : classes) {
586 context->query_->addClass(cclass);
587 }
588 }
589}
590
591void
593 if (context_->subnet_) {
594 SharedNetwork4Ptr shared_network;
595 context_->subnet_->getSharedNetwork(shared_network);
596 if (shared_network) {
597 ConstHostPtr host = context_->currentHost();
598 if (host && (host->getIPv4SubnetID() != SUBNET_ID_GLOBAL)) {
599 setReservedClientClasses(context_);
600 }
601 }
602 }
603}
604
605void
607 ConstHostPtr host = context_->currentHost();
608 // Nothing to do if host reservations not specified for this client.
609 if (host) {
610 if (!host->getNextServer().isV4Zero()) {
611 resp_->setSiaddr(host->getNextServer());
612 }
613
614 std::string sname = host->getServerHostname();
615 if (!sname.empty()) {
616 resp_->setSname(reinterpret_cast<const uint8_t*>(sname.c_str()),
617 sname.size());
618 }
619
620 std::string bootfile = host->getBootFileName();
621 if (!bootfile.empty()) {
622 resp_->setFile(reinterpret_cast<const uint8_t*>(bootfile.c_str()),
623 bootfile.size());
624 }
625 }
626}
627
629 // Built-in vendor class processing
630 boost::shared_ptr<OptionString> vendor_class =
631 boost::dynamic_pointer_cast<OptionString>(pkt->getOption(DHO_VENDOR_CLASS_IDENTIFIER));
632
633 if (!vendor_class) {
634 return;
635 }
636
637 string escaped = ClientClasses::escape(vendor_class->getValue());
638 pkt->addClass(Dhcpv4Srv::VENDOR_CLASS_PREFIX + escaped);
639}
640
642 // All packets belong to ALL.
643 pkt->addClass("ALL");
644
645 // First: built-in vendor class processing.
646 classifyByVendor(pkt);
647
648 // Run match expressions on classes not depending on KNOWN/UNKNOWN.
649 evaluateClasses(pkt, false);
650}
651
652void Dhcpv4Exchange::evaluateClasses(const Pkt4Ptr& pkt, bool depend_on_known) {
653 // Note getClientClassDictionary() cannot be null
654 const ClientClassDictionaryPtr& dict =
655 CfgMgr::instance().getCurrentCfg()->getClientClassDictionary();
656 const ClientClassDefListPtr& defs_ptr = dict->getClasses();
657 for (auto const& it : *defs_ptr) {
658 // Note second cannot be null
659 const ExpressionPtr& expr_ptr = it->getMatchExpr();
660 // Nothing to do without an expression to evaluate
661 if (!expr_ptr) {
662 continue;
663 }
664 // Not the right time if only when additional
665 if (it->getAdditional()) {
666 continue;
667 }
668 // Not the right pass.
669 if (it->getDependOnKnown() != depend_on_known) {
670 continue;
671 }
672 it->test(pkt, expr_ptr);
673 }
674}
675
676const std::string Dhcpv4Srv::VENDOR_CLASS_PREFIX("VENDOR_CLASS_");
677
678Dhcpv4Srv::Dhcpv4Srv(uint16_t server_port, uint16_t client_port,
679 const bool use_bcast, const bool direct_response_desired)
680 : io_service_(new IOService()), server_port_(server_port),
681 client_port_(client_port), shutdown_(true),
682 alloc_engine_(), use_bcast_(use_bcast),
685 test_send_responses_to_source_(false) {
686
687 const char* env = std::getenv("KEA_TEST_SEND_RESPONSES_TO_SOURCE");
688 if (env) {
690 test_send_responses_to_source_ = true;
691 }
692
694 .arg(server_port);
695
696 try {
697 // Port 0 is used for testing purposes where we don't open broadcast
698 // capable sockets. So, set the packet filter handling direct traffic
699 // only if we are in non-test mode.
700 if (server_port) {
701 // First call to instance() will create IfaceMgr (it's a singleton)
702 // it may throw something if things go wrong.
703 // The 'true' value of the call to setMatchingPacketFilter imposes
704 // that IfaceMgr will try to use the mechanism to respond directly
705 // to the client which doesn't have address assigned. This capability
706 // may be lacking on some OSes, so there is no guarantee that server
707 // will be able to respond directly.
708 IfaceMgr::instance().setMatchingPacketFilter(direct_response_desired);
709 }
710
711 // Instantiate allocation engine. The number of allocation attempts equal
712 // to zero indicates that the allocation engine will use the number of
713 // attempts depending on the pool size.
714 alloc_engine_.reset(new AllocEngine(0));
715
717
718 } catch (const std::exception &e) {
720 return;
721 }
722
723 // Initializing all observations with default value
725
726 // All done, so can proceed
727 shutdown_ = false;
728}
729
731 StatsMgr& stats_mgr = StatsMgr::instance();
732
733 // Iterate over set of observed statistics
734 for (auto const& it : dhcp4_statistics) {
735 // Initialize them with default value 0
736 stats_mgr.setValue(it, static_cast<int64_t>(0));
737 }
738}
739
741 // Discard any parked packets
743
744 try {
745 stopD2();
746 } catch (const std::exception& ex) {
747 // Highly unlikely, but lets Report it but go on
749 }
750
751 try {
753 } catch (const std::exception& ex) {
754 // Highly unlikely, but lets Report it but go on
756 }
757
759
760 // The lease manager was instantiated during DHCPv4Srv configuration,
761 // so we should clean up after ourselves.
763
764 // Destroy the host manager before hooks unload.
766
767 // Explicitly unload hooks
770 auto names = HooksManager::getLibraryNames();
771 std::string msg;
772 if (!names.empty()) {
773 msg = names[0];
774 for (size_t i = 1; i < names.size(); ++i) {
775 msg += std::string(", ") + names[i];
776 }
777 }
779 }
781 io_service_->stopAndPoll();
782}
783
784void
789
791Dhcpv4Srv::selectSubnet(const Pkt4Ptr& query, bool& drop, bool allow_answer_park) {
792 // DHCPv4-over-DHCPv6 is a special (and complex) case
793 if (query->isDhcp4o6()) {
794 return (selectSubnet4o6(query, drop, allow_answer_park));
795 }
796
797 ConstSubnet4Ptr subnet;
798
799 const SubnetSelector& selector = CfgSubnets4::initSelector(query);
800
801 CfgMgr& cfgmgr = CfgMgr::instance();
802 subnet = cfgmgr.getCurrentCfg()->getCfgSubnets4()->selectSubnet(selector);
803
804 // Let's execute all callouts registered for subnet4_select
805 // (skip callouts if the selectSubnet was called to do sanity checks only)
806 if (HooksManager::calloutsPresent(Hooks.hook_index_subnet4_select_)) {
807 CalloutHandlePtr callout_handle = getCalloutHandle(query);
808
809 // Use the RAII wrapper to make sure that the callout handle state is
810 // reset when this object goes out of scope. All hook points must do
811 // it to prevent possible circular dependency between the callout
812 // handle and its arguments.
813 shared_ptr<ScopedCalloutHandleState> callout_handle_state(
814 std::make_shared<ScopedCalloutHandleState>(callout_handle));
815
816 // Enable copying options from the packet within hook library.
817 ScopedEnableOptionsCopy<Pkt4> query4_options_copy(query);
818
819 // Set new arguments
820 callout_handle->setArgument("query4", query);
821 callout_handle->setArgument("subnet4", subnet);
822 callout_handle->setArgument("subnet4collection",
823 cfgmgr.getCurrentCfg()->
824 getCfgSubnets4()->getAll());
825
826 auto const tpl(parkingLimitExceeded("subnet4_select"));
827 bool const exceeded(get<0>(tpl));
828 if (exceeded) {
829 uint32_t const limit(get<1>(tpl));
830 // We can't park it so we're going to throw it on the floor.
833 .arg(limit)
834 .arg(query->getLabel());
835 StatsMgr::instance().addValue("pkt4-queue-full",
836 static_cast<int64_t>(1));
837 StatsMgr::instance().addValue("pkt4-receive-drop",
838 static_cast<int64_t>(1));
839 return (ConstSubnet4Ptr());
840 }
841
842 // We proactively park the packet.
844 "subnet4_select", query, [this, query, allow_answer_park, callout_handle_state]() {
845 if (MultiThreadingMgr::instance().getMode()) {
846 boost::shared_ptr<function<void()>> callback(
847 boost::make_shared<function<void()>>(
848 [this, query, allow_answer_park]() mutable {
849 processLocalizedQuery4AndSendResponse(query, allow_answer_park);
850 }));
851 callout_handle_state->on_completion_ = [callback]() {
853 };
854 } else {
855 processLocalizedQuery4AndSendResponse(query, allow_answer_park);
856 }
857 });
858
859 // Call user (and server-side) callouts
860 try {
861 HooksManager::callCallouts(Hooks.hook_index_subnet4_select_,
862 *callout_handle);
863 } catch (...) {
864 // Make sure we don't orphan a parked packet.
865 HooksManager::drop("subnet4_select", query);
866 throw;
867 }
868
869 // Callouts parked the packet. Same as drop but callouts will resume
870 // processing or drop the packet later.
871 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_PARK) {
874 .arg(query->getLabel());
875 drop = true;
876 return (ConstSubnet4Ptr());
877 } else {
878 HooksManager::drop("subnet4_select", query);
879 }
880
881 // Callouts decided to skip this step. This means that no subnet
882 // will be selected. Packet processing will continue, but it will
883 // be severely limited (i.e. only global options will be assigned)
884 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
887 .arg(query->getLabel());
888 return (ConstSubnet4Ptr());
889 }
890
891 // Callouts decided to drop the packet. It is a superset of the
892 // skip case so no subnet will be selected.
893 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP) {
896 .arg(query->getLabel());
897 drop = true;
898 return (ConstSubnet4Ptr());
899 }
900
901 // Use whatever subnet was specified by the callout
902 callout_handle->getArgument("subnet4", subnet);
903 }
904
905 if (subnet) {
906 // Log at higher debug level that subnet has been found.
908 .arg(query->getLabel())
909 .arg(subnet->getID());
910 // Log detailed information about the selected subnet at the
911 // lower debug level.
913 .arg(query->getLabel())
914 .arg(subnet->toText());
915
916 } else {
919 .arg(query->getLabel());
920 }
921
922 return (subnet);
923}
924
926Dhcpv4Srv::selectSubnet4o6(const Pkt4Ptr& query, bool& drop,
927 bool allow_answer_park) {
928 ConstSubnet4Ptr subnet;
929
930 SubnetSelector selector;
931 selector.ciaddr_ = query->getCiaddr();
932 selector.giaddr_ = query->getGiaddr();
933 selector.local_address_ = query->getLocalAddr();
934 selector.client_classes_ = query->classes_;
935 selector.iface_name_ = query->getIface();
936 // Mark it as DHCPv4-over-DHCPv6
937 selector.dhcp4o6_ = true;
938 // Now the DHCPv6 part
939 selector.remote_address_ = query->getRemoteAddr();
940 selector.first_relay_linkaddr_ = IOAddress("::");
941
942 // Handle a DHCPv6 relayed query
943 Pkt4o6Ptr query4o6 = boost::dynamic_pointer_cast<Pkt4o6>(query);
944 if (!query4o6) {
945 isc_throw(Unexpected, "Can't get DHCP4o6 message");
946 }
947 const Pkt6Ptr& query6 = query4o6->getPkt6();
948
949 // Initialize fields specific to relayed messages.
950 if (query6 && !query6->relay_info_.empty()) {
951 for (auto const& relay : boost::adaptors::reverse(query6->relay_info_)) {
952 if (!relay.linkaddr_.isV6Zero() &&
953 !relay.linkaddr_.isV6LinkLocal()) {
954 selector.first_relay_linkaddr_ = relay.linkaddr_;
955 break;
956 }
957 }
958 selector.interface_id_ =
959 query6->getAnyRelayOption(D6O_INTERFACE_ID,
961 }
962
963 // If the Subnet Selection option is present, extract its value.
964 OptionPtr sbnsel = query->getOption(DHO_SUBNET_SELECTION);
965 if (sbnsel) {
966 OptionCustomPtr oc = boost::dynamic_pointer_cast<OptionCustom>(sbnsel);
967 if (oc) {
968 selector.option_select_ = oc->readAddress();
969 }
970 }
971
972 CfgMgr& cfgmgr = CfgMgr::instance();
973 subnet = cfgmgr.getCurrentCfg()->getCfgSubnets4()->selectSubnet4o6(selector);
974
975 // Let's execute all callouts registered for subnet4_select.
976 // (skip callouts if the selectSubnet was called to do sanity checks only)
977 if (HooksManager::calloutsPresent(Hooks.hook_index_subnet4_select_)) {
978 CalloutHandlePtr callout_handle = getCalloutHandle(query);
979
980 // Use the RAII wrapper to make sure that the callout handle state is
981 // reset when this object goes out of scope. All hook points must do
982 // it to prevent possible circular dependency between the callout
983 // handle and its arguments.
984 shared_ptr<ScopedCalloutHandleState> callout_handle_state(
985 std::make_shared<ScopedCalloutHandleState>(callout_handle));
986
987 // Enable copying options from the packet within hook library.
988 ScopedEnableOptionsCopy<Pkt4> query4_options_copy(query);
989
990 // Set new arguments
991 callout_handle->setArgument("query4", query);
992 callout_handle->setArgument("subnet4", subnet);
993 callout_handle->setArgument("subnet4collection",
994 cfgmgr.getCurrentCfg()->
995 getCfgSubnets4()->getAll());
996
997 auto const tpl(parkingLimitExceeded("subnet4_select"));
998 bool const exceeded(get<0>(tpl));
999 if (exceeded) {
1000 uint32_t const limit(get<1>(tpl));
1001 // We can't park it so we're going to throw it on the floor.
1004 .arg(limit)
1005 .arg(query->getLabel());
1006 StatsMgr::instance().addValue("pkt4-queue-full",
1007 static_cast<int64_t>(1));
1008 StatsMgr::instance().addValue("pkt4-receive-drop",
1009 static_cast<int64_t>(1));
1010 return (ConstSubnet4Ptr());
1011 }
1012
1013 // We proactively park the packet.
1015 "subnet4_select", query, [this, query, allow_answer_park, callout_handle_state]() {
1016 if (MultiThreadingMgr::instance().getMode()) {
1017 boost::shared_ptr<function<void()>> callback(
1018 boost::make_shared<function<void()>>(
1019 [this, query, allow_answer_park]() mutable {
1020 processLocalizedQuery4AndSendResponse(query, allow_answer_park);
1021 }));
1022 callout_handle_state->on_completion_ = [callback]() {
1024 };
1025 } else {
1026 processLocalizedQuery4AndSendResponse(query, allow_answer_park);
1027 }
1028 });
1029
1030 // Call user (and server-side) callouts
1031 try {
1032 HooksManager::callCallouts(Hooks.hook_index_subnet4_select_,
1033 *callout_handle);
1034 } catch (...) {
1035 // Make sure we don't orphan a parked packet.
1036 HooksManager::drop("subnet4_select", query);
1037 throw;
1038 }
1039
1040 // Callouts parked the packet. Same as drop but callouts will resume
1041 // processing or drop the packet later.
1042 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_PARK) {
1045 .arg(query->getLabel());
1046 drop = true;
1047 return (ConstSubnet4Ptr());
1048 } else {
1049 HooksManager::drop("subnet4_select", query);
1050 }
1051
1052 // Callouts decided to skip this step. This means that no subnet
1053 // will be selected. Packet processing will continue, but it will
1054 // be severely limited (i.e. only global options will be assigned)
1055 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
1058 .arg(query->getLabel());
1059 return (ConstSubnet4Ptr());
1060 }
1061
1062 // Callouts decided to drop the packet. It is a superset of the
1063 // skip case so no subnet will be selected.
1064 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP) {
1067 .arg(query->getLabel());
1068 drop = true;
1069 return (ConstSubnet4Ptr());
1070 }
1071
1072 // Use whatever subnet was specified by the callout
1073 callout_handle->getArgument("subnet4", subnet);
1074 }
1075
1076 if (subnet) {
1077 // Log at higher debug level that subnet has been found.
1080 .arg(query->getLabel())
1081 .arg(subnet->getID());
1082 // Log detailed information about the selected subnet at the
1083 // lower debug level.
1086 .arg(query->getLabel())
1087 .arg(subnet->toText());
1088
1089 } else {
1092 .arg(query->getLabel());
1093 }
1094
1095 return (subnet);
1096}
1097
1098Pkt4Ptr
1100 return (IfaceMgr::instance().receive4(timeout));
1101}
1102
1103void
1105 IfaceMgr::instance().send(packet);
1106}
1107
1108void
1111 // Pointer to client's query.
1112 ctx->query_ = query;
1113
1114 // Hardware address.
1115 ctx->hwaddr_ = query->getHWAddr();
1116}
1117
1118bool
1121
1122 // First part of context initialization.
1123 initContext0(query, ctx);
1124
1125 // Get the early-global-reservations-lookup flag value.
1128 if (egrl) {
1129 ctx->early_global_reservations_lookup_ = egrl->boolValue();
1130 }
1131
1132 // Perform early global reservations lookup when wanted.
1133 if (ctx->early_global_reservations_lookup_) {
1134 // Retrieve retrieve client identifier.
1135 OptionPtr opt_clientid = query->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
1136 if (opt_clientid) {
1137 ctx->clientid_.reset(new ClientId(opt_clientid->getData()));
1138 }
1139
1140 // Get the host identifiers.
1142
1143 // Check for global host reservations.
1144 ConstHostPtr global_host = alloc_engine_->findGlobalReservation(*ctx);
1145
1146 if (global_host && !global_host->getClientClasses4().empty()) {
1147 // Remove dependent evaluated classes.
1149
1150 // Add classes from the global reservations.
1151 const ClientClasses& classes = global_host->getClientClasses4();
1152 for (auto const& cclass : classes) {
1153 query->addClass(cclass);
1154 }
1155
1156 // Evaluate classes before KNOWN.
1157 Dhcpv4Exchange::evaluateClasses(query, false);
1158 }
1159
1160 if (global_host) {
1161 // Add the KNOWN class;
1162 query->addClass("KNOWN");
1164 .arg(query->getLabel())
1165 .arg("KNOWN");
1166
1167 // Evaluate classes after KNOWN.
1169
1170 // Check the DROP special class.
1171 if (query->inClass("DROP")) {
1174 .arg(query->getHWAddrLabel())
1175 .arg(query->toText());
1176 StatsMgr::instance().addValue("pkt4-admin-filtered",
1177 static_cast<int64_t>(1));
1178 StatsMgr::instance().addValue("pkt4-receive-drop",
1179 static_cast<int64_t>(1));
1180 return (false);
1181 }
1182
1183 // Store the reservation.
1184 ctx->hosts_[SUBNET_ID_GLOBAL] = global_host;
1185 }
1186 }
1187
1188 return (true);
1189}
1190
1191int
1193#ifdef HAVE_AFL
1194 // Get the values of the environment variables used to control the
1195 // fuzzing.
1196
1197 // Specfies the interface to be used to pass packets from AFL to Kea.
1198 const char* interface = getenv("KEA_AFL_INTERFACE");
1199 if (!interface) {
1200 isc_throw(FuzzInitFail, "no fuzzing interface has been set");
1201 }
1202
1203 // The address on the interface to be used.
1204 const char* address = getenv("KEA_AFL_ADDRESS");
1205 if (!address) {
1206 isc_throw(FuzzInitFail, "no fuzzing address has been set");
1207 }
1208
1209 // Set up structures needed for fuzzing.
1210 PacketFuzzer fuzzer(server_port_, interface, address);
1211
1212 // The next line is needed as a signature for AFL to recognize that we are
1213 // running persistent fuzzing. This has to be in the main image file.
1214 while (__AFL_LOOP(fuzzer.maxLoopCount())) {
1215 // Read from stdin and put the data read into an address/port on which
1216 // Kea is listening, read for Kea to read it via asynchronous I/O.
1217 fuzzer.transfer();
1218#else
1219 while (!shutdown_) {
1220#endif // HAVE_AFL
1221 try {
1222 runOne();
1223 // Handle events registered by hooks using external IOService objects.
1225 getIOService()->poll();
1226 } catch (const std::exception& e) {
1227 // General catch-all standard exceptions that are not caught by more
1228 // specific catches.
1230 .arg(e.what());
1231 } catch (...) {
1232 // General catch-all exception that are not caught by more specific
1233 // catches. This one is for other exceptions, not derived from
1234 // std::exception.
1236 }
1237 }
1238
1239 // Stop everything before we change into single-threaded mode.
1241
1242 // destroying the thread pool
1243 MultiThreadingMgr::instance().apply(false, 0, 0);
1244
1245 return (getExitValue());
1246}
1247
1248void
1250 // client's message and server's response
1251 Pkt4Ptr query;
1252
1253 try {
1254 // Set select() timeout to 1s. This value should not be modified
1255 // because it is important that the select() returns control
1256 // frequently so as the IOService can be polled for ready handlers.
1257 uint32_t timeout = 1;
1258 query = receivePacket(timeout);
1259
1260 // Log if packet has arrived. We can't log the detailed information
1261 // about the DHCP message because it hasn't been unpacked/parsed
1262 // yet, and it can't be parsed at this point because hooks will
1263 // have to process it first. The only information available at this
1264 // point are: the interface, source address and destination addresses
1265 // and ports.
1266 if (query) {
1268 .arg(query->getRemoteAddr().toText())
1269 .arg(query->getRemotePort())
1270 .arg(query->getLocalAddr().toText())
1271 .arg(query->getLocalPort())
1272 .arg(query->getIface());
1273
1274 // Log reception of the packet. We need to increase it early, as
1275 // any failures in unpacking will cause the packet to be dropped.
1276 // We will increase type specific statistic further down the road.
1277 // See processStatsReceived().
1278 StatsMgr::instance().addValue("pkt4-received",
1279 static_cast<int64_t>(1));
1280 }
1281
1282 // We used to log that the wait was interrupted, but this is no longer
1283 // the case. Our wait time is 1s now, so the lack of query packet more
1284 // likely means that nothing new appeared within a second, rather than
1285 // we were interrupted. And we don't want to print a message every
1286 // second.
1287
1288 } catch (const SignalInterruptOnSelect&) {
1289 // Packet reception interrupted because a signal has been received.
1290 // This is not an error because we might have received a SIGTERM,
1291 // SIGINT, SIGHUP or SIGCHLD which are handled by the server. For
1292 // signals that are not handled by the server we rely on the default
1293 // behavior of the system.
1295 } catch (const std::exception& e) {
1296 // Log all other errors.
1298 .arg(e.what());
1299 }
1300
1301 // Timeout may be reached or signal received, which breaks select()
1302 // with no reception occurred. No need to log anything here because
1303 // we have logged right after the call to receivePacket().
1304 if (!query) {
1305 return;
1306 }
1307
1308 // If the DHCP service has been globally disabled, drop the packet.
1309 if (!network_state_->isServiceEnabled()) {
1311 .arg(query->getLabel());
1312 // Increase the statistics of service disabled and dropped packets.
1313 StatsMgr::instance().addValue("pkt4-service-disabled",
1314 static_cast<int64_t>(1));
1315 StatsMgr::instance().addValue("pkt4-receive-drop",
1316 static_cast<int64_t>(1));
1317 return;
1318 } else {
1319 if (MultiThreadingMgr::instance().getMode()) {
1320 query->addPktEvent("mt_queued");
1321 typedef function<void()> CallBack;
1322 boost::shared_ptr<CallBack> call_back =
1323 boost::make_shared<CallBack>(std::bind(&Dhcpv4Srv::processPacketAndSendResponseNoThrow,
1324 this, query));
1325 if (!MultiThreadingMgr::instance().getThreadPool().add(call_back)) {
1327 StatsMgr::instance().addValue("pkt4-queue-full",
1328 static_cast<int64_t>(1));
1329 StatsMgr::instance().addValue("pkt4-receive-drop",
1330 static_cast<int64_t>(1));
1331 }
1332 } else {
1334 }
1335 }
1336}
1337
1338void
1340 try {
1342 } catch (const std::exception& e) {
1344 .arg(query->getLabel())
1345 .arg(e.what());
1346 StatsMgr::instance().addValue("pkt4-processing-failed",
1347 static_cast<int64_t>(1));
1348 StatsMgr::instance().addValue("pkt4-receive-drop",
1349 static_cast<int64_t>(1));
1350 } catch (...) {
1352 .arg(query->getLabel());
1353 StatsMgr::instance().addValue("pkt4-processing-failed",
1354 static_cast<int64_t>(1));
1355 StatsMgr::instance().addValue("pkt4-receive-drop",
1356 static_cast<int64_t>(1));
1357 }
1358}
1359
1360void
1362 Pkt4Ptr rsp = processPacket(query);
1363 if (!rsp) {
1364 return;
1365 }
1366
1367 CalloutHandlePtr callout_handle = getCalloutHandle(query);
1368
1369 processPacketBufferSend(callout_handle, rsp);
1370}
1371
1372Pkt4Ptr
1373Dhcpv4Srv::processPacket(Pkt4Ptr query, bool allow_answer_park) {
1374 query->addPktEvent("process_started");
1375
1376 // All packets belong to ALL.
1377 query->addClass("ALL");
1378
1379 bool skip_unpack = false;
1380
1381 // The packet has just been received so contains the uninterpreted wire
1382 // data; execute callouts registered for buffer4_receive.
1383 if (HooksManager::calloutsPresent(Hooks.hook_index_buffer4_receive_)) {
1384 CalloutHandlePtr callout_handle = getCalloutHandle(query);
1385
1386 // Use the RAII wrapper to make sure that the callout handle state is
1387 // reset when this object goes out of scope. All hook points must do
1388 // it to prevent possible circular dependency between the callout
1389 // handle and its arguments.
1390 ScopedCalloutHandleState callout_handle_state(callout_handle);
1391
1392 // Enable copying options from the packet within hook library.
1393 ScopedEnableOptionsCopy<Pkt4> query4_options_copy(query);
1394
1395 // Pass incoming packet as argument
1396 callout_handle->setArgument("query4", query);
1397
1398 // Call callouts
1399 HooksManager::callCallouts(Hooks.hook_index_buffer4_receive_,
1400 *callout_handle);
1401
1402 // Callouts decided to drop the received packet.
1403 // The response (rsp) is null so the caller (runOne) will
1404 // immediately return too.
1405 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP) {
1408 .arg(query->getRemoteAddr().toText())
1409 .arg(query->getLocalAddr().toText())
1410 .arg(query->getIface());
1411
1412 // Not increasing the statistics of the dropped packets because it
1413 // is the callouts' responsibility to increase it.
1414 return (Pkt4Ptr());;
1415 }
1416
1417 // Callouts decided to skip the next processing step. The next
1418 // processing step would be to parse the packet, so skip at this
1419 // stage means that callouts did the parsing already, so server
1420 // should skip parsing.
1421 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
1424 .arg(query->getRemoteAddr().toText())
1425 .arg(query->getLocalAddr().toText())
1426 .arg(query->getIface());
1427 skip_unpack = true;
1428 }
1429
1430 callout_handle->getArgument("query4", query);
1431 if (!query) {
1432 // Please use the status instead of resetting query!
1433 return (Pkt4Ptr());
1434 }
1435 }
1436
1437 // Unpack the packet information unless the buffer4_receive callouts
1438 // indicated they did it
1439 if (!skip_unpack) {
1440 try {
1442 .arg(query->getRemoteAddr().toText())
1443 .arg(query->getLocalAddr().toText())
1444 .arg(query->getIface());
1445 query->unpack();
1446 } catch (const SkipRemainingOptionsError& e) {
1447 // An option failed to unpack but we are to attempt to process it
1448 // anyway. Log it and let's hope for the best.
1451 .arg(query->getLabel())
1452 .arg(e.what());
1453 } catch (const std::exception& e) {
1454 // Failed to parse the packet.
1456 .arg(query->getLabel())
1457 .arg(query->getRemoteAddr().toText())
1458 .arg(query->getLocalAddr().toText())
1459 .arg(query->getIface())
1460 .arg(e.what())
1461 .arg(query->getHWAddrLabel());
1462
1463 // Increase the statistics of parse failures and dropped packets.
1464 StatsMgr::instance().addValue("pkt4-parse-failed",
1465 static_cast<int64_t>(1));
1466 StatsMgr::instance().addValue("pkt4-receive-drop",
1467 static_cast<int64_t>(1));
1468 return (Pkt4Ptr());
1469 }
1470 }
1471
1472 // Classify can emit INFO logs so help to track the query.
1474 .arg(query->getLabel());
1475
1476 // Update statistics accordingly for received packet.
1477 processStatsReceived(query);
1478
1479 // Recover stashed RAI from client address lease.
1480 try {
1482 } catch (const std::exception&) {
1483 // Ignore exceptions.
1484 }
1485
1486 // Assign this packet to one or more classes if needed. We need to do
1487 // this before calling accept(), because getSubnet4() may need client
1488 // class information.
1489 classifyPacket(query);
1490
1491 // Now it is classified the deferred unpacking can be done.
1492 deferredUnpack(query);
1493
1494 // Check whether the message should be further processed or discarded.
1495 // There is no need to log anything here. This function logs by itself.
1496 if (!accept(query)) {
1497 // Increase the statistic of dropped packets.
1498 // Specific drop cause stat was increased by accept* methods.
1499 StatsMgr::instance().addValue("pkt4-receive-drop",
1500 static_cast<int64_t>(1));
1501 return (Pkt4Ptr());
1502 }
1503
1504 // We have sanity checked (in accept() that the Message Type option
1505 // exists, so we can safely get it here.
1506 int type = query->getType();
1508 .arg(query->getLabel())
1509 .arg(query->getName())
1510 .arg(type)
1511 .arg(query->getRemoteAddr())
1512 .arg(query->getLocalAddr())
1513 .arg(query->getIface());
1515 .arg(query->getLabel())
1516 .arg(query->toText(true));
1517
1518 // Let's execute all callouts registered for pkt4_receive
1519 if (HooksManager::calloutsPresent(Hooks.hook_index_pkt4_receive_)) {
1520 CalloutHandlePtr callout_handle = getCalloutHandle(query);
1521
1522 // Use the RAII wrapper to make sure that the callout handle state is
1523 // reset when this object goes out of scope. All hook points must do
1524 // it to prevent possible circular dependency between the callout
1525 // handle and its arguments.
1526 ScopedCalloutHandleState callout_handle_state(callout_handle);
1527
1528 // Enable copying options from the packet within hook library.
1529 ScopedEnableOptionsCopy<Pkt4> query4_options_copy(query);
1530
1531 // Pass incoming packet as argument
1532 callout_handle->setArgument("query4", query);
1533
1534 // Call callouts
1535 HooksManager::callCallouts(Hooks.hook_index_pkt4_receive_,
1536 *callout_handle);
1537
1538 // Callouts decided to skip the next processing step. The next
1539 // processing step would be to process the packet, so skip at this
1540 // stage means drop.
1541 if ((callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) ||
1542 (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP)) {
1545 .arg(query->getLabel());
1546 // Not increasing the statistics of the dropped packets because it
1547 // is the callouts' responsibility to increase it.
1548 return (Pkt4Ptr());
1549 }
1550
1551 callout_handle->getArgument("query4", query);
1552 if (!query) {
1553 // Please use the status instead of resetting query!
1554 return (Pkt4Ptr());
1555 }
1556 }
1557
1558 // Check the DROP special class.
1559 if (query->inClass("DROP")) {
1561 .arg(query->getHWAddrLabel())
1562 .arg(query->toText());
1563 StatsMgr::instance().addValue("pkt4-admin-filtered",
1564 static_cast<int64_t>(1));
1565 StatsMgr::instance().addValue("pkt4-receive-drop",
1566 static_cast<int64_t>(1));
1567 return (Pkt4Ptr());
1568 }
1569
1570 return (processDhcp4Query(query, allow_answer_park));
1571}
1572
1573void
1575 bool allow_answer_park) {
1576 try {
1577 Pkt4Ptr rsp = processDhcp4Query(query, allow_answer_park);
1578 if (!rsp) {
1579 return;
1580 }
1581
1582 CalloutHandlePtr callout_handle = getCalloutHandle(query);
1583 processPacketBufferSend(callout_handle, rsp);
1584 } catch (const std::exception& e) {
1586 .arg(query->getLabel())
1587 .arg(e.what());
1588 StatsMgr::instance().addValue("pkt4-processing-failed",
1589 static_cast<int64_t>(1));
1590 StatsMgr::instance().addValue("pkt4-receive-drop",
1591 static_cast<int64_t>(1));
1592 } catch (...) {
1594 .arg(query->getLabel());
1595 StatsMgr::instance().addValue("pkt4-processing-failed",
1596 static_cast<int64_t>(1));
1597 StatsMgr::instance().addValue("pkt4-receive-drop",
1598 static_cast<int64_t>(1));
1599 }
1600}
1601
1602Pkt4Ptr
1603Dhcpv4Srv::processDhcp4Query(Pkt4Ptr query, bool allow_answer_park) {
1604 // Create a client race avoidance RAII handler.
1605 ClientHandler client_handler;
1606
1607 // Check for lease modifier queries from the same client being processed.
1608 if (MultiThreadingMgr::instance().getMode() &&
1609 ((query->getType() == DHCPDISCOVER) ||
1610 (query->getType() == DHCPREQUEST) ||
1611 (query->getType() == DHCPRELEASE) ||
1612 (query->getType() == DHCPDECLINE))) {
1613 ContinuationPtr cont =
1615 this, query, allow_answer_park));
1616 if (!client_handler.tryLock(query, cont)) {
1617 return (Pkt4Ptr());
1618 }
1619 }
1620
1622 if (!earlyGHRLookup(query, ctx)) {
1623 return (Pkt4Ptr());
1624 }
1625
1626 // The only expected exception is RFCViolation.
1627 bool rfc_violation = false;
1628 try {
1629 try {
1630 sanityCheck(query);
1631
1632 if ((query->getType() == DHCPDISCOVER) ||
1633 (query->getType() == DHCPREQUEST) ||
1634 (query->getType() == DHCPINFORM)) {
1635 bool drop = false;
1636 ctx->subnet_ = selectSubnet(query, drop, allow_answer_park);
1637 // Stop here if selectSubnet decided to drop the packet
1638 if (drop) {
1639 return (Pkt4Ptr());
1640 }
1641 }
1642 } catch (const RFCViolation&) {
1643 rfc_violation = true;
1644 throw;
1645 }
1646 } catch (const std::exception& e) {
1647
1648 // Catch-all exception (we used to call only isc::Exception, but
1649 // std::exception could potentially be raised and if we don't catch
1650 // it here, it would be caught in main() and the process would
1651 // terminate). Just log the problem and ignore the packet.
1652 // (The problem is logged as a debug message because debug is
1653 // disabled by default - it prevents a DDOS attack based on the
1654 // sending of problem packets.)
1656 .arg(query->getLabel())
1657 .arg(e.what());
1658
1659 // Increase the statistic of dropped packets.
1660 // The RFCViolation thrower updated the drop cause statistic.
1661 if (!rfc_violation) {
1662 StatsMgr::instance().addValue("pkt4-processing-failed",
1663 static_cast<int64_t>(1));
1664 }
1665 StatsMgr::instance().addValue("pkt4-receive-drop",
1666 static_cast<int64_t>(1));
1667 return (Pkt4Ptr());
1668 }
1669
1670 return (processLocalizedQuery4(ctx, allow_answer_park));
1671}
1672
1673void
1676 bool allow_answer_park) {
1677 try {
1678 Pkt4Ptr rsp = processLocalizedQuery4(ctx, allow_answer_park);
1679 if (!rsp) {
1680 return;
1681 }
1682
1683 CalloutHandlePtr callout_handle = getCalloutHandle(query);
1684
1685 processPacketBufferSend(callout_handle, rsp);
1686 } catch (const std::exception& e) {
1688 .arg(query->getLabel())
1689 .arg(e.what());
1690 StatsMgr::instance().addValue("pkt4-processing-failed",
1691 static_cast<int64_t>(1));
1692 StatsMgr::instance().addValue("pkt4-receive-drop",
1693 static_cast<int64_t>(1));
1694 } catch (...) {
1696 .arg(query->getLabel());
1697 StatsMgr::instance().addValue("pkt4-processing-failed",
1698 static_cast<int64_t>(1));
1699 StatsMgr::instance().addValue("pkt4-receive-drop",
1700 static_cast<int64_t>(1));
1701 }
1702}
1703
1704void
1706 bool allow_answer_park) {
1707 // Initialize context.
1709 initContext0(query, ctx);
1710
1711 // Subnet is cached in the callout context associated to the query.
1712 try {
1713 CalloutHandlePtr callout_handle = getCalloutHandle(query);
1714 callout_handle->getContext("subnet4", ctx->subnet_);
1715 } catch (const Exception&) {
1716 // No subnet, leave it to null...
1717 }
1718
1719 processLocalizedQuery4AndSendResponse(query, ctx, allow_answer_park);
1720}
1721
1722Pkt4Ptr
1724 bool allow_answer_park) {
1725 if (!ctx) {
1726 isc_throw(Unexpected, "null context");
1727 }
1728 Pkt4Ptr query = ctx->query_;
1729 Pkt4Ptr rsp;
1730 // The only expected exception is RFCViolation.
1731 bool rfc_violation = false;
1732 try {
1733 try {
1734 switch (query->getType()) {
1735 case DHCPDISCOVER:
1736 rsp = processDiscover(query, ctx);
1737 break;
1738
1739 case DHCPREQUEST:
1740 // Note that REQUEST is used for many things in DHCPv4: for
1741 // requesting new leases, renewing existing ones and even
1742 // for rebinding.
1743 rsp = processRequest(query, ctx);
1744 break;
1745
1746 case DHCPRELEASE:
1747 processRelease(query, ctx);
1748 break;
1749
1750 case DHCPDECLINE:
1751 processDecline(query, ctx);
1752 break;
1753
1754 case DHCPINFORM:
1755 rsp = processInform(query, ctx);
1756 break;
1757
1758 default:
1759 // Only action is to output a message if debug is enabled,
1760 // and that is covered by the debug statement before the
1761 // "switch" statement.
1762 ;
1763 }
1764 } catch (const RFCViolation&) {
1765 rfc_violation = true;
1766 throw;
1767 }
1768 } catch (const std::exception& e) {
1769
1770 // Catch-all exception (we used to call only isc::Exception, but
1771 // std::exception could potentially be raised and if we don't catch
1772 // it here, it would be caught in main() and the process would
1773 // terminate). Just log the problem and ignore the packet.
1774 // (The problem is logged as a debug message because debug is
1775 // disabled by default - it prevents a DDOS attack based on the
1776 // sending of problem packets.)
1778 .arg(query->getLabel())
1779 .arg(e.what());
1780
1781 // Increase the statistic of dropped packets.
1782 // The RFCViolation thrower updated the drop cause statistic.
1783 if (!rfc_violation) {
1784 StatsMgr::instance().addValue("pkt4-processing-failed",
1785 static_cast<int64_t>(1));
1786 }
1787 StatsMgr::instance().addValue("pkt4-receive-drop",
1788 static_cast<int64_t>(1));
1789 return (Pkt4Ptr());
1790 }
1791
1792 CalloutHandlePtr callout_handle = getCalloutHandle(query);
1793 if (ctx) {
1794 // leases4_committed and lease4_offer callouts are treated in the same way,
1795 // so prepare correct set of variables basing on the packet context.
1796 int hook_idx = Hooks.hook_index_leases4_committed_;
1797 std::string hook_label = "leases4_committed";
1801 if (ctx->fake_allocation_) {
1802 hook_idx = Hooks.hook_index_lease4_offer_;
1803 hook_label = "lease4_offer";
1804 pkt_park_msg = DHCP4_HOOK_LEASE4_OFFER_PARK;
1805 pkt_drop_msg = DHCP4_HOOK_LEASE4_OFFER_DROP;
1806 parking_lot_full_msg = DHCP4_HOOK_LEASE4_OFFER_PARKING_LOT_FULL;
1807 }
1808
1809 if (HooksManager::calloutsPresent(hook_idx)) {
1810 // The ScopedCalloutHandleState class which guarantees that the task
1811 // is added to the thread pool after the response is reset (if needed)
1812 // and CalloutHandle state is reset. In ST it does nothing.
1813 // A smart pointer is used to store the ScopedCalloutHandleState so that
1814 // a copy of the pointer is created by the lambda and only on the
1815 // destruction of the last reference the task is added.
1816 // In MT there are 2 cases:
1817 // 1. packet is unparked before current thread smart pointer to
1818 // ScopedCalloutHandleState is destroyed:
1819 // - the lambda uses the smart pointer to set the callout which adds the
1820 // task, but the task is added after ScopedCalloutHandleState is
1821 // destroyed, on the destruction of the last reference which is held
1822 // by the current thread.
1823 // 2. packet is unparked after the current thread smart pointer to
1824 // ScopedCalloutHandleState is destroyed:
1825 // - the current thread reference to ScopedCalloutHandleState is
1826 // destroyed, but the reference in the lambda keeps it alive until
1827 // the lambda is called and the last reference is released, at which
1828 // time the task is actually added.
1829 // Use the RAII wrapper to make sure that the callout handle state is
1830 // reset when this object goes out of scope. All hook points must do
1831 // it to prevent possible circular dependency between the callout
1832 // handle and its arguments.
1833 std::shared_ptr<ScopedCalloutHandleState> callout_handle_state =
1834 std::make_shared<ScopedCalloutHandleState>(callout_handle);
1835
1836 ScopedEnableOptionsCopy<Pkt4> query4_options_copy(query);
1837
1838 // Also pass the corresponding query packet as argument
1839 callout_handle->setArgument("query4", query);
1840
1841 // Also pass the corresponding response packet as argument
1842 ScopedEnableOptionsCopy<Pkt4> response4_options_copy(rsp);
1843 callout_handle->setArgument("response4", rsp);
1844
1845 Lease4CollectionPtr new_leases(new Lease4Collection());
1846 // Filter out the new lease if it was reused so not committed.
1847 if (ctx->new_lease_ && (ctx->new_lease_->reuseable_valid_lft_ == 0)) {
1848 new_leases->push_back(ctx->new_lease_);
1849 }
1850 callout_handle->setArgument("leases4", new_leases);
1851
1852 if (ctx->fake_allocation_) {
1853 // Arguments required only for lease4_offer callout.
1854 callout_handle->setArgument("offer_lifetime", ctx->offer_lft_);
1855 callout_handle->setArgument("old_lease", ctx->old_lease_);
1856 callout_handle->setArgument("host", ctx->currentHost());
1857 } else {
1858 // Arguments required only for leases4_committed callout.
1859 Lease4CollectionPtr deleted_leases(new Lease4Collection());
1860 if (ctx->old_lease_) {
1861 if ((!ctx->new_lease_) || (ctx->new_lease_->addr_ != ctx->old_lease_->addr_)) {
1862 deleted_leases->push_back(ctx->old_lease_);
1863 }
1864 }
1865 callout_handle->setArgument("deleted_leases4", deleted_leases);
1866 }
1867
1868 if (allow_answer_park) {
1869 auto const tpl(parkingLimitExceeded(hook_label));
1870 bool const exceeded(get<0>(tpl));
1871 if (exceeded) {
1872 uint32_t const limit(get<1>(tpl));
1873 // We can't park it so we're going to throw it on the floor.
1874 LOG_DEBUG(packet4_logger, DBGLVL_PKT_HANDLING, parking_lot_full_msg)
1875 .arg(limit)
1876 .arg(query->getLabel());
1877 StatsMgr::instance().addValue("pkt4-queue-full",
1878 static_cast<int64_t>(1));
1879 StatsMgr::instance().addValue("pkt4-receive-drop",
1880 static_cast<int64_t>(1));
1881 return (Pkt4Ptr());
1882 }
1883
1884 // We proactively park the packet. We'll unpark it without invoking
1885 // the callback (i.e. drop) unless the callout status is set to
1886 // NEXT_STEP_PARK. Otherwise the callback we bind here will be
1887 // executed when the hook library unparks the packet.
1889 hook_label, query,
1890 [this, callout_handle, query, rsp, callout_handle_state, hook_idx, ctx]() mutable {
1891 if (hook_idx == Hooks.hook_index_lease4_offer_) {
1892 bool offer_address_in_use = false;
1893 try {
1894 callout_handle->getArgument("offer_address_in_use", offer_address_in_use);
1895 } catch (const NoSuchArgument& ex) {
1897 .arg(query->getLabel())
1898 .arg(ex.what());
1899 }
1900
1901 if (offer_address_in_use) {
1902 Lease4Ptr lease = ctx->new_lease_;
1903 bool lease_exists = (ctx->offer_lft_ > 0);
1904 if (MultiThreadingMgr::instance().getMode()) {
1905 typedef function<void()> CallBack;
1906 // We need to pass in the lease and flag as the callback handle state
1907 // gets reset prior to the invocation of the on_completion_ callback.
1908 boost::shared_ptr<CallBack> call_back = boost::make_shared<CallBack>(
1909 std::bind(&Dhcpv4Srv::serverDeclineNoThrow, this,
1910 callout_handle, query, lease, lease_exists));
1911 callout_handle_state->on_completion_ = [call_back]() {
1913 };
1914 } else {
1915 serverDecline(callout_handle, query, lease, lease_exists);
1916 }
1917
1918 return;
1919 }
1920 }
1921
1922 // Send the response to the client.
1923 if (MultiThreadingMgr::instance().getMode()) {
1924 typedef function<void()> CallBack;
1925 boost::shared_ptr<CallBack> call_back = boost::make_shared<CallBack>(
1926 std::bind(&Dhcpv4Srv::sendResponseNoThrow, this, callout_handle,
1927 query, rsp, ctx->subnet_));
1928 callout_handle_state->on_completion_ = [call_back]() {
1930 };
1931 } else {
1932 processPacketPktSend(callout_handle, query, rsp, ctx->subnet_);
1933 processPacketBufferSend(callout_handle, rsp);
1934 }
1935 });
1936 }
1937
1938 try {
1939 // Call all installed callouts
1940 HooksManager::callCallouts(hook_idx, *callout_handle);
1941 } catch (...) {
1942 // Make sure we don't orphan a parked packet.
1943 if (allow_answer_park) {
1944 HooksManager::drop(hook_label, query);
1945 }
1946
1947 throw;
1948 }
1949
1950 if ((callout_handle->getStatus() == CalloutHandle::NEXT_STEP_PARK) &&
1951 allow_answer_park) {
1952 LOG_DEBUG(hooks_logger, DBG_DHCP4_HOOKS, pkt_park_msg)
1953 .arg(query->getLabel());
1954 // Since the hook library(ies) are going to do the unparking, then
1955 // reset the pointer to the response to indicate to the caller that
1956 // it should return, as the packet processing will continue via
1957 // the callback.
1958 rsp.reset();
1959 } else {
1960 // Drop the park job on the packet, it isn't needed.
1961 HooksManager::drop(hook_label, query);
1962 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP) {
1964 .arg(query->getLabel());
1965 rsp.reset();
1966 }
1967 }
1968 }
1969 }
1970
1971 // If we have a response prep it for shipment.
1972 if (rsp) {
1973 ConstSubnet4Ptr subnet = (ctx ? ctx->subnet_ : ConstSubnet4Ptr());
1974 processPacketPktSend(callout_handle, query, rsp, subnet);
1975 }
1976 return (rsp);
1977}
1978
1979void
1981 Pkt4Ptr& query, Pkt4Ptr& rsp,
1982 ConstSubnet4Ptr& subnet) {
1983 try {
1984 processPacketPktSend(callout_handle, query, rsp, subnet);
1985 processPacketBufferSend(callout_handle, rsp);
1986 } catch (const std::exception& e) {
1988 .arg(query->getLabel())
1989 .arg(e.what());
1990 } catch (...) {
1992 .arg(query->getLabel());
1993 }
1994}
1995
1996void
1998 Pkt4Ptr& query, Pkt4Ptr& rsp,
1999 ConstSubnet4Ptr& subnet) {
2000 query->addPktEvent("process_completed");
2001 if (!rsp) {
2002 return;
2003 }
2004
2005 // Specifies if server should do the packing
2006 bool skip_pack = false;
2007
2008 // Execute all callouts registered for pkt4_send
2009 if (HooksManager::calloutsPresent(Hooks.hook_index_pkt4_send_)) {
2010
2011 // Use the RAII wrapper to make sure that the callout handle state is
2012 // reset when this object goes out of scope. All hook points must do
2013 // it to prevent possible circular dependency between the callout
2014 // handle and its arguments.
2015 ScopedCalloutHandleState callout_handle_state(callout_handle);
2016
2017 // Enable copying options from the query and response packets within
2018 // hook library.
2019 ScopedEnableOptionsCopy<Pkt4> query_resp_options_copy(query, rsp);
2020
2021 // Pass incoming packet as argument
2022 callout_handle->setArgument("query4", query);
2023
2024 // Set our response
2025 callout_handle->setArgument("response4", rsp);
2026
2027 // Pass in the selected subnet.
2028 callout_handle->setArgument("subnet4", subnet);
2029
2030 // Call all installed callouts
2031 HooksManager::callCallouts(Hooks.hook_index_pkt4_send_,
2032 *callout_handle);
2033
2034 // Callouts decided to skip the next processing step. The next
2035 // processing step would be to pack the packet (create wire data).
2036 // That step will be skipped if any callout sets skip flag.
2037 // It essentially means that the callout already did packing,
2038 // so the server does not have to do it again.
2039 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) {
2041 .arg(query->getLabel());
2042 skip_pack = true;
2043 }
2044
2046 if (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP) {
2048 .arg(rsp->getLabel());
2049 rsp.reset();
2050 return;
2051 }
2052 }
2053
2054 if (!skip_pack) {
2055 try {
2057 .arg(rsp->getLabel());
2058 rsp->pack();
2059 } catch (const std::exception& e) {
2061 .arg(rsp->getLabel())
2062 .arg(e.what());
2063 }
2064 }
2065}
2066
2067void
2069 Pkt4Ptr& rsp) {
2070 if (!rsp) {
2071 return;
2072 }
2073
2074 try {
2075 // Now all fields and options are constructed into output wire buffer.
2076 // Option objects modification does not make sense anymore. Hooks
2077 // can only manipulate wire buffer at this stage.
2078 // Let's execute all callouts registered for buffer4_send
2079 if (HooksManager::calloutsPresent(Hooks.hook_index_buffer4_send_)) {
2080
2081 // Use the RAII wrapper to make sure that the callout handle state is
2082 // reset when this object goes out of scope. All hook points must do
2083 // it to prevent possible circular dependency between the callout
2084 // handle and its arguments.
2085 ScopedCalloutHandleState callout_handle_state(callout_handle);
2086
2087 // Enable copying options from the packet within hook library.
2088 ScopedEnableOptionsCopy<Pkt4> resp4_options_copy(rsp);
2089
2090 // Pass incoming packet as argument
2091 callout_handle->setArgument("response4", rsp);
2092
2093 // Call callouts
2094 HooksManager::callCallouts(Hooks.hook_index_buffer4_send_,
2095 *callout_handle);
2096
2097 // Callouts decided to skip the next processing step. The next
2098 // processing step would be to parse the packet, so skip at this
2099 // stage means drop.
2100 if ((callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) ||
2101 (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP)) {
2104 .arg(rsp->getLabel());
2105 return;
2106 }
2107
2108 callout_handle->getArgument("response4", rsp);
2109 }
2110
2112 .arg(rsp->getLabel())
2113 .arg(rsp->getName())
2114 .arg(static_cast<int>(rsp->getType()))
2115 .arg(rsp->getLocalAddr().isV4Zero() ? "*" : rsp->getLocalAddr().toText())
2116 .arg(rsp->getLocalPort())
2117 .arg(rsp->getRemoteAddr())
2118 .arg(rsp->getRemotePort())
2119 .arg(rsp->getIface().empty() ? "to be determined from routing" :
2120 rsp->getIface());
2121
2124 .arg(rsp->getLabel())
2125 .arg(rsp->getName())
2126 .arg(static_cast<int>(rsp->getType()))
2127 .arg(rsp->toText(true));
2128 sendPacket(rsp);
2129
2130 // Update statistics accordingly for sent packet.
2131 processStatsSent(rsp);
2132
2133 } catch (const std::exception& e) {
2135 .arg(rsp->getLabel())
2136 .arg(e.what());
2137 }
2138}
2139
2140string
2142 if (!srvid) {
2143 isc_throw(BadValue, "NULL pointer passed to srvidToString()");
2144 }
2145 boost::shared_ptr<Option4AddrLst> generated =
2146 boost::dynamic_pointer_cast<Option4AddrLst>(srvid);
2147 if (!srvid) {
2148 isc_throw(BadValue, "Pointer to invalid option passed to srvidToString()");
2149 }
2150
2151 Option4AddrLst::AddressContainer addrs = generated->getAddresses();
2152 if (addrs.size() != 1) {
2153 isc_throw(BadValue, "Malformed option passed to srvidToString(). "
2154 << "Expected to contain a single IPv4 address.");
2155 }
2156
2157 return (addrs[0].toText());
2158}
2159
2160void
2162
2163 // Do not append generated server identifier if there is one appended already.
2164 // This is when explicitly configured server identifier option is present.
2165 if (ex.getResponse()->getOption(DHO_DHCP_SERVER_IDENTIFIER)) {
2166 return;
2167 }
2168
2169 // Use local address on which the packet has been received as a
2170 // server identifier. In some cases it may be a different address,
2171 // e.g. broadcast packet or DHCPv4o6 packet.
2172 IOAddress local_addr = ex.getQuery()->getLocalAddr();
2173 Pkt4Ptr query = ex.getQuery();
2174
2175 if (local_addr.isV4Bcast() || query->isDhcp4o6()) {
2176 local_addr = IfaceMgr::instance().getSocket(query).addr_;
2177 }
2178
2179 static const OptionDefinition& server_id_def = LibDHCP::DHO_DHCP_SERVER_IDENTIFIER_DEF();
2180 OptionCustomPtr opt_srvid(new OptionCustom(server_id_def, Option::V4));
2181 opt_srvid->writeAddress(local_addr);
2182 ex.getResponse()->addOption(opt_srvid);
2183}
2184
2185void
2187 CfgOptionList& co_list = ex.getCfgOptionList();
2188
2189 // Retrieve subnet.
2190 ConstSubnet4Ptr subnet = ex.getContext()->subnet_;
2191 if (!subnet) {
2192 // All methods using the CfgOptionList object return soon when
2193 // there is no subnet so do the same
2194 return;
2195 }
2196
2197 // Firstly, host specific options.
2198 const ConstHostPtr& host = ex.getContext()->currentHost();
2199 if (host && !host->getCfgOption4()->empty()) {
2200 co_list.push_back(host->getCfgOption4());
2201 }
2202
2203 // Secondly, pool specific options.
2204 Pkt4Ptr resp = ex.getResponse();
2206 if (resp) {
2207 addr = resp->getYiaddr();
2208 }
2209 if (!addr.isV4Zero()) {
2210 PoolPtr pool = subnet->getPool(Lease::TYPE_V4, addr, false);
2211 if (pool && !pool->getCfgOption()->empty()) {
2212 co_list.push_back(pool->getCfgOption());
2213 }
2214 }
2215
2216 // Thirdly, subnet configured options.
2217 if (!subnet->getCfgOption()->empty()) {
2218 co_list.push_back(subnet->getCfgOption());
2219 }
2220
2221 // Fourthly, shared network specific options.
2222 SharedNetwork4Ptr network;
2223 subnet->getSharedNetwork(network);
2224 if (network && !network->getCfgOption()->empty()) {
2225 co_list.push_back(network->getCfgOption());
2226 }
2227
2228 // Each class in the incoming packet
2229 const ClientClasses& classes = ex.getQuery()->getClasses();
2230 for (auto const& cclass : classes) {
2231 // Find the client class definition for this class
2233 getClientClassDictionary()->findClass(cclass);
2234 if (!ccdef) {
2235 // Not found: the class is built-in or not configured
2236 if (!isClientClassBuiltIn(cclass)) {
2238 .arg(ex.getQuery()->getLabel())
2239 .arg(cclass);
2240 }
2241 // Skip it
2242 continue;
2243 }
2244
2245 if (ccdef->getCfgOption()->empty()) {
2246 // Skip classes which don't configure options
2247 continue;
2248 }
2249
2250 co_list.push_back(ccdef->getCfgOption());
2251 }
2252
2253 // Last global options
2254 if (!CfgMgr::instance().getCurrentCfg()->getCfgOption()->empty()) {
2255 co_list.push_back(CfgMgr::instance().getCurrentCfg()->getCfgOption());
2256 }
2257}
2258
2259void
2261 // Get the subnet relevant for the client. We will need it
2262 // to get the options associated with it.
2263 ConstSubnet4Ptr subnet = ex.getContext()->subnet_;
2264 // If we can't find the subnet for the client there is no way
2265 // to get the options to be sent to a client. We don't log an
2266 // error because it will be logged by the assignLease method
2267 // anyway.
2268 if (!subnet) {
2269 return;
2270 }
2271
2272 // Unlikely short cut
2273 const CfgOptionList& co_list = ex.getCfgOptionList();
2274 if (co_list.empty()) {
2275 return;
2276 }
2277
2278 Pkt4Ptr query = ex.getQuery();
2279 Pkt4Ptr resp = ex.getResponse();
2280 set<uint8_t> requested_opts;
2281
2282 // try to get the 'Parameter Request List' option which holds the
2283 // codes of requested options.
2284 OptionUint8ArrayPtr option_prl = boost::dynamic_pointer_cast<
2286
2287 // Get the list of options that client requested.
2288 if (option_prl) {
2289 for (uint16_t code : option_prl->getValues()) {
2290 static_cast<void>(requested_opts.insert(code));
2291 }
2292 }
2293
2294 std::set<uint8_t> cancelled_opts;
2295 const auto& cclasses = query->getClasses();
2296
2297 // Iterate on the configured option list to add persistent and
2298 // cancelled options.
2299 for (auto const& copts : co_list) {
2300 const OptionContainerPtr& opts = copts->getAll(DHCP4_OPTION_SPACE);
2301 if (!opts) {
2302 continue;
2303 }
2304 // Get persistent options.
2305 const OptionContainerPersistIndex& pidx = opts->get<2>();
2306 const OptionContainerPersistRange& prange = pidx.equal_range(true);
2307 BOOST_FOREACH(auto const& desc, prange) {
2308 // Add the persistent option code to requested options.
2309 if (desc.option_) {
2310 uint8_t code = static_cast<uint8_t>(desc.option_->getType());
2311 static_cast<void>(requested_opts.insert(code));
2312 }
2313 }
2314 // Get cancelled options.
2315 const OptionContainerCancelIndex& cidx = opts->get<5>();
2316 const OptionContainerCancelRange& crange = cidx.equal_range(true);
2317 BOOST_FOREACH(auto const& desc, crange) {
2318 // Add the cancelled option code to cancelled options.
2319 if (desc.option_) {
2320 uint8_t code = static_cast<uint8_t>(desc.option_->getType());
2321 static_cast<void>(cancelled_opts.insert(code));
2322 }
2323 }
2324 }
2325
2326 // For each requested option code get the first instance of the option
2327 // to be returned to the client.
2328 for (uint8_t opt : requested_opts) {
2329 if (cancelled_opts.count(opt) > 0) {
2330 continue;
2331 }
2332 // Skip special cases: DHO_VIVSO_SUBOPTIONS.
2333 if (opt == DHO_VIVSO_SUBOPTIONS) {
2334 continue;
2335 }
2336 // Add nothing when it is already there.
2337 if (!resp->getOption(opt)) {
2338 // Iterate on the configured option list
2339 for (auto const& copts : co_list) {
2341 opt, cclasses);
2342 if (desc.option_) {
2343 // Got it: add it and jump to the outer loop
2344 resp->addOption(desc.option_);
2345 break;
2346 }
2347 }
2348 }
2349 }
2350
2351 // Special cases for vendor class and options which are identified
2352 // by the code/type and the vendor/enterprise id vs. the code/type only.
2353 if ((requested_opts.count(DHO_VIVCO_SUBOPTIONS) > 0) &&
2354 (cancelled_opts.count(DHO_VIVCO_SUBOPTIONS) == 0)) {
2355 // Keep vendor ids which are already in the response to insert
2356 // VIVCO options at most once per vendor.
2357 set<uint32_t> vendor_ids;
2358 // Get what already exists in the response.
2359 for (auto const& opt : resp->getOptions(DHO_VIVCO_SUBOPTIONS)) {
2360 OptionVendorClassPtr vendor_opts;
2361 vendor_opts = boost::dynamic_pointer_cast<OptionVendorClass>(opt.second);
2362 if (vendor_opts) {
2363 uint32_t vendor_id = vendor_opts->getVendorId();
2364 static_cast<void>(vendor_ids.insert(vendor_id));
2365 }
2366 }
2367 // Iterate on the configured option list.
2368 for (auto const& copts : co_list) {
2369 for (auto const& desc : copts->getList(DHCP4_OPTION_SPACE,
2371 if (!desc.option_ || !desc.allowedForClientClasses(cclasses)) {
2372 continue;
2373 }
2374 OptionVendorClassPtr vendor_opts =
2375 boost::dynamic_pointer_cast<OptionVendorClass>(desc.option_);
2376 if (!vendor_opts) {
2377 continue;
2378 }
2379 // Is the vendor id already in the response?
2380 uint32_t vendor_id = vendor_opts->getVendorId();
2381 if (vendor_ids.count(vendor_id) > 0) {
2382 continue;
2383 }
2384 // Got it: add it.
2385 resp->Pkt::addOption(desc.option_);
2386 static_cast<void>(vendor_ids.insert(vendor_id));
2387 }
2388 }
2389 }
2390
2391 if ((requested_opts.count(DHO_VIVSO_SUBOPTIONS) > 0) &&
2392 (cancelled_opts.count(DHO_VIVSO_SUBOPTIONS) == 0)) {
2393 // Keep vendor ids which are already in the response to insert
2394 // VIVSO options at most once per vendor.
2395 set<uint32_t> vendor_ids;
2396 // Get what already exists in the response.
2397 for (auto const& opt : resp->getOptions(DHO_VIVSO_SUBOPTIONS)) {
2398 OptionVendorPtr vendor_opts;
2399 vendor_opts = boost::dynamic_pointer_cast<OptionVendor>(opt.second);
2400 if (vendor_opts) {
2401 uint32_t vendor_id = vendor_opts->getVendorId();
2402 static_cast<void>(vendor_ids.insert(vendor_id));
2403 }
2404 }
2405 // Iterate on the configured option list
2406 for (auto const& copts : co_list) {
2407 for (auto const& desc : copts->getList(DHCP4_OPTION_SPACE,
2409 if (!desc.option_ || !desc.allowedForClientClasses(cclasses)) {
2410 continue;
2411 }
2412 OptionVendorPtr vendor_opts =
2413 boost::dynamic_pointer_cast<OptionVendor>(desc.option_);
2414 if (!vendor_opts) {
2415 continue;
2416 }
2417 // Is the vendor id already in the response?
2418 uint32_t vendor_id = vendor_opts->getVendorId();
2419 if (vendor_ids.count(vendor_id) > 0) {
2420 continue;
2421 }
2422 // Append a fresh vendor option as the next method should
2423 // add suboptions to it.
2424 vendor_opts.reset(new OptionVendor(Option::V4, vendor_id));
2425 resp->Pkt::addOption(vendor_opts);
2426 static_cast<void>(vendor_ids.insert(vendor_id));
2427 }
2428 }
2429 }
2430}
2431
2432void
2434 // Get the configured subnet suitable for the incoming packet.
2435 ConstSubnet4Ptr subnet = ex.getContext()->subnet_;
2436
2437 const CfgOptionList& co_list = ex.getCfgOptionList();
2438
2439 // Leave if there is no subnet matching the incoming packet.
2440 // There is no need to log the error message here because
2441 // it will be logged in the assignLease() when it fails to
2442 // pick the suitable subnet. We don't want to duplicate
2443 // error messages in such case.
2444 //
2445 // Also, if there's no options to possibly assign, give up.
2446 if (!subnet || co_list.empty()) {
2447 return;
2448 }
2449
2450 Pkt4Ptr query = ex.getQuery();
2451 Pkt4Ptr resp = ex.getResponse();
2452 set<uint32_t> vendor_ids;
2453
2454 // The server could have provided the option using client classification or
2455 // hooks. If there're vendor info options in the response already, use them.
2456 map<uint32_t, OptionVendorPtr> vendor_rsps;
2457 for (auto const& opt : resp->getOptions(DHO_VIVSO_SUBOPTIONS)) {
2458 OptionVendorPtr vendor_rsp;
2459 vendor_rsp = boost::dynamic_pointer_cast<OptionVendor>(opt.second);
2460 if (vendor_rsp) {
2461 uint32_t vendor_id = vendor_rsp->getVendorId();
2462 vendor_rsps[vendor_id] = vendor_rsp;
2463 static_cast<void>(vendor_ids.insert(vendor_id));
2464 }
2465 }
2466
2467 // Next, try to get the vendor-id from the client packet's
2468 // vendor-specific information option (125).
2469 map<uint32_t, OptionVendorPtr> vendor_reqs;
2470 for (auto const& opt : query->getOptions(DHO_VIVSO_SUBOPTIONS)) {
2471 OptionVendorPtr vendor_req;
2472 vendor_req = boost::dynamic_pointer_cast<OptionVendor>(opt.second);
2473 if (vendor_req) {
2474 uint32_t vendor_id = vendor_req->getVendorId();
2475 vendor_reqs[vendor_id] = vendor_req;
2476 static_cast<void>(vendor_ids.insert(vendor_id));
2477 }
2478 }
2479
2480 // Finally, try to get the vendor-id from the client packet's
2481 // vendor-specific class option (124).
2482 for (auto const& opt : query->getOptions(DHO_VIVCO_SUBOPTIONS)) {
2483 OptionVendorClassPtr vendor_class;
2484 vendor_class = boost::dynamic_pointer_cast<OptionVendorClass>(opt.second);
2485 if (vendor_class) {
2486 uint32_t vendor_id = vendor_class->getVendorId();
2487 static_cast<void>(vendor_ids.insert(vendor_id));
2488 }
2489 }
2490
2491 // If there's no vendor option in either request or response, then there's no way
2492 // to figure out what the vendor-id values are and we give up.
2493 if (vendor_ids.empty()) {
2494 return;
2495 }
2496
2497 map<uint32_t, set<uint8_t> > requested_opts;
2498
2499 // Let's try to get ORO within that vendor-option.
2500 // This is specific to vendor-id=4491 (Cable Labs). Other vendors may have
2501 // different policies.
2503 if (vendor_reqs.count(VENDOR_ID_CABLE_LABS) > 0) {
2504 OptionVendorPtr vendor_req = vendor_reqs[VENDOR_ID_CABLE_LABS];
2505 OptionPtr oro_generic = vendor_req->getOption(DOCSIS3_V4_ORO);
2506 if (oro_generic) {
2507 // Vendor ID 4491 makes Kea look at DOCSIS3_V4_OPTION_DEFINITIONS
2508 // when parsing options. Based on that, oro_generic will have been
2509 // created as an OptionUint8Array, but might not be for other
2510 // vendor IDs.
2511 oro = boost::dynamic_pointer_cast<OptionUint8Array>(oro_generic);
2512 }
2513 if (oro) {
2514 set<uint8_t> oro_req_opts;
2515 for (uint8_t code : oro->getValues()) {
2516 static_cast<void>(oro_req_opts.insert(code));
2517 }
2518 requested_opts[VENDOR_ID_CABLE_LABS] = oro_req_opts;
2519 }
2520 }
2521
2522 const auto& cclasses = query->getClasses();
2523 for (uint32_t vendor_id : vendor_ids) {
2524
2525 std::set<uint8_t> cancelled_opts;
2526
2527 // Iterate on the configured option list to add persistent and
2528 // cancelled options,
2529 for (auto const& copts : co_list) {
2530 const OptionContainerPtr& opts = copts->getAll(vendor_id);
2531 if (!opts) {
2532 continue;
2533 }
2534
2535 // Get persistent options.
2536 const OptionContainerPersistIndex& pidx = opts->get<2>();
2537 const OptionContainerPersistRange& prange = pidx.equal_range(true);
2538 BOOST_FOREACH(auto const& desc, prange) {
2539 // Add the persistent option code to requested options.
2540 if (desc.option_) {
2541 uint8_t code = static_cast<uint8_t>(desc.option_->getType());
2542 static_cast<void>(requested_opts[vendor_id].insert(code));
2543 }
2544 }
2545
2546 // Get cancelled options.
2547 const OptionContainerCancelIndex& cidx = opts->get<5>();
2548 const OptionContainerCancelRange& crange = cidx.equal_range(true);
2549 BOOST_FOREACH(auto const& desc, crange) {
2550 // Add the cancelled option code to cancelled options.
2551 if (desc.option_) {
2552 uint8_t code = static_cast<uint8_t>(desc.option_->getType());
2553 static_cast<void>(cancelled_opts.insert(code));
2554 }
2555 }
2556 }
2557
2558 // If there is nothing to add don't do anything with this vendor.
2559 // This will explicitly not echo back vendor options from the request
2560 // that either correspond to a vendor not known to Kea even if the
2561 // option encapsulates data or there are no persistent options
2562 // configured for this vendor so Kea does not send any option back.
2563 if (requested_opts[vendor_id].empty()) {
2564 continue;
2565 }
2566
2567
2568 // It's possible that vivso was inserted already by client class or
2569 // a hook. If that is so, let's use it.
2570 OptionVendorPtr vendor_rsp;
2571 if (vendor_rsps.count(vendor_id) > 0) {
2572 vendor_rsp = vendor_rsps[vendor_id];
2573 } else {
2574 vendor_rsp.reset(new OptionVendor(Option::V4, vendor_id));
2575 }
2576
2577 // Get the list of options that client requested.
2578 bool added = false;
2579
2580 for (uint8_t opt : requested_opts[vendor_id]) {
2581 if (cancelled_opts.count(opt) > 0) {
2582 continue;
2583 }
2584 if (!vendor_rsp->getOption(opt)) {
2585 for (auto const& copts : co_list) {
2586 OptionDescriptor desc = copts->allowedForClientClasses(vendor_id,
2587 opt, cclasses);
2588 if (desc.option_) {
2589 vendor_rsp->addOption(desc.option_);
2590 added = true;
2591 break;
2592 }
2593 }
2594 }
2595 }
2596
2597 // If we added some sub-options and the vendor opts option is not in
2598 // the response already, then add it.
2599 if (added && (vendor_rsps.count(vendor_id) == 0)) {
2600 resp->Pkt::addOption(vendor_rsp);
2601 }
2602 }
2603}
2604
2605void
2607 // Identify options that we always want to send to the
2608 // client (if they are configured).
2609 static const std::vector<uint16_t> required_options = {
2614
2615 // Get the subnet.
2616 ConstSubnet4Ptr subnet = ex.getContext()->subnet_;
2617 if (!subnet) {
2618 return;
2619 }
2620
2621 // Unlikely short cut
2622 const CfgOptionList& co_list = ex.getCfgOptionList();
2623 if (co_list.empty()) {
2624 return;
2625 }
2626
2627 Pkt4Ptr resp = ex.getResponse();
2628 const auto& cclasses = ex.getQuery()->getClasses();
2629
2630 // Try to find all 'required' options in the outgoing
2631 // message. Those that are not present will be added.
2632 for (auto const& required : required_options) {
2633 OptionPtr opt = resp->getOption(required);
2634 if (!opt) {
2635 // Check whether option has been configured.
2636 for (auto const& copts : co_list) {
2638 required, cclasses);
2639 if (desc.option_) {
2640 resp->addOption(desc.option_);
2641 break;
2642 }
2643 }
2644 }
2645 }
2646}
2647
2648void
2650 // It is possible that client has sent both Client FQDN and Hostname
2651 // option. In that the server should prefer Client FQDN option and
2652 // ignore the Hostname option.
2653 try {
2654 Pkt4Ptr query = ex.getQuery();
2655 Pkt4Ptr resp = ex.getResponse();
2656 Option4ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<Option4ClientFqdn>
2657 (query->getOption(DHO_FQDN));
2658 if (fqdn) {
2660 .arg(query->getLabel());
2661 processClientFqdnOption(ex);
2662
2663 } else {
2666 .arg(query->getLabel());
2667 processHostnameOption(ex);
2668 }
2669
2670 // Based on the output option added to the response above, we figure out
2671 // the values for the hostname and dns flags to set in the context. These
2672 // will be used to populate the lease.
2673 std::string hostname;
2674 bool fqdn_fwd = false;
2675 bool fqdn_rev = false;
2676
2677 OptionStringPtr opt_hostname;
2678 fqdn = boost::dynamic_pointer_cast<Option4ClientFqdn>(resp->getOption(DHO_FQDN));
2679 if (fqdn) {
2680 hostname = fqdn->getDomainName();
2681 CfgMgr::instance().getD2ClientMgr().getUpdateDirections(*fqdn, fqdn_fwd, fqdn_rev);
2682 } else {
2683 opt_hostname = boost::dynamic_pointer_cast<OptionString>
2684 (resp->getOption(DHO_HOST_NAME));
2685
2686 if (opt_hostname) {
2687 hostname = opt_hostname->getValue();
2688 // DHO_HOST_NAME is string option which cannot be blank,
2689 // we use "." to know we should replace it with a fully
2690 // generated name. The local string variable needs to be
2691 // blank in logic below.
2692 if (hostname == ".") {
2693 hostname = "";
2694 }
2695
2698 if (ex.getContext()->getDdnsParams()->getEnableUpdates()) {
2699 fqdn_fwd = true;
2700 fqdn_rev = true;
2701 }
2702 }
2703 }
2704
2705 // Optionally, call a hook that may possibly override the decisions made
2706 // earlier.
2707 if (HooksManager::calloutsPresent(Hooks.hook_index_ddns4_update_)) {
2708 CalloutHandlePtr callout_handle = getCalloutHandle(query);
2709
2710 // Use the RAII wrapper to make sure that the callout handle state is
2711 // reset when this object goes out of scope. All hook points must do
2712 // it to prevent possible circular dependency between the callout
2713 // handle and its arguments.
2714 ScopedCalloutHandleState callout_handle_state(callout_handle);
2715
2716 // Setup the callout arguments.
2717 ConstSubnet4Ptr subnet = ex.getContext()->subnet_;
2718 callout_handle->setArgument("query4", query);
2719 callout_handle->setArgument("response4", resp);
2720 callout_handle->setArgument("subnet4", subnet);
2721 callout_handle->setArgument("hostname", hostname);
2722 callout_handle->setArgument("fwd-update", fqdn_fwd);
2723 callout_handle->setArgument("rev-update", fqdn_rev);
2724 callout_handle->setArgument("ddns-params", ex.getContext()->getDdnsParams());
2725
2726 // Call callouts
2727 HooksManager::callCallouts(Hooks.hook_index_ddns4_update_, *callout_handle);
2728
2729 // Let's get the parameters returned by hook.
2730 string hook_hostname;
2731 bool hook_fqdn_fwd = false;
2732 bool hook_fqdn_rev = false;
2733 callout_handle->getArgument("hostname", hook_hostname);
2734 callout_handle->getArgument("fwd-update", hook_fqdn_fwd);
2735 callout_handle->getArgument("rev-update", hook_fqdn_rev);
2736
2737 // If there's anything changed by the hook, log it and then update
2738 // the parameters.
2739 if ((hostname != hook_hostname) || (fqdn_fwd != hook_fqdn_fwd) ||
2740 (fqdn_rev != hook_fqdn_rev)) {
2742 .arg(hostname).arg(hook_hostname).arg(fqdn_fwd).arg(hook_fqdn_fwd)
2743 .arg(fqdn_rev).arg(hook_fqdn_rev);
2744 hostname = hook_hostname;
2745 fqdn_fwd = hook_fqdn_fwd;
2746 fqdn_rev = hook_fqdn_rev;
2747
2748 // If there's an outbound host-name option in the response we
2749 // need to updated it with the new host name.
2750 OptionStringPtr hostname_opt = boost::dynamic_pointer_cast<OptionString>
2751 (resp->getOption(DHO_HOST_NAME));
2752 if (hostname_opt) {
2753 hostname_opt->setValue(hook_hostname);
2754 }
2755
2756 // If there's an outbound FQDN option in the response we need
2757 // to update it with the new host name.
2758 fqdn = boost::dynamic_pointer_cast<Option4ClientFqdn>(resp->getOption(DHO_FQDN));
2759 if (fqdn) {
2760 fqdn->setDomainName(hook_hostname, Option4ClientFqdn::FULL);
2761 // Hook disabled updates, Set flags back to client accordingly.
2762 fqdn->setFlag(Option4ClientFqdn::FLAG_S, 0);
2763 fqdn->setFlag(Option4ClientFqdn::FLAG_N, 1);
2764 }
2765 }
2766 }
2767
2768 // Update the context
2769 auto ctx = ex.getContext();
2770 ctx->fwd_dns_update_ = fqdn_fwd;
2771 ctx->rev_dns_update_ = fqdn_rev;
2772 ctx->hostname_ = hostname;
2773
2774 } catch (const Exception& e) {
2775 // In some rare cases it is possible that the client's name processing
2776 // fails. For example, the Hostname option may be malformed, or there
2777 // may be an error in the server's logic which would cause multiple
2778 // attempts to add the same option to the response message. This
2779 // error message aggregates all these errors so they can be diagnosed
2780 // from the log. We don't want to throw an exception here because,
2781 // it will impact the processing of the whole packet. We rather want
2782 // the processing to continue, even if the client's name is wrong.
2784 .arg(ex.getQuery()->getLabel())
2785 .arg(e.what());
2786 }
2787}
2788
2789void
2790Dhcpv4Srv::processClientFqdnOption(Dhcpv4Exchange& ex) {
2791 // Obtain the FQDN option from the client's message.
2792 Option4ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<
2793 Option4ClientFqdn>(ex.getQuery()->getOption(DHO_FQDN));
2794
2796 .arg(ex.getQuery()->getLabel())
2797 .arg(fqdn->toText());
2798
2799 // Create the DHCPv4 Client FQDN Option to be included in the server's
2800 // response to a client.
2801 Option4ClientFqdnPtr fqdn_resp(new Option4ClientFqdn(*fqdn));
2802
2803 // Set the server S, N, and O flags based on client's flags and
2804 // current configuration.
2806 d2_mgr.adjustFqdnFlags<Option4ClientFqdn>(*fqdn, *fqdn_resp,
2807 *(ex.getContext()->getDdnsParams()));
2808 // Carry over the client's E flag.
2811
2812 if (ex.getContext()->currentHost() &&
2813 !ex.getContext()->currentHost()->getHostname().empty()) {
2814 fqdn_resp->setDomainName(d2_mgr.qualifyName(ex.getContext()->currentHost()->getHostname(),
2815 *(ex.getContext()->getDdnsParams()), true),
2817
2818 } else {
2819 // Adjust the domain name based on domain name value and type sent by the
2820 // client and current configuration.
2821 try {
2822 d2_mgr.adjustDomainName<Option4ClientFqdn>(*fqdn, *fqdn_resp,
2823 *(ex.getContext()->getDdnsParams()));
2824 } catch (const FQDNScrubbedEmpty& scrubbed) {
2826 .arg(ex.getQuery()->getLabel())
2827 .arg(scrubbed.what());
2828 return;
2829 }
2830 }
2831
2832 // Add FQDN option to the response message. Note that, there may be some
2833 // cases when server may choose not to include the FQDN option in a
2834 // response to a client. In such cases, the FQDN should be removed from the
2835 // outgoing message. In theory we could cease to include the FQDN option
2836 // in this function until it is confirmed that it should be included.
2837 // However, we include it here for simplicity. Functions used to acquire
2838 // lease for a client will scan the response message for FQDN and if it
2839 // is found they will take necessary actions to store the FQDN information
2840 // in the lease database as well as to generate NameChangeRequests to DNS.
2841 // If we don't store the option in the response message, we will have to
2842 // propagate it in the different way to the functions which acquire the
2843 // lease. This would require modifications to the API of this class.
2845 .arg(ex.getQuery()->getLabel())
2846 .arg(fqdn_resp->toText());
2847 ex.getResponse()->addOption(fqdn_resp);
2848}
2849
2850void
2851Dhcpv4Srv::processHostnameOption(Dhcpv4Exchange& ex) {
2852 // Fetch D2 configuration.
2853 D2ClientMgr& d2_mgr = CfgMgr::instance().getD2ClientMgr();
2854
2855 // Obtain the Hostname option from the client's message.
2856 OptionStringPtr opt_hostname = boost::dynamic_pointer_cast<OptionString>
2857 (ex.getQuery()->getOption(DHO_HOST_NAME));
2858
2859 if (opt_hostname) {
2861 .arg(ex.getQuery()->getLabel())
2862 .arg(opt_hostname->getValue());
2863 }
2864
2866
2867 // Hostname reservations take precedence over any other configuration,
2868 // i.e. DDNS configuration. If we have a reserved hostname we should
2869 // use it and send it back.
2870 if (ctx->currentHost() && !ctx->currentHost()->getHostname().empty()) {
2871 // Qualify if there is a suffix configured.
2872 std::string hostname = d2_mgr.qualifyName(ctx->currentHost()->getHostname(),
2873 *(ex.getContext()->getDdnsParams()), false);
2874 // Convert it to lower case.
2875 boost::algorithm::to_lower(hostname);
2877 .arg(ex.getQuery()->getLabel())
2878 .arg(hostname);
2879
2880 // Add it to the response
2881 OptionStringPtr opt_hostname_resp(new OptionString(Option::V4, DHO_HOST_NAME, hostname));
2882 ex.getResponse()->addOption(opt_hostname_resp);
2883
2884 // We're done here.
2885 return;
2886 }
2887
2888 // There is no reservation for this client however there is still a
2889 // possibility that we'll have to send hostname option to this client
2890 // if the client has included hostname option or the configuration of
2891 // the server requires that we send the option regardless.
2892 D2ClientConfig::ReplaceClientNameMode replace_name_mode =
2893 ex.getContext()->getDdnsParams()->getReplaceClientNameMode();
2894
2895 // If we don't have a hostname then either we'll supply it or do nothing.
2896 if (!opt_hostname) {
2897 // If we're configured to supply it then add it to the response.
2898 // Use the root domain to signal later on that we should replace it.
2899 if (replace_name_mode == D2ClientConfig::RCM_ALWAYS ||
2900 replace_name_mode == D2ClientConfig::RCM_WHEN_NOT_PRESENT) {
2903 .arg(ex.getQuery()->getLabel());
2904 OptionStringPtr opt_hostname_resp(new OptionString(Option::V4,
2906 "."));
2907 ex.getResponse()->addOption(opt_hostname_resp);
2908 }
2909
2910 return;
2911 }
2912
2913 // Client sent us a hostname option so figure out what to do with it.
2915 .arg(ex.getQuery()->getLabel())
2916 .arg(opt_hostname->getValue());
2917
2918 std::string hostname = isc::util::str::trim(opt_hostname->getValue());
2919 unsigned int label_count;
2920
2921 try {
2922 // Parsing into labels can throw on malformed content so we're
2923 // going to explicitly catch that here.
2924 label_count = OptionDataTypeUtil::getLabelCount(hostname);
2925 } catch (const std::exception& exc) {
2927 .arg(ex.getQuery()->getLabel())
2928 .arg(exc.what());
2929 return;
2930 }
2931
2932 // The hostname option sent by the client should be at least 1 octet long.
2933 // If it isn't we ignore this option. (Per RFC 2131, section 3.14)
2936 if (label_count == 0) {
2938 .arg(ex.getQuery()->getLabel());
2939 return;
2940 }
2941
2942 // Stores the value we eventually use, so we can send it back.
2943 OptionStringPtr opt_hostname_resp;
2944
2945 // The hostname option may be unqualified or fully qualified. The lab_count
2946 // holds the number of labels for the name. The number of 1 means that
2947 // there is only root label "." (even for unqualified names, as the
2948 // getLabelCount function treats each name as a fully qualified one).
2949 // By checking the number of labels present in the hostname we may infer
2950 // whether client has sent the fully qualified or unqualified hostname.
2951
2952 if ((replace_name_mode == D2ClientConfig::RCM_ALWAYS ||
2953 replace_name_mode == D2ClientConfig::RCM_WHEN_PRESENT)
2954 || label_count < 2) {
2955 // Set to root domain to signal later on that we should replace it.
2956 // DHO_HOST_NAME is a string option which cannot be empty.
2964 opt_hostname_resp.reset(new OptionString(Option::V4, DHO_HOST_NAME, "."));
2965 } else {
2966 // Sanitize the name the client sent us, if we're configured to do so.
2968 ex.getContext()->getDdnsParams()->getHostnameSanitizer();
2969
2970 if (sanitizer) {
2971 auto tmp = sanitizer->scrub(hostname);
2972 if (tmp.empty()) {
2974 .arg(ex.getQuery()->getLabel())
2975 .arg(hostname);
2976 return;
2977 }
2978
2979 hostname = tmp;
2980 }
2981
2982 // Convert hostname to lower case.
2983 boost::algorithm::to_lower(hostname);
2984
2985 if (label_count == 2) {
2986 // If there are two labels, it means that the client has specified
2987 // the unqualified name. We have to concatenate the unqualified name
2988 // with the domain name. The false value passed as a second argument
2989 // indicates that the trailing dot should not be appended to the
2990 // hostname. We don't want to append the trailing dot because
2991 // we don't know whether the hostname is partial or not and some
2992 // clients do not handle the hostnames with the trailing dot.
2993 opt_hostname_resp.reset(
2994 new OptionString(Option::V4, DHO_HOST_NAME,
2995 d2_mgr.qualifyName(hostname, *(ex.getContext()->getDdnsParams()),
2996 false)));
2997 } else {
2998 opt_hostname_resp.reset(new OptionString(Option::V4, DHO_HOST_NAME, hostname));
2999 }
3000 }
3001
3003 .arg(ex.getQuery()->getLabel())
3004 .arg(opt_hostname_resp->getValue());
3005 ex.getResponse()->addOption(opt_hostname_resp);
3006}
3007
3008void
3010 const Lease4Ptr& old_lease,
3011 const DdnsParams& ddns_params) {
3012 if (!lease) {
3014 "NULL lease specified when creating NameChangeRequest");
3015 }
3016
3017 // Nothing to do if updates are not enabled.
3018 if (!ddns_params.getEnableUpdates()) {
3019 return;
3020 }
3021
3022 if ((lease->reuseable_valid_lft_ == 0) &&
3023 (!old_lease || ddns_params.getUpdateOnRenew() ||
3024 !lease->hasIdenticalFqdn(*old_lease))) {
3025 if (old_lease) {
3026 // Queue's up a remove of the old lease's DNS (if needed)
3027 queueNCR(CHG_REMOVE, old_lease);
3028 }
3029
3030 // We may need to generate the NameChangeRequest for the new lease. It
3031 // will be generated only if hostname is set and if forward or reverse
3032 // update has been requested.
3033 queueNCR(CHG_ADD, lease);
3034 }
3035}
3036
3037bool
3039 const ClientClasses& client_classes) {
3040 ConstSubnet4Ptr current_subnet = subnet;
3041 // Try subnets.
3042 while (current_subnet) {
3043 const ConstCfgOptionPtr& co = current_subnet->getCfgOption();
3044 if (!co->empty()) {
3045 OptionDescriptor desc = co->get(DHCP4_OPTION_SPACE,
3047 if (desc.option_) {
3048 subnet = current_subnet;
3049 return (true);
3050 }
3051 }
3052 current_subnet = current_subnet->getNextSubnet(subnet, client_classes);
3053 }
3054 // Try the shared network.
3055 SharedNetwork4Ptr network;
3056 subnet->getSharedNetwork(network);
3057 if (network) {
3058 const ConstCfgOptionPtr& co = network->getCfgOption();
3059 if (!co->empty()) {
3060 OptionDescriptor desc = co->get(DHCP4_OPTION_SPACE,
3062 if (desc.option_) {
3063 return (true);
3064 }
3065 }
3066 }
3067 return (false);
3068}
3069
3070void
3072 Pkt4Ptr query = ex.getQuery();
3073 Pkt4Ptr resp = ex.getResponse();
3074 resp->setType(DHCPNAK);
3075 resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
3077 .arg(query->getLabel())
3078 .arg(query->toText());
3079}
3080
3081void
3083 // Get the pointers to the query and the response messages.
3084 Pkt4Ptr query = ex.getQuery();
3085 Pkt4Ptr resp = ex.getResponse();
3086
3087 // Get the context.
3089
3090 // Subnet should have been already selected when the context was created.
3091 ConstSubnet4Ptr subnet = ctx->subnet_;
3092
3093 // "Fake" allocation is processing of DISCOVER message. We pretend to do an
3094 // allocation, but we do not put the lease in the database. That is ok,
3095 // because we do not guarantee that the user will get that exact lease. If
3096 // the user selects this server to do actual allocation (i.e. sends REQUEST)
3097 // it should include this hint. That will help us during the actual lease
3098 // allocation.
3099 bool fake_allocation = (query->getType() == DHCPDISCOVER);
3100
3101 if (subnet) {
3102 // Check if IPv6-Only Preferred was requested.
3103 OptionUint8ArrayPtr option_prl = boost::dynamic_pointer_cast<
3105 if (option_prl) {
3106 auto const& requested_opts = option_prl->getValues();
3107 if ((std::find(requested_opts.cbegin(), requested_opts.cend(),
3108 DHO_V6_ONLY_PREFERRED) != requested_opts.cend()) &&
3109 assignZero(subnet, query->getClasses())) {
3110 ex.setIPv6OnlyPreferred(true);
3111 ctx->subnet_ = subnet;
3112 resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
3113 if (!fake_allocation) {
3114 resp->setCiaddr(query->getCiaddr());
3115 }
3116 return;
3117 }
3118 }
3119 }
3120
3121 // Get the server identifier. It will be used to determine the state
3122 // of the client.
3123 OptionCustomPtr opt_serverid = boost::dynamic_pointer_cast<
3124 OptionCustom>(query->getOption(DHO_DHCP_SERVER_IDENTIFIER));
3125
3126 // Check if the client has sent a requested IP address option or
3127 // ciaddr.
3128 OptionCustomPtr opt_requested_address = boost::dynamic_pointer_cast<
3129 OptionCustom>(query->getOption(DHO_DHCP_REQUESTED_ADDRESS));
3131 if (opt_requested_address) {
3132 hint = opt_requested_address->readAddress();
3133
3134 } else if (!query->getCiaddr().isV4Zero()) {
3135 hint = query->getCiaddr();
3136
3137 }
3138
3139 // This flag controls whether or not the server should respond to the clients
3140 // in the INIT-REBOOT state. We will initialize it to a configured value only
3141 // when the client is in that state.
3142 auto authoritative = false;
3143
3144 // If there is no server id and there is a Requested IP Address option
3145 // the client is in the INIT-REBOOT state in which the server has to
3146 // determine whether the client's notion of the address is correct
3147 // and whether the client is known, i.e., has a lease.
3148 auto init_reboot = (!fake_allocation && !opt_serverid && opt_requested_address);
3149
3150 if (init_reboot) {
3152 .arg(query->getLabel())
3153 .arg(hint.toText());
3154
3155 // Find the authoritative flag configuration.
3156 if (subnet) {
3157 authoritative = subnet->getAuthoritative();
3158 } else {
3159 // If there is no subnet, use the global value.
3160 auto flag = CfgMgr::instance().getCurrentCfg()->getConfiguredGlobals()->
3162 if (flag && (flag->getType() == data::Element::boolean)) {
3163 authoritative = flag->boolValue();
3164 }
3165 }
3166 } else if (fake_allocation) {
3168 .arg(query->getLabel())
3169 .arg(hint != IOAddress::IPV4_ZERO_ADDRESS() ? hint.toText() : "(no hint)");
3170 } else {
3172 .arg(query->getLabel())
3173 .arg(hint != IOAddress::IPV4_ZERO_ADDRESS() ? hint.toText() : "(no hint)");
3174 }
3175
3176 // If there is no subnet configuration for that client we ignore the
3177 // request from the INIT-REBOOT client if we're not authoritative, because
3178 // we don't know whether the network configuration is correct for this
3179 // client. We return DHCPNAK if we're authoritative, though.
3180 if (!subnet) {
3181 // This particular client is out of luck today. We do not have
3182 // information about the subnet he is connected to. This likely means
3183 // misconfiguration of the server (or some relays).
3184
3185 // If it's a rebind, quietly drop it.
3186 if (!fake_allocation && !opt_serverid && !opt_requested_address
3187 && !query->getCiaddr().isV4Zero() && query->getLocalAddr().isV4Bcast()) {
3188 ex.deleteResponse();
3189 return;
3190 }
3191
3192 if (!init_reboot || authoritative) {
3193 // Perhaps this should be logged on some higher level?
3195 .arg(query->getLabel())
3196 .arg(query->getRemoteAddr().toText())
3197 .arg(query->getName());
3198 resp->setType(DHCPNAK);
3199 resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
3200 return;
3201 }
3202 }
3203
3204 HWAddrPtr hwaddr = query->getHWAddr();
3205
3206 ConstSubnet4Ptr original_subnet = subnet;
3207
3208 // Get client-id. It is not mandatory in DHCPv4.
3209 ClientIdPtr client_id = ex.getContext()->clientid_;
3210
3211 // In the INIT-REBOOT state, a client remembering its previously assigned
3212 // address is trying to confirm whether or not this address is still usable.
3213 if (init_reboot) {
3214 Lease4Ptr lease;
3215
3216 auto const& classes = query->getClasses();
3217
3218 // We used to issue a separate query (two actually: one for client-id
3219 // and another one for hw-addr for) each subnet in the shared network.
3220 // That was horribly inefficient if the client didn't have any lease
3221 // (or there were many subnets and the client happened to be in one
3222 // of the last subnets).
3223 //
3224 // We now issue at most two queries: get all the leases for specific
3225 // client-id and then get all leases for specific hw-address.
3226 if (original_subnet && client_id) {
3227
3228 // Get all the leases for this client-id
3229 Lease4Collection leases_client_id = LeaseMgrFactory::instance().getLease4(*client_id);
3230 if (!leases_client_id.empty()) {
3231 ConstSubnet4Ptr s = original_subnet;
3232
3233 // Among those returned try to find a lease that belongs to
3234 // current shared network.
3235 while (s) {
3236 for (auto const& l : leases_client_id) {
3237 if (l->subnet_id_ == s->getID()) {
3238 lease = l;
3239 break;
3240 }
3241 }
3242
3243 if (lease) {
3244 break;
3245
3246 } else {
3247 s = s->getNextSubnet(original_subnet, classes);
3248 }
3249 }
3250 }
3251 }
3252
3253 // If we haven't found a lease yet, try again by hardware-address.
3254 // The logic is the same.
3255 if (original_subnet && !lease && hwaddr) {
3256
3257 // Get all leases for this particular hw-address.
3258 Lease4Collection leases_hwaddr = LeaseMgrFactory::instance().getLease4(*hwaddr);
3259 if (!leases_hwaddr.empty()) {
3260 ConstSubnet4Ptr s = original_subnet;
3261
3262 // Pick one that belongs to a subnet in this shared network.
3263 while (s) {
3264 for (auto const& l : leases_hwaddr) {
3265 if (l->subnet_id_ == s->getID()) {
3266 lease = l;
3267 break;
3268 }
3269 }
3270
3271 if (lease) {
3272 break;
3273
3274 } else {
3275 s = s->getNextSubnet(original_subnet, classes);
3276 }
3277 }
3278 }
3279 }
3280
3281 // Check the first error case: unknown client. We check this before
3282 // validating the address sent because we don't want to respond if
3283 // we don't know this client, except if we're authoritative.
3284 bool known_client = lease && lease->belongsToClient(hwaddr, client_id);
3285 if (!authoritative && !known_client) {
3288 .arg(query->getLabel())
3289 .arg(hint.toText());
3290
3291 ex.deleteResponse();
3292 return;
3293 }
3294
3295 // If we know this client, check if his notion of the IP address is
3296 // correct, if we don't know him, check if we are authoritative.
3297 if ((known_client && (lease->addr_ != hint)) ||
3298 (!known_client && authoritative) ||
3299 (!original_subnet)) {
3302 .arg(query->getLabel())
3303 .arg(hint.toText());
3304
3305 resp->setType(DHCPNAK);
3306 resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
3307 return;
3308 }
3309 }
3310
3311 CalloutHandlePtr callout_handle = getCalloutHandle(query);
3312
3313 // We need to set these values in the context as they haven't been set yet.
3314 ctx->requested_address_ = hint;
3315 ctx->fake_allocation_ = fake_allocation;
3316 ctx->callout_handle_ = callout_handle;
3317
3318 // If client query contains an FQDN or Hostname option, server
3319 // should respond to the client with the appropriate FQDN or Hostname
3320 // option to indicate if it takes responsibility for the DNS updates.
3321 // This is also the source for the hostname and dns flags that are
3322 // initially added to the lease. In most cases, this information is
3323 // good now. If we end up changing subnets in allocation we'll have to
3324 // do it again and then update the lease.
3326
3327 // Get a lease.
3328 Lease4Ptr lease = alloc_engine_->allocateLease4(*ctx);
3329
3330 bool reprocess_client_name = false;
3331 if (lease) {
3332 // Since we have a lease check for pool-level DDNS parameters.
3333 // If there are any we need to call processClientName() again.
3334 auto ddns_params = ex.getContext()->getDdnsParams();
3335 auto pool = ddns_params->setPoolFromAddress(lease->addr_);
3336 if (pool) {
3337 reprocess_client_name = pool->hasDdnsParameters();
3338 }
3339 }
3340
3341 // Subnet may be modified by the allocation engine, if the initial subnet
3342 // belongs to a shared network.
3343 if (subnet && ctx->subnet_ && subnet->getID() != ctx->subnet_->getID()) {
3344 // We changed subnets and that means DDNS parameters might be different
3345 // so we need to rerun client name processing logic. Arguably we could
3346 // compare DDNS parameters for both subnets and then decide if we need
3347 // to rerun the name logic, but that's not likely to be any faster than
3348 // just re-running the name logic. @todo When inherited parameter
3349 // performance is improved this argument could be revisited.
3350 // Another case is the new subnet has a reserved hostname.
3351 SharedNetwork4Ptr network;
3352 subnet->getSharedNetwork(network);
3354 .arg(query->getLabel())
3355 .arg(subnet->toText())
3356 .arg(ctx->subnet_->toText())
3357 .arg(network ? network->getName() : "<no network?>");
3358
3359 subnet = ctx->subnet_;
3360 if (lease) {
3361 reprocess_client_name = true;
3362 }
3363 }
3364
3365 // Tracks whether or not the client name (FQDN or host) has changed since
3366 // the lease was allocated.
3367 bool client_name_changed = false;
3368
3369 if (reprocess_client_name) {
3370 // First, we need to remove the prior values from the response and reset
3371 // those in context, to give processClientName a clean slate.
3372 resp->delOption(DHO_FQDN);
3373 resp->delOption(DHO_HOST_NAME);
3374 ctx->hostname_ = "";
3375 ctx->fwd_dns_update_ = false;
3376 ctx->rev_dns_update_ = false;
3377
3378 // Regenerate the name and dns flags.
3380
3381 // If the results are different from the values already on the
3382 // lease, flag it so the lease gets updated down below.
3383 if ((lease->hostname_ != ctx->hostname_) ||
3384 (lease->fqdn_fwd_ != ctx->fwd_dns_update_) ||
3385 (lease->fqdn_rev_ != ctx->rev_dns_update_)) {
3386 lease->hostname_ = ctx->hostname_;
3387 lease->fqdn_fwd_ = ctx->fwd_dns_update_;
3388 lease->fqdn_rev_ = ctx->rev_dns_update_;
3389 client_name_changed = true;
3390 }
3391 }
3392
3393 if (lease) {
3394 // We have a lease! Let's set it in the packet and send it back to
3395 // the client.
3396 if (fake_allocation) {
3398 .arg(query->getLabel())
3399 .arg(lease->addr_.toText());
3400 } else {
3402 .arg(query->getLabel())
3403 .arg(lease->addr_.toText())
3404 .arg(Lease::lifetimeToText(lease->valid_lft_));
3405 }
3406
3407 // We're logging this here, because this is the place where we know
3408 // which subnet has been actually used for allocation. If the
3409 // client identifier matching is disabled, we want to make sure that
3410 // the user is notified.
3411 if (!ctx->subnet_->getMatchClientId()) {
3413 .arg(ctx->query_->getLabel())
3414 .arg(ctx->subnet_->getID());
3415 }
3416
3417 resp->setYiaddr(lease->addr_);
3418
3423 if (!fake_allocation) {
3424 // If this is a renewing client it will set a ciaddr which the
3425 // server may include in the response. If this is a new allocation
3426 // the client will set ciaddr to 0 and this will also be propagated
3427 // to the server's resp.
3428 resp->setCiaddr(query->getCiaddr());
3429 }
3430
3431 // We may need to update FQDN or hostname if the server is to generate
3432 // a new name from the allocated IP address or if the allocation engine
3433 // switched to a different subnet within a shared network.
3434 postAllocateNameUpdate(ctx, lease, query, resp, client_name_changed);
3435
3436 // Reuse the lease if possible.
3437 if (lease->reuseable_valid_lft_ > 0) {
3438 lease->valid_lft_ = lease->reuseable_valid_lft_;
3440 .arg(query->getLabel())
3441 .arg(lease->addr_.toText())
3442 .arg(Lease::lifetimeToText(lease->valid_lft_));
3443
3444 // Increment the reuse statistics.
3445 StatsMgr::instance().addValue("v4-lease-reuses",
3446 static_cast<int64_t>(1));
3448 lease->subnet_id_,
3449 "v4-lease-reuses"),
3450 static_cast<int64_t>(1));
3451 }
3452
3453 // IP Address Lease time (type 51)
3454 // If we're not allocating on discover then we just sent the lifetime on the lease.
3455 // Otherwise (i.e. offer_lft > 0), the lease's lifetime has been set to offer_lft but
3456 // we want to send the client the proper valid lifetime so we have to fetch it.
3457 auto send_lft = (ctx->offer_lft_ ? AllocEngine::getValidLft(*ctx) : lease->valid_lft_);
3459
3460 resp->addOption(opt);
3461
3462 // Subnet mask (type 1)
3463 resp->addOption(getNetmaskOption(subnet));
3464
3465 // Set T1 and T2 per configuration.
3466 setTeeTimes(lease, subnet, resp);
3467
3468 // Create NameChangeRequests if this is a real allocation.
3469 if (!fake_allocation) {
3470 try {
3471 createNameChangeRequests(lease, ctx->old_lease_,
3472 *ex.getContext()->getDdnsParams());
3473 } catch (const Exception& e) {
3475 .arg(query->getLabel())
3476 .arg(e.what());
3477 }
3478 }
3479
3480 } else {
3481 // Allocation engine did not allocate a lease. The engine logged
3482 // cause of that failure.
3483 if (ctx->unknown_requested_addr_) {
3484 ConstSubnet4Ptr s = original_subnet;
3485 // Address might have been rejected via class guard (i.e. not
3486 // allowed for this client). We need to determine if we truly
3487 // do not know about the address or whether this client just
3488 // isn't allowed to have that address. We should only DHCPNAK
3489 // For the latter.
3490 while (s) {
3491 if (s->inPool(Lease::TYPE_V4, hint)) {
3492 break;
3493 }
3494
3495 s = s->getNextSubnet(original_subnet);
3496 }
3497
3498 // If we didn't find a subnet, it's not an address we know about
3499 // so we drop the DHCPNAK.
3500 if (!s) {
3503 .arg(query->getLabel())
3504 .arg(query->getCiaddr().toText())
3505 .arg(opt_requested_address ?
3506 opt_requested_address->readAddress().toText() : "(no address)");
3507 ex.deleteResponse();
3508 return;
3509 }
3510 }
3511
3514 .arg(query->getLabel())
3515 .arg(query->getCiaddr().toText())
3516 .arg(opt_requested_address ?
3517 opt_requested_address->readAddress().toText() : "(no address)");
3518
3519 resp->setType(DHCPNAK);
3520 resp->setYiaddr(IOAddress::IPV4_ZERO_ADDRESS());
3521
3522 resp->delOption(DHO_FQDN);
3523 resp->delOption(DHO_HOST_NAME);
3524 }
3525}
3526
3527void
3529 const Pkt4Ptr& query, const Pkt4Ptr& resp, bool client_name_changed) {
3530 // We may need to update FQDN or hostname if the server is to generate
3531 // new name from the allocated IP address or if the allocation engine
3532 // has switched to a different subnet within a shared network. Get
3533 // FQDN and hostname options from the response.
3534 OptionStringPtr opt_hostname;
3535 Option4ClientFqdnPtr fqdn = boost::dynamic_pointer_cast<
3536 Option4ClientFqdn>(resp->getOption(DHO_FQDN));
3537 if (!fqdn) {
3538 opt_hostname = boost::dynamic_pointer_cast<OptionString>(resp->getOption(DHO_HOST_NAME));
3539 if (!opt_hostname) {
3540 // We don't have either one, nothing to do.
3541 return;
3542 }
3543 }
3544
3545 // Empty hostname on the lease means we need to generate it.
3546 if (lease->hostname_.empty()) {
3547 // Note that if we have received the hostname option, rather than
3548 // Client FQDN the trailing dot is not appended to the generated
3549 // hostname because some clients don't handle the trailing dot in
3550 // the hostname. Whether the trailing dot is appended or not is
3551 // controlled by the second argument to the generateFqdn().
3552 lease->hostname_ = CfgMgr::instance().getD2ClientMgr()
3553 .generateFqdn(lease->addr_, *(ctx->getDdnsParams()), static_cast<bool>(fqdn));
3554
3556 .arg(query->getLabel())
3557 .arg(lease->hostname_);
3558
3559 client_name_changed = true;
3560 }
3561
3562 if (client_name_changed) {
3563 // The operations below are rather safe, but we want to catch
3564 // any potential exceptions (e.g. invalid lease database backend
3565 // implementation) and log an error.
3566 try {
3568 if (!ctx->fake_allocation_ || (ctx->offer_lft_ > 0)) {
3569 // The lease can't be reused.
3570 lease->reuseable_valid_lft_ = 0;
3571
3572 // The lease update should be safe, because the lease should
3573 // be already in the database. In most cases the exception
3574 // would be thrown if the lease was missing.
3576 }
3577
3578 // The name update in the outbound option should be also safe,
3579 // because the generated name is well formed.
3580 if (fqdn) {
3581 fqdn->setDomainName(lease->hostname_, Option4ClientFqdn::FULL);
3582 } else {
3583 opt_hostname->setValue(lease->hostname_);
3584 }
3585 } catch (const Exception& ex) {
3587 .arg(query->getLabel())
3588 .arg(lease->hostname_)
3589 .arg(ex.what());
3590 }
3591 }
3592}
3593
3595void
3596Dhcpv4Srv::setTeeTimes(const Lease4Ptr& lease, const ConstSubnet4Ptr& subnet, Pkt4Ptr resp) {
3597
3598 uint32_t t2_time = 0;
3599 // If T2 is explicitly configured we'll use try value.
3600 if (!subnet->getT2().unspecified()) {
3601 t2_time = subnet->getT2();
3602 } else if (subnet->getCalculateTeeTimes()) {
3603 // Calculating tee times is enabled, so calculated it.
3604 t2_time = static_cast<uint32_t>(round(subnet->getT2Percent() * (lease->valid_lft_)));
3605 }
3606
3607 // Send the T2 candidate value only if it's sane: to be sane it must be less than
3608 // the valid life time.
3609 uint32_t timer_ceiling = lease->valid_lft_;
3610 if (t2_time > 0 && t2_time < timer_ceiling) {
3612 resp->addOption(t2);
3613 // When we send T2, timer ceiling for T1 becomes T2.
3614 timer_ceiling = t2_time;
3615 }
3616
3617 uint32_t t1_time = 0;
3618 // If T1 is explicitly configured we'll use try value.
3619 if (!subnet->getT1().unspecified()) {
3620 t1_time = subnet->getT1();
3621 } else if (subnet->getCalculateTeeTimes()) {
3622 // Calculating tee times is enabled, so calculate it.
3623 t1_time = static_cast<uint32_t>(round(subnet->getT1Percent() * (lease->valid_lft_)));
3624 }
3625
3626 // Send T1 if it's sane: If we sent T2, T1 must be less than that. If not it must be
3627 // less than the valid life time.
3628 if (t1_time > 0 && t1_time < timer_ceiling) {
3630 resp->addOption(t1);
3631 }
3632}
3633
3634uint16_t
3636
3637 // Look for a relay-port RAI sub-option in the query.
3638 const Pkt4Ptr& query = ex.getQuery();
3639 const OptionPtr& rai = query->getOption(DHO_DHCP_AGENT_OPTIONS);
3640 if (rai && rai->getOption(RAI_OPTION_RELAY_PORT)) {
3641 // Got the sub-option so use the remote port set by the relay.
3642 return (query->getRemotePort());
3643 }
3644 return (0);
3645}
3646
3647void
3649 adjustRemoteAddr(ex);
3650
3651 // Initialize the pointers to the client's message and the server's
3652 // response.
3653 Pkt4Ptr query = ex.getQuery();
3654 Pkt4Ptr response = ex.getResponse();
3655
3656 // The DHCPINFORM is generally unicast to the client. The only situation
3657 // when the server is unable to unicast to the client is when the client
3658 // doesn't include ciaddr and the message is relayed. In this case the
3659 // server has to reply via relay agent. For other messages we send back
3660 // through relay if message is relayed, and unicast to the client if the
3661 // message is not relayed.
3662 // If client port was set from the command line enforce all responses
3663 // to it. Of course it is only for testing purposes.
3664 // Note that the call to this function may throw if invalid combination
3665 // of hops and giaddr is found (hops = 0 if giaddr = 0 and hops != 0 if
3666 // giaddr != 0). The exception will propagate down and eventually cause the
3667 // packet to be discarded.
3668 if (client_port_) {
3669 response->setRemotePort(client_port_);
3670 } else if (((query->getType() == DHCPINFORM) &&
3671 ((!query->getCiaddr().isV4Zero()) ||
3672 (!query->isRelayed() && !query->getRemoteAddr().isV4Zero()))) ||
3673 ((query->getType() != DHCPINFORM) && !query->isRelayed())) {
3674 response->setRemotePort(DHCP4_CLIENT_PORT);
3675
3676 } else {
3677 // RFC 8357 section 5.1
3678 uint16_t relay_port = checkRelayPort(ex);
3679 response->setRemotePort(relay_port ? relay_port : DHCP4_SERVER_PORT);
3680 }
3681
3682 CfgIfacePtr cfg_iface = CfgMgr::instance().getCurrentCfg()->getCfgIface();
3683 if (query->isRelayed() &&
3684 (cfg_iface->getSocketType() == CfgIface::SOCKET_UDP) &&
3685 (cfg_iface->getOutboundIface() == CfgIface::USE_ROUTING)) {
3686
3687 // Mark the response to follow routing
3688 response->setLocalAddr(IOAddress::IPV4_ZERO_ADDRESS());
3689 response->resetIndex();
3690 // But keep the interface name
3691 response->setIface(query->getIface());
3692
3693 } else {
3694
3695 IOAddress local_addr = query->getLocalAddr();
3696
3697 // In many cases the query is sent to a broadcast address. This address
3698 // appears as a local address in the query message. We can't simply copy
3699 // this address to a response message and use it as a source address.
3700 // Instead we will need to use the address assigned to the interface
3701 // on which the query has been received. In other cases, we will just
3702 // use this address as a source address for the response.
3703 // Do the same for DHCPv4-over-DHCPv6 exchanges.
3704 if (local_addr.isV4Bcast() || query->isDhcp4o6()) {
3705 local_addr = IfaceMgr::instance().getSocket(query).addr_;
3706 }
3707
3708 // We assume that there is an appropriate socket bound to this address
3709 // and that the address is correct. This is safe assumption because
3710 // the local address of the query is set when the query is received.
3711 // The query sent to an incorrect address wouldn't have been received.
3712 // However, if socket is closed for this address between the reception
3713 // of the query and sending a response, the IfaceMgr should detect it
3714 // and return an error.
3715 response->setLocalAddr(local_addr);
3716 // In many cases the query is sent to a broadcast address. This address
3717 // appears as a local address in the query message. Therefore we can't
3718 // simply copy local address from the query and use it as a source
3719 // address for the response. Instead, we have to check what address our
3720 // socket is bound to and use it as a source address. This operation
3721 // may throw if for some reason the socket is closed.
3724 response->setIndex(query->getIndex());
3725 response->setIface(query->getIface());
3726 }
3727
3728 if (server_port_) {
3729 response->setLocalPort(server_port_);
3730 } else {
3731 response->setLocalPort(DHCP4_SERVER_PORT);
3732 }
3733}
3734
3735void
3737 // Initialize the pointers to the client's message and the server's
3738 // response.
3739 Pkt4Ptr query = ex.getQuery();
3740 Pkt4Ptr response = ex.getResponse();
3741
3742 // DHCPv4-over-DHCPv6 is simple
3743 if (query->isDhcp4o6()) {
3744 response->setRemoteAddr(query->getRemoteAddr());
3745 return;
3746 }
3747
3748 // The DHCPINFORM is slightly different than other messages in a sense
3749 // that the server should always unicast the response to the ciaddr.
3750 // It appears however that some clients don't set the ciaddr. We still
3751 // want to provision these clients and we do what we can't to send the
3752 // packet to the address where client can receive it.
3753 if (query->getType() == DHCPINFORM) {
3754 // If client adheres to RFC2131 it will set the ciaddr and in this
3755 // case we always unicast our response to this address.
3756 if (!query->getCiaddr().isV4Zero()) {
3757 response->setRemoteAddr(query->getCiaddr());
3758
3759 // If we received DHCPINFORM via relay and the ciaddr is not set we
3760 // will try to send the response via relay. The caveat is that the
3761 // relay will not have any idea where to forward the packet because
3762 // the yiaddr is likely not set. So, the broadcast flag is set so
3763 // as the response may be broadcast.
3764 } else if (query->isRelayed()) {
3765 response->setRemoteAddr(query->getGiaddr());
3766 response->setFlags(response->getFlags() | BOOTP_BROADCAST);
3767
3768 // If there is no ciaddr and no giaddr the only thing we can do is
3769 // to use the source address of the packet.
3770 } else {
3771 response->setRemoteAddr(query->getRemoteAddr());
3772 }
3773 // Remote address is now set so return.
3774 return;
3775 }
3776
3777 // If received relayed message, server responds to the relay address.
3778 if (query->isRelayed()) {
3779 // The client should set the ciaddr when sending the DHCPINFORM
3780 // but in case he didn't, the relay may not be able to determine the
3781 // address of the client, because yiaddr is not set when responding
3782 // to Confirm and the only address available was the source address
3783 // of the client. The source address is however not used here because
3784 // the message is relayed. Therefore, we set the BROADCAST flag so
3785 // as the relay can broadcast the packet.
3786 if ((query->getType() == DHCPINFORM) &&
3787 query->getCiaddr().isV4Zero()) {
3788 response->setFlags(BOOTP_BROADCAST);
3789 }
3790 response->setRemoteAddr(query->getGiaddr());
3791
3792 // If giaddr is 0 but client set ciaddr, server should unicast the
3793 // response to ciaddr.
3794 } else if (!query->getCiaddr().isV4Zero()) {
3795 response->setRemoteAddr(query->getCiaddr());
3796
3797 // We can't unicast the response to the client when sending DHCPNAK,
3798 // because we haven't allocated address for him. Therefore,
3799 // DHCPNAK is broadcast.
3800 } else if (response->getType() == DHCPNAK) {
3801 response->setRemoteAddr(IOAddress::IPV4_BCAST_ADDRESS());
3802
3803 // If yiaddr is set it means that we have created a lease for a client.
3804 } else if (!response->getYiaddr().isV4Zero()) {
3805 // If the broadcast bit is set in the flags field, we have to
3806 // send the response to broadcast address. Client may have requested it
3807 // because it doesn't support reception of messages on the interface
3808 // which doesn't have an address assigned. The other case when response
3809 // must be broadcasted is when our server does not support responding
3810 // directly to a client without address assigned.
3811 const bool bcast_flag = ((query->getFlags() & Pkt4::FLAG_BROADCAST_MASK) != 0);
3812 if (!IfaceMgr::instance().isDirectResponseSupported() || bcast_flag) {
3813 response->setRemoteAddr(IOAddress::IPV4_BCAST_ADDRESS());
3814
3815 // Client cleared the broadcast bit and we support direct responses
3816 // so we should unicast the response to a newly allocated address -
3817 // yiaddr.
3818 } else {
3819 response->setRemoteAddr(response ->getYiaddr());
3820
3821 }
3822
3823 // In most cases, we should have the remote address found already. If we
3824 // found ourselves at this point, the rational thing to do is to respond
3825 // to the address we got the query from.
3826 } else {
3827 response->setRemoteAddr(query->getRemoteAddr());
3828 }
3829
3830 // For testing *only*.
3832 response->setRemoteAddr(query->getRemoteAddr());
3833 }
3834}
3835
3836void
3838 Pkt4Ptr query = ex.getQuery();
3839 Pkt4Ptr response = ex.getResponse();
3840
3841 // Step 1: Start with fixed fields defined on subnet level.
3842 ConstSubnet4Ptr subnet = ex.getContext()->subnet_;
3843 if (subnet) {
3844 IOAddress subnet_next_server = subnet->getSiaddr();
3845 if (!subnet_next_server.isV4Zero()) {
3846 response->setSiaddr(subnet_next_server);
3847 }
3848
3849 const string& sname = subnet->getSname();
3850 if (!sname.empty()) {
3851 // Converting string to (const uint8_t*, size_t len) format is
3852 // tricky. reinterpret_cast is not the most elegant solution,
3853 // but it does avoid us making unnecessary copy. We will convert
3854 // sname and file fields in Pkt4 to string one day and life
3855 // will be easier.
3856 response->setSname(reinterpret_cast<const uint8_t*>(sname.c_str()),
3857 sname.size());
3858 }
3859
3860 const string& filename = subnet->getFilename();
3861 if (!filename.empty()) {
3862 // Converting string to (const uint8_t*, size_t len) format is
3863 // tricky. reinterpret_cast is not the most elegant solution,
3864 // but it does avoid us making unnecessary copy. We will convert
3865 // sname and file fields in Pkt4 to string one day and life
3866 // will be easier.
3867 response->setFile(reinterpret_cast<const uint8_t*>(filename.c_str()),
3868 filename.size());
3869 }
3870 }
3871
3872 // Step 2: Try to set the values based on classes.
3873 // Any values defined in classes will override those from subnet level.
3874 const ClientClasses& classes = query->getClasses();
3875 if (!classes.empty()) {
3876
3877 // Let's get class definitions
3878 const ClientClassDictionaryPtr& dict =
3879 CfgMgr::instance().getCurrentCfg()->getClientClassDictionary();
3880
3881 // Now we need to iterate over the classes assigned to the
3882 // query packet and find corresponding class definitions for it.
3883 // We want the first value found for each field. We track how
3884 // many we've found so we can stop if we have all three.
3886 string sname;
3887 string filename;
3888 size_t found_cnt = 0; // How many fields we have found.
3889 for (auto const& name : classes) {
3890
3891 if (found_cnt >= 3) {
3892 break;
3893 }
3894
3895 ClientClassDefPtr cl = dict->findClass(name);
3896 if (!cl) {
3897 // Let's skip classes that don't have definitions. Currently
3898 // these are automatic classes VENDOR_CLASS_something, but there
3899 // may be other classes assigned under other circumstances, e.g.
3900 // by hooks.
3901 continue;
3902 }
3903
3904 if (next_server == IOAddress::IPV4_ZERO_ADDRESS()) {
3905 next_server = cl->getNextServer();
3906 if (!next_server.isV4Zero()) {
3907 response->setSiaddr(next_server);
3908 found_cnt++;
3909 }
3910 }
3911
3912 if (sname.empty()) {
3913 sname = cl->getSname();
3914 if (!sname.empty()) {
3915 // Converting string to (const uint8_t*, size_t len) format is
3916 // tricky. reinterpret_cast is not the most elegant solution,
3917 // but it does avoid us making unnecessary copy. We will convert
3918 // sname and file fields in Pkt4 to string one day and life
3919 // will be easier.
3920 response->setSname(reinterpret_cast<const uint8_t*>(sname.c_str()),
3921 sname.size());
3922 found_cnt++;
3923 }
3924 }
3925
3926 if (filename.empty()) {
3927 filename = cl->getFilename();
3928 if (!filename.empty()) {
3929 // Converting string to (const uint8_t*, size_t len) format is
3930 // tricky. reinterpret_cast is not the most elegant solution,
3931 // but it does avoid us making unnecessary copy. We will convert
3932 // sname and file fields in Pkt4 to string one day and life
3933 // will be easier.
3934 response->setFile(reinterpret_cast<const uint8_t*>(filename.c_str()),
3935 filename.size());
3936 found_cnt++;
3937 }
3938 }
3939 }
3940 }
3941
3942 // Step 3: try to set values using HR. Any values coming from there will override
3943 // the subnet or class values.
3945}
3946
3948Dhcpv4Srv::getNetmaskOption(const ConstSubnet4Ptr& subnet) {
3949 uint32_t netmask = getNetmask4(subnet->get().second).toUint32();
3950
3952 DHO_SUBNET_MASK, netmask));
3953
3954 return (opt);
3955}
3956
3957tuple<bool, uint32_t>
3958Dhcpv4Srv::parkingLimitExceeded(string const& hook_label) {
3959 // Get the parking limit. Parsing should ensure the value is present.
3960 uint32_t parked_packet_limit(0);
3961 ConstElementPtr const& ppl(
3962 CfgMgr::instance().getCurrentCfg()->getConfiguredGlobal(CfgGlobals::PARKED_PACKET_LIMIT));
3963 if (ppl) {
3964 parked_packet_limit = ppl->intValue();
3965 }
3966
3967 if (parked_packet_limit) {
3968 ParkingLotPtr const& parking_lot(
3969 ServerHooks::getServerHooks().getParkingLotPtr(hook_label));
3970
3971 if (parking_lot && parked_packet_limit <= parking_lot->size()) {
3972 return make_tuple(true, parked_packet_limit);
3973 }
3974 }
3975 return make_tuple(false, parked_packet_limit);
3976}
3977
3978Pkt4Ptr
3980 bool drop = false;
3981 Dhcpv4Exchange ex(alloc_engine_, discover, context, context->subnet_, drop);
3982
3983 // Stop here if Dhcpv4Exchange constructor decided to drop the packet
3984 if (drop) {
3985 return (Pkt4Ptr());
3986 }
3987
3988 if (discover->inClass("REJECT")) {
3989 reject(ex);
3990 } else if (MultiThreadingMgr::instance().getMode()) {
3991 // The lease reclamation cannot run at the same time.
3992 ReadLockGuard share(alloc_engine_->getReadWriteMutex());
3993 assignLease(ex);
3994 } else {
3995 assignLease(ex);
3996 }
3997
3998 if (!ex.getResponse()) {
3999 // The offer is empty so return it *now*!
4000 return (Pkt4Ptr());
4001 }
4002
4003 // Adding any other options makes sense only when we got the lease
4004 // or it is for an IPv6-Only client.
4005 if (!ex.getResponse()->getYiaddr().isV4Zero() || ex.getIPv6OnlyPreferred()) {
4006 // If this is global reservation or the subnet doesn't belong to a shared
4007 // network we have already fetched it and evaluated the classes.
4009
4010 // Evaluate additional classes.
4012
4014 .arg(discover->getLabel())
4015 .arg(discover->getName())
4016 .arg(discover->getClasses().toText());
4017
4020 // Sanity check for IPv6-Only clients.
4021 if (ex.getIPv6OnlyPreferred()) {
4022 if (!ex.getResponse()->getOption(DHO_V6_ONLY_PREFERRED)) {
4023 // Better to drop the packet than to send an insane response.
4025 .arg(discover->getLabel());
4026 return (Pkt4Ptr());
4027 }
4028 }
4030 // There are a few basic options that we always want to
4031 // include in the response. If client did not request
4032 // them we append them for him.
4034
4035 // Set fixed fields (siaddr, sname, filename) if defined in
4036 // the reservation, class or subnet specific configuration.
4037 setFixedFields(ex);
4038
4039 } else {
4040 // If the server can't offer an address, it drops the packet.
4041 return (Pkt4Ptr());
4042
4043 }
4044
4045 // Set the src/dest IP address, port and interface for the outgoing
4046 // packet.
4047 adjustIfaceData(ex);
4048
4049 appendServerID(ex);
4050
4051 // Return the pointer to the context, which will be required by the
4052 // lease4_offer callouts.
4053 context = ex.getContext();
4054
4055 return (ex.getResponse());
4056}
4057
4058Pkt4Ptr
4060 bool drop = false;
4061 Dhcpv4Exchange ex(alloc_engine_, request, context, context->subnet_, drop);
4062
4063 // Stop here if Dhcpv4Exchange constructor decided to drop the packet
4064 if (drop) {
4065 return (Pkt4Ptr());
4066 }
4067
4068 // Note that we treat REQUEST message uniformly, regardless if this is a
4069 // first request (requesting for new address), renewing existing address
4070 // or even rebinding.
4071 if (request->inClass("REJECT")) {
4072 reject(ex);
4073 } else if (MultiThreadingMgr::instance().getMode()) {
4074 // The lease reclamation cannot run at the same time.
4075 ReadLockGuard share(alloc_engine_->getReadWriteMutex());
4076 assignLease(ex);
4077 } else {
4078 assignLease(ex);
4079 }
4080
4081 Pkt4Ptr response = ex.getResponse();
4082 if (!response) {
4083 // The ack is empty so return it *now*!
4084 return (Pkt4Ptr());
4085 } else if (request->inClass("BOOTP")) {
4086 // Put BOOTP responses in the BOOTP class.
4087 response->addClass("BOOTP");
4088 }
4089
4090 // Adding any other options makes sense only when we got the lease
4091 // or it is for an IPv6-Only client.
4092 if (!response->getYiaddr().isV4Zero() || ex.getIPv6OnlyPreferred()) {
4093 // If this is global reservation or the subnet doesn't belong to a shared
4094 // network we have already fetched it and evaluated the classes.
4096
4097 // Evaluate additional classes.
4099
4101 .arg(request->getLabel())
4102 .arg(request->getName())
4103 .arg(request->getClasses().toText());
4104
4107 // Sanity check for IPv6-Only clients.
4108 if (ex.getIPv6OnlyPreferred()) {
4109 if (!response->getOption(DHO_V6_ONLY_PREFERRED)) {
4110 // Better to drop the packet than to send an insane response.
4112 .arg(request->getLabel());
4113 return (Pkt4Ptr());
4114 }
4115 }
4117 // There are a few basic options that we always want to
4118 // include in the response. If client did not request
4119 // them we append them for him.
4121
4122 // Set fixed fields (siaddr, sname, filename) if defined in
4123 // the reservation, class or subnet specific configuration.
4124 setFixedFields(ex);
4125 }
4126
4127 // Set the src/dest IP address, port and interface for the outgoing
4128 // packet.
4129 adjustIfaceData(ex);
4130
4131 appendServerID(ex);
4132
4133 // Return the pointer to the context, which will be required by the
4134 // leases4_committed callouts.
4135 context = ex.getContext();
4136
4137 return (ex.getResponse());
4138}
4139
4140void
4142 // Try to find client-id. Note that for the DHCPRELEASE we don't check if the
4143 // match-client-id configuration parameter is disabled because this parameter
4144 // is configured for subnets and we don't select subnet for the DHCPRELEASE.
4145 // Bogus clients usually generate new client identifiers when they first
4146 // connect to the network, so whatever client identifier has been used to
4147 // acquire the lease, the client identifier carried in the DHCPRELEASE is
4148 // likely to be the same and the lease will be correctly identified in the
4149 // lease database. If supplied client identifier differs from the one used
4150 // to acquire the lease then the lease will remain in the database and
4151 // simply expire.
4152 ClientIdPtr client_id;
4153 OptionPtr opt = release->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
4154 if (opt) {
4155 client_id = ClientIdPtr(new ClientId(opt->getData()));
4156 }
4157
4158 try {
4159 // Do we have a lease for that particular address?
4160 Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(release->getCiaddr());
4161
4162 if (!lease) {
4163 // No such lease - bogus release
4165 .arg(release->getLabel())
4166 .arg(release->getCiaddr().toText());
4167 return;
4168 }
4169
4170 if (!lease->belongsToClient(release->getHWAddr(), client_id)) {
4172 .arg(release->getLabel())
4173 .arg(release->getCiaddr().toText());
4174 return;
4175 }
4176
4177 if (lease->state_ != Lease4::STATE_DEFAULT) {
4179 .arg(release->getLabel())
4180 .arg(release->getCiaddr().toText())
4181 .arg(Lease::basicStatesToText(lease->state_));
4182 return;
4183 }
4184
4185 bool skip = false;
4186
4187 // Execute all callouts registered for lease4_release
4188 if (HooksManager::calloutsPresent(Hooks.hook_index_lease4_release_)) {
4189 CalloutHandlePtr callout_handle = getCalloutHandle(release);
4190
4191 // Use the RAII wrapper to make sure that the callout handle state is
4192 // reset when this object goes out of scope. All hook points must do
4193 // it to prevent possible circular dependency between the callout
4194 // handle and its arguments.
4195 ScopedCalloutHandleState callout_handle_state(callout_handle);
4196
4197 // Enable copying options from the packet within hook library.
4198 ScopedEnableOptionsCopy<Pkt4> query4_options_copy(release);
4199
4200 // Pass the original packet
4201 callout_handle->setArgument("query4", release);
4202
4203 // Pass the lease to be updated
4204 callout_handle->setArgument("lease4", lease);
4205
4206 // Call all installed callouts
4207 HooksManager::callCallouts(Hooks.hook_index_lease4_release_,
4208 *callout_handle);
4209
4210 // Callouts decided to skip the next processing step. The next
4211 // processing step would be to send the packet, so skip at this
4212 // stage means "drop response".
4213 if ((callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) ||
4214 (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP)) {
4215 skip = true;
4218 .arg(release->getLabel());
4219 }
4220 }
4221
4222 // Callout didn't indicate to skip the release process. Let's release
4223 // the lease.
4224 if (!skip) {
4225 // Ok, we've passed all checks. Let's release this address.
4226 bool success = false; // was the removal operation successful?
4227 bool expired = false; // explicitly expired instead of removed?
4228 auto expiration_cfg = CfgMgr::instance().getCurrentCfg()->getCfgExpiration();
4229
4230 // Delete lease only if affinity is disabled.
4231 if (expiration_cfg->getFlushReclaimedTimerWaitTime() &&
4232 expiration_cfg->getHoldReclaimedTime() &&
4233 lease->valid_lft_ != Lease::INFINITY_LFT) {
4234 // Expire the lease.
4235 lease->valid_lft_ = 0;
4236 // Set the lease state to released to indicate that this lease
4237 // must be preserved in the database. It is particularly useful
4238 // in HA to differentiate between the leases that should be
4239 // updated in the partner's database and deleted from the partner's
4240 // database.
4241 lease->state_ = Lease4::STATE_RELEASED;
4243 expired = true;
4244 success = true;
4245 } else {
4246 success = LeaseMgrFactory::instance().deleteLease(lease);
4247 }
4248
4249 if (success) {
4250 context.reset(new AllocEngine::ClientContext4());
4251 context->old_lease_ = lease;
4252
4253 // Release successful
4255 .arg(release->getLabel())
4256 .arg(lease->addr_.toText());
4257
4258 if (expired) {
4260 .arg(release->getLabel())
4261 .arg(lease->addr_.toText());
4262 } else {
4264 .arg(release->getLabel())
4265 .arg(lease->addr_.toText());
4266
4267 // Remove existing DNS entries for the lease, if any.
4268 queueNCR(CHG_REMOVE, lease);
4269 }
4270
4271 // Need to decrease statistic for assigned addresses.
4272 StatsMgr::instance().addValue("assigned-addresses", static_cast<int64_t>(-1));
4273
4275 StatsMgr::generateName("subnet", lease->subnet_id_, "assigned-addresses"),
4276 static_cast<int64_t>(-1));
4277
4278 auto const& subnet = CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getBySubnetId(lease->subnet_id_);
4279 if (subnet) {
4280 auto const& pool = subnet->getPool(Lease::TYPE_V4, lease->addr_, false);
4281 if (pool) {
4283 StatsMgr::generateName("subnet", subnet->getID(),
4284 StatsMgr::generateName("pool", pool->getID(), "assigned-addresses")),
4285 static_cast<int64_t>(-1));
4286 }
4287 }
4288
4289 } else {
4290 // Release failed
4292 .arg(release->getLabel())
4293 .arg(lease->addr_.toText());
4294 }
4295 }
4296 } catch (const isc::Exception& ex) {
4298 .arg(release->getLabel())
4299 .arg(release->getCiaddr())
4300 .arg(ex.what());
4301 }
4302}
4303
4304void
4306 // Client is supposed to specify the address being declined in
4307 // Requested IP address option, but must not set its ciaddr.
4308 // (again, see table 5 in RFC2131).
4309
4310 OptionCustomPtr opt_requested_address = boost::dynamic_pointer_cast<
4311 OptionCustom>(decline->getOption(DHO_DHCP_REQUESTED_ADDRESS));
4312 if (!opt_requested_address) {
4313
4314 StatsMgr::instance().addValue("pkt4-rfc-violation",
4315 static_cast<int64_t>(1));
4316 isc_throw(RFCViolation, "Mandatory 'Requested IP address' option missing"
4317 " in DHCPDECLINE sent from " << decline->getLabel());
4318 }
4319 IOAddress addr(opt_requested_address->readAddress());
4320
4321 // We could also extract client's address from ciaddr, but that's clearly
4322 // against RFC2131.
4323
4324 // Now we need to check whether this address really belongs to the client
4325 // that attempts to decline it.
4326 const Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(addr);
4327
4328 if (!lease) {
4329 // Client tried to decline an address, but we don't have a lease for
4330 // that address. Let's ignore it.
4331 //
4332 // We could assume that we're recovering from a mishandled migration
4333 // to a new server and mark the address as declined, but the window of
4334 // opportunity for that to be useful is small and the attack vector
4335 // would be pretty severe.
4337 .arg(addr.toText()).arg(decline->getLabel());
4338 return;
4339 }
4340
4341 // Get client-id, if available.
4342 OptionPtr opt_clientid = decline->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
4343 ClientIdPtr client_id;
4344 if (opt_clientid) {
4345 client_id.reset(new ClientId(opt_clientid->getData()));
4346 }
4347
4348 // Check if the client attempted to decline an expired lease or a lease
4349 // it doesn't own. Declining expired leases is typically a client
4350 // misbehavior and may lead to pool exhaustion in case of a storm of
4351 // such declines. Only decline the lease if the lease has been recently
4352 // allocated to the client.
4353 if (lease->expired() || lease->state_ != Lease::STATE_DEFAULT ||
4354 !lease->belongsToClient(decline->getHWAddr(), client_id)) {
4355
4356 // Get printable hardware addresses
4357 string client_hw = decline->getHWAddr() ?
4358 decline->getHWAddr()->toText(false) : "(none)";
4359 string lease_hw = lease->hwaddr_ ?
4360 lease->hwaddr_->toText(false) : "(none)";
4361
4362 // Get printable client-ids
4363 string client_id_txt = client_id ? client_id->toText() : "(none)";
4364 string lease_id_txt = lease->client_id_ ?
4365 lease->client_id_->toText() : "(none)";
4366
4367 // Print the warning and we're done here.
4369 .arg(addr.toText()).arg(decline->getLabel())
4370 .arg(client_hw).arg(lease_hw).arg(client_id_txt).arg(lease_id_txt);
4371
4372 return;
4373 }
4374
4375 // Ok, all is good. The client is reporting its own address. Let's
4376 // process it.
4377 declineLease(lease, decline, context);
4378}
4379
4380void
4381Dhcpv4Srv::declineLease(const Lease4Ptr& lease, const Pkt4Ptr& decline,
4383
4384 // Let's check if there are hooks installed for decline4 hook point.
4385 // If they are, let's pass the lease and client's packet. If the hook
4386 // sets status to drop, we reject this Decline.
4387 if (HooksManager::calloutsPresent(Hooks.hook_index_lease4_decline_)) {
4388 CalloutHandlePtr callout_handle = getCalloutHandle(decline);
4389
4390 // Use the RAII wrapper to make sure that the callout handle state is
4391 // reset when this object goes out of scope. All hook points must do
4392 // it to prevent possible circular dependency between the callout
4393 // handle and its arguments.
4394 ScopedCalloutHandleState callout_handle_state(callout_handle);
4395
4396 // Enable copying options from the packet within hook library.
4397 ScopedEnableOptionsCopy<Pkt4> query4_options_copy(decline);
4398
4399 // Pass the original packet
4400 callout_handle->setArgument("query4", decline);
4401
4402 // Pass the lease to be updated
4403 callout_handle->setArgument("lease4", lease);
4404
4405 // Call callouts
4406 HooksManager::callCallouts(Hooks.hook_index_lease4_decline_,
4407 *callout_handle);
4408
4409 // Check if callouts decided to skip the next processing step.
4410 // If any of them did, we will drop the packet.
4411 if ((callout_handle->getStatus() == CalloutHandle::NEXT_STEP_SKIP) ||
4412 (callout_handle->getStatus() == CalloutHandle::NEXT_STEP_DROP)) {
4414 .arg(decline->getLabel()).arg(lease->addr_.toText());
4415 return;
4416 }
4417 }
4418
4419 Lease4Ptr old_values = boost::make_shared<Lease4>(*lease);
4420
4421 // @todo: Call hooks.
4422
4423 // We need to disassociate the lease from the client. Once we move a lease
4424 // to declined state, it is no longer associated with the client in any
4425 // way.
4426 lease->decline(CfgMgr::instance().getCurrentCfg()->getDeclinePeriod());
4427
4428 try {
4430 } catch (const Exception& ex) {
4431 // Update failed.
4433 .arg(decline->getLabel())
4434 .arg(lease->addr_.toText())
4435 .arg(ex.what());
4436 return;
4437 }
4438
4439 // Remove existing DNS entries for the lease, if any.
4440 // queueNCR will do the necessary checks and will skip the update, if not needed.
4441 queueNCR(CHG_REMOVE, old_values);
4442
4443 // Bump up the statistics.
4444
4445 // Per subnet declined addresses counter.
4447 StatsMgr::generateName("subnet", lease->subnet_id_, "declined-addresses"),
4448 static_cast<int64_t>(1));
4449
4450 auto const& subnet = CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getBySubnetId(lease->subnet_id_);
4451 if (subnet) {
4452 auto const& pool = subnet->getPool(Lease::TYPE_V4, lease->addr_, false);
4453 if (pool) {
4455 StatsMgr::generateName("subnet", subnet->getID(),
4456 StatsMgr::generateName("pool", pool->getID(), "declined-addresses")),
4457 static_cast<int64_t>(1));
4458 }
4459 }
4460
4461 // Global declined addresses counter.
4462 StatsMgr::instance().addValue("declined-addresses", static_cast<int64_t>(1));
4463
4464 // We do not want to decrease the assigned-addresses at this time. While
4465 // technically a declined address is no longer allocated, the primary usage
4466 // of the assigned-addresses statistic is to monitor pool utilization. Most
4467 // people would forget to include declined-addresses in the calculation,
4468 // and simply do assigned-addresses/total-addresses. This would have a bias
4469 // towards under-representing pool utilization, if we decreased allocated
4470 // immediately after receiving DHCPDECLINE, rather than later when we recover
4471 // the address.
4472
4473 context.reset(new AllocEngine::ClientContext4());
4474 context->new_lease_ = lease;
4475
4476 LOG_INFO(lease4_logger, DHCP4_DECLINE_LEASE).arg(lease->addr_.toText())
4477 .arg(decline->getLabel()).arg(lease->valid_lft_);
4478}
4479
4480void
4482 Lease4Ptr lease, bool lease_exists) {
4484 .arg(query->getLabel())
4485 .arg(lease->addr_.toText())
4486 .arg(lease->valid_lft_);
4487
4488 {
4489 // Check if the resource is busy i.e. can be modified by another thread
4490 // for another client. Highly unlikely.
4491 ResourceHandler4 resource_handler;
4492 if (MultiThreadingMgr::instance().getMode() && !resource_handler.tryLock4(lease->addr_)) {
4494 .arg(query->getLabel())
4495 .arg(lease->addr_.toText());
4496 return;
4497 }
4498
4499 // We need to disassociate the lease from the client. Once we move a lease
4500 // to declined state, it is no longer associated with the client in any
4501 // way.
4502 lease->decline(CfgMgr::instance().getCurrentCfg()->getDeclinePeriod());
4503
4504 // If the lease already exists, update it in the database.
4505 if (lease_exists) {
4506 try {
4508 } catch (const NoSuchLease& ex) {
4509 // We expected the lease to exist but it doesn't so let's try
4510 // to add it.
4511 lease_exists = false;
4512 } catch (const Exception& ex) {
4513 // Update failed.
4515 .arg(query->getLabel())
4516 .arg(lease->addr_.toText());
4517 return;
4518 }
4519 }
4520
4521 if (!lease_exists) {
4522 try {
4524 } catch (const Exception& ex) {
4526 .arg(query->getLabel())
4527 .arg(lease->addr_.toText());
4528 return;
4529 }
4530 }
4531 }
4532
4533 // Bump up the statistics. If the lease does not exist (i.e. offer-lifetime == 0) we
4534 // need to increment assigned address stats, otherwise the accounting will be off.
4535 // This saves us from having to determine later, when declined leases are reclaimed,
4536 // whether or not we need to decrement assigned stats. In other words, this keeps
4537 // a declined lease always counted also as an assigned lease, regardless of how
4538 // it was declined, until it is reclaimed at which point both groups of stats
4539 // are decremented.
4540
4541 // Per subnet declined addresses counter.
4543 StatsMgr::generateName("subnet", lease->subnet_id_, "declined-addresses"),
4544 static_cast<int64_t>(1));
4545
4546 if (!lease_exists) {
4548 StatsMgr::generateName("subnet", lease->subnet_id_, "assigned-addresses"),
4549 static_cast<int64_t>(1));
4550 }
4551
4552 auto const& subnet = CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getBySubnetId(lease->subnet_id_);
4553 if (subnet) {
4554 auto const& pool = subnet->getPool(Lease::TYPE_V4, lease->addr_, false);
4555 if (pool) {
4557 StatsMgr::generateName("subnet", subnet->getID(),
4558 StatsMgr::generateName("pool", pool->getID(), "declined-addresses")),
4559 static_cast<int64_t>(1));
4560 if (!lease_exists) {
4562 StatsMgr::generateName("subnet", subnet->getID(),
4563 StatsMgr::generateName("pool", pool->getID(), "assigned-addresses")),
4564 static_cast<int64_t>(1));
4565 }
4566 }
4567 }
4568
4569 // Global declined addresses counter.
4570 StatsMgr::instance().addValue("declined-addresses", static_cast<int64_t>(1));
4571 if (!lease_exists) {
4572 StatsMgr::instance().addValue("assigned-addresses", static_cast<int64_t>(1));
4573 }
4574
4575 // Let's check if there are hooks installed for server decline hook point.
4576 // If there are, let's pass the DHCPDISCOVER and the declined lease .
4577 if (HooksManager::calloutsPresent(Hooks.hook_index_lease4_server_decline_)) {
4578 // Use the RAII wrapper to make sure that the callout handle state is
4579 // reset when this object goes out of scope. All hook points must do
4580 // it to prevent possible circular dependency between the callout
4581 // handle and its arguments.
4582 ScopedCalloutHandleState callout_handle_state(callout_handle);
4583
4584 // Pass in the original DHCPDISCOVER
4585 callout_handle->setArgument("query4", query);
4586
4587 // Pass in the declined lease.
4588 callout_handle->setArgument("lease4", lease);
4589
4590 // Call callouts
4591 HooksManager::callCallouts(Hooks.hook_index_lease4_server_decline_,
4592 *callout_handle);
4593 }
4594}
4595
4596void
4598 Lease4Ptr lease, bool lease_exists) {
4599 try {
4600 serverDecline(callout_handle, query, lease, lease_exists);
4601 } catch (...) {
4603 .arg(query->getLabel());
4604 }
4605}
4606
4607Pkt4Ptr
4609 bool drop = false;
4610 Dhcpv4Exchange ex(alloc_engine_, inform, context, context->subnet_, drop);
4611
4612 // Stop here if Dhcpv4Exchange constructor decided to drop the packet
4613 if (drop) {
4614 return (Pkt4Ptr());
4615 }
4616
4617 Pkt4Ptr ack = ex.getResponse();
4618
4619 // If this is global reservation or the subnet doesn't belong to a shared
4620 // network we have already fetched it and evaluated the classes.
4622
4623 // Evaluate additional classes.
4625
4627 .arg(inform->getLabel())
4628 .arg(inform->getName())
4629 .arg(inform->getClasses().toText());
4630
4635 adjustIfaceData(ex);
4636
4637 // Set fixed fields (siaddr, sname, filename) if defined in
4638 // the reservation, class or subnet specific configuration.
4639 setFixedFields(ex);
4640
4641 // There are cases for the DHCPINFORM that the server receives it via
4642 // relay but will send the response to the client's unicast address
4643 // carried in the ciaddr. In this case, the giaddr and hops field should
4644 // be cleared (these fields were copied by the copyDefaultFields function).
4645 // Also Relay Agent Options should be removed if present.
4646 if (ack->getRemoteAddr() != inform->getGiaddr()) {
4648 .arg(inform->getLabel())
4649 .arg(ack->getRemoteAddr())
4650 .arg(ack->getIface());
4651 ack->setHops(0);
4652 ack->setGiaddr(IOAddress::IPV4_ZERO_ADDRESS());
4653 ack->delOption(DHO_DHCP_AGENT_OPTIONS);
4654 }
4655
4656 // The DHCPACK must contain server id.
4657 appendServerID(ex);
4658
4659 return (ex.getResponse());
4660}
4661
4662void
4664 if (query->getCiaddr().isV4Zero() || !query->getGiaddr().isV4Zero()) {
4665 return;
4666 }
4668 getConfiguredGlobal(CfgGlobals::STASH_AGENT_OPTIONS);
4669 if (!sao || (sao->getType() != Element::boolean) || !sao->boolValue()) {
4670 return;
4671 }
4672 if (query->getType() != DHCPREQUEST) {
4673 return;
4674 }
4675 OptionPtr rai_opt = query->getOption(DHO_DHCP_AGENT_OPTIONS);
4676 if (rai_opt && (rai_opt->len() > Option::OPTION4_HDR_LEN)) {
4677 return;
4678 }
4679 // Should not happen but makes sense to check and gives a trivial way
4680 // to disable the feature from previous callout points.
4681 if (query->inClass("STASH_AGENT_OPTIONS")) {
4682 return;
4683 }
4684 Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(query->getCiaddr());
4685 if (!lease || lease->expired()) {
4686 return;
4687 }
4688 ConstElementPtr user_context = lease->getContext();
4689 if (!user_context || (user_context->getType() != Element::map)) {
4690 return;
4691 }
4692 ConstElementPtr isc = user_context->get("ISC");
4693 if (!isc || (isc->getType() != Element::map)) {
4694 return;
4695 }
4696 ConstElementPtr relay_agent_info = isc->get("relay-agent-info");
4697 if (!relay_agent_info) {
4698 return;
4699 }
4700 // Compatibility with the old layout.
4701 if (relay_agent_info->getType() == Element::map) {
4702 relay_agent_info = relay_agent_info->get("sub-options");
4703 if (!relay_agent_info) {
4704 return;
4705 }
4706 }
4707 if (relay_agent_info->getType() != Element::string) {
4708 return;
4709 }
4710 // Check ownership before going further.
4711 ClientIdPtr client_id;
4712 OptionPtr opt_clientid = query->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
4713 if (opt_clientid) {
4714 client_id.reset(new ClientId(opt_clientid->getData()));
4715 }
4716 if (!lease->belongsToClient(query->getHWAddr(), client_id)) {
4717 return;
4718 }
4719 // Extract the RAI.
4720 string rai_hex = relay_agent_info->stringValue();
4721 if (rai_hex.empty()) {
4722 return;
4723 }
4724 vector<uint8_t> rai_data;
4725 str::decodeFormattedHexString(rai_hex, rai_data);
4726 static const OptionDefinition& rai_def = LibDHCP::DHO_DHCP_AGENT_OPTIONS_DEF();
4727 OptionCustomPtr rai(new OptionCustom(rai_def, Option::V4, rai_data));
4728 // unpackOptions is a bit too flexible so check if it got something...
4729 if (!rai || rai->getOptions().empty()) {
4730 return;
4731 }
4732 // Remove an existing empty RAI.
4733 if (rai_opt) {
4734 query->delOption(DHO_DHCP_AGENT_OPTIONS);
4735 }
4736 query->addOption(rai);
4737 query->addClass("STASH_AGENT_OPTIONS");
4740 .arg(query->getLabel())
4741 .arg(query->getCiaddr())
4742 .arg(rai->toText());
4743}
4744
4745bool
4747 // Check that the message type is accepted by the server. We rely on the
4748 // function called to log a message if needed.
4749 if (!acceptMessageType(query)) {
4750 return (false);
4751 }
4752 // Check if the message from directly connected client (if directly
4753 // connected) should be dropped or processed.
4754 if (!acceptDirectRequest(query)) {
4756 .arg(query->getLabel())
4757 .arg(query->getIface());
4758 return (false);
4759 }
4760
4761 // Check if the DHCPv4 packet has been sent to us or to someone else.
4762 // If it hasn't been sent to us, drop it!
4763 if (!acceptServerId(query)) {
4765 .arg(query->getLabel())
4766 .arg(query->getIface());
4767 return (false);
4768 }
4769
4770 return (true);
4771}
4772
4773bool
4775 // Accept all relayed messages.
4776 if (pkt->isRelayed()) {
4777 return (true);
4778 }
4779
4780 // Accept all DHCPv4-over-DHCPv6 messages.
4781 if (pkt->isDhcp4o6()) {
4782 return (true);
4783 }
4784
4785 // The source address must not be zero for the DHCPINFORM message from
4786 // the directly connected client because the server will not know where
4787 // to respond if the ciaddr was not present.
4788 bool result = true;
4789 try {
4790 if (pkt->getType() == DHCPINFORM) {
4791 if (pkt->getRemoteAddr().isV4Zero() &&
4792 pkt->getCiaddr().isV4Zero()) {
4793 result = false;
4794 }
4795 }
4796 } catch (...) {
4797 // If we got here, it is probably because the message type hasn't
4798 // been set. But, this should not really happen assuming that
4799 // we validate the message type prior to calling this function.
4800 result = false;
4801 }
4802
4803 if (!result) {
4804 StatsMgr::instance().addValue("pkt4-rfc-violation",
4805 static_cast<int64_t>(1));
4806 }
4807 return (result);
4808}
4809
4810bool
4812 // When receiving a packet without message type option, getType() will
4813 // throw.
4814 int type;
4815 try {
4816 type = query->getType();
4817
4818 } catch (...) {
4820 .arg(query->getLabel())
4821 .arg(query->getIface());
4822 StatsMgr::instance().addValue("pkt4-rfc-violation",
4823 static_cast<int64_t>(1));
4824 return (false);
4825 }
4826
4827 // Once we know that the message type is within a range of defined DHCPv4
4828 // messages, we do a detailed check to make sure that the received message
4829 // is targeted at server. Note that we could have received some Offer
4830 // message broadcasted by the other server to a relay. Even though, the
4831 // server would rather unicast its response to a relay, let's be on the
4832 // safe side. Also, we want to drop other messages which we don't support.
4833 // All these valid messages that we are not going to process are dropped
4834 // silently.
4835
4836 switch(type) {
4837 case DHCPDISCOVER:
4838 case DHCPREQUEST:
4839 case DHCPRELEASE:
4840 case DHCPDECLINE:
4841 case DHCPINFORM:
4842 return (true);
4843 break;
4844
4845 case DHCP_NOTYPE:
4847 .arg(query->getLabel());
4848 break;
4849
4850 default:
4851 // If we receive a message with a non-existing type, we are logging it.
4852 if (type >= DHCP_TYPES_EOF) {
4854 .arg(query->getLabel())
4855 .arg(type);
4856 } else {
4857 // Exists but we don't support it.
4859 .arg(query->getLabel())
4860 .arg(type);
4861 }
4862 break;
4863 }
4864
4865 StatsMgr::instance().addValue("pkt4-rfc-violation",
4866 static_cast<int64_t>(1));
4867 return (false);
4868}
4869
4870bool
4872 // This function is meant to be called internally by the server class, so
4873 // we rely on the caller to sanity check the pointer and we don't check
4874 // it here.
4875
4876 // Check if server identifier option is present. If it is not present
4877 // we accept the message because it is targeted to all servers.
4878 // Note that we don't check cases that server identifier is mandatory
4879 // but not present. This is meant to be sanity checked in other
4880 // functions.
4881 OptionPtr option = query->getOption(DHO_DHCP_SERVER_IDENTIFIER);
4882 if (!option) {
4883 return (true);
4884 }
4885 // Server identifier is present. Let's convert it to 4-byte address
4886 // and try to match with server identifiers used by the server.
4887 OptionCustomPtr option_custom =
4888 boost::dynamic_pointer_cast<OptionCustom>(option);
4889 // Unable to convert the option to the option type which encapsulates it.
4890 // We treat this as non-matching server id.
4891 if (!option_custom) {
4892 StatsMgr::instance().addValue("pkt4-rfc-violation",
4893 static_cast<int64_t>(1));
4894 return (false);
4895 }
4896 // The server identifier option should carry exactly one IPv4 address.
4897 // If the option definition for the server identifier doesn't change,
4898 // the OptionCustom object should have exactly one IPv4 address and
4899 // this check is somewhat redundant. On the other hand, if someone
4900 // breaks option it may be better to check that here.
4901 if (option_custom->getDataFieldsNum() != 1) {
4902 StatsMgr::instance().addValue("pkt4-rfc-violation",
4903 static_cast<int64_t>(1));
4904 return (false);
4905 }
4906
4907 // The server identifier MUST be an IPv4 address. If given address is
4908 // v6, it is wrong.
4909 IOAddress server_id = option_custom->readAddress();
4910 if (!server_id.isV4()) {
4911 StatsMgr::instance().addValue("pkt4-rfc-violation",
4912 static_cast<int64_t>(1));
4913 return (false);
4914 }
4915
4916 // According to RFC5107, the RAI_OPTION_SERVER_ID_OVERRIDE option if
4917 // present, should match DHO_DHCP_SERVER_IDENTIFIER option.
4918 OptionPtr rai_option = query->getOption(DHO_DHCP_AGENT_OPTIONS);
4919 if (rai_option) {
4920 OptionPtr rai_suboption = rai_option->getOption(RAI_OPTION_SERVER_ID_OVERRIDE);
4921 if (rai_suboption && (server_id.toBytes() == rai_suboption->toBinary())) {
4922 return (true);
4923 }
4924 }
4925
4926 // Skip address check if configured to ignore the server id.
4928 if (cfg->getIgnoreServerIdentifier()) {
4929 return (true);
4930 }
4931
4932 // This function iterates over all interfaces on which the
4933 // server is listening to find the one which has a socket bound
4934 // to the address carried in the server identifier option.
4935 // This has some performance implications. However, given that
4936 // typically there will be just a few active interfaces the
4937 // performance hit should be acceptable. If it turns out to
4938 // be significant, we will have to cache server identifiers
4939 // when sockets are opened.
4940 if (IfaceMgr::instance().hasOpenSocket(server_id)) {
4941 return (true);
4942 }
4943
4944 // There are some cases when an administrator explicitly sets server
4945 // identifier (option 54) that should be used for a given, subnet,
4946 // network etc. It doesn't have to be an address assigned to any of
4947 // the server interfaces. Thus, we have to check if the server
4948 // identifier received is the one that we explicitly set in the
4949 // server configuration. At this point, we don't know which subnet
4950 // the client belongs to so we can't match the server id with any
4951 // subnet. We simply check if this server identifier is configured
4952 // anywhere. This should be good enough to eliminate exchanges
4953 // with other servers in the same network.
4954
4962
4963 // Check if there is at least one subnet configured with this server
4964 // identifier.
4965 ConstCfgSubnets4Ptr cfg_subnets = cfg->getCfgSubnets4();
4966 if (cfg_subnets->hasSubnetWithServerId(server_id)) {
4967 return (true);
4968 }
4969
4970 // This server identifier is not configured for any of the subnets, so
4971 // check on the shared network level.
4972 CfgSharedNetworks4Ptr cfg_networks = cfg->getCfgSharedNetworks4();
4973 if (cfg_networks->hasNetworkWithServerId(server_id)) {
4974 return (true);
4975 }
4976
4977 // Check if the server identifier is configured at client class level.
4978 const ClientClasses& classes = query->getClasses();
4979 for (auto const& cclass : classes) {
4980 // Find the client class definition for this class
4982 getClientClassDictionary()->findClass(cclass);
4983 if (!ccdef) {
4984 continue;
4985 }
4986
4987 if (ccdef->getCfgOption()->empty()) {
4988 // Skip classes which don't configure options
4989 continue;
4990 }
4991
4992 OptionCustomPtr context_opt_server_id = boost::dynamic_pointer_cast<OptionCustom>
4993 (ccdef->getCfgOption()->get(DHCP4_OPTION_SPACE, DHO_DHCP_SERVER_IDENTIFIER).option_);
4994 if (context_opt_server_id && (context_opt_server_id->readAddress() == server_id)) {
4995 return (true);
4996 }
4997 }
4998
4999 // Finally, it is possible that the server identifier is specified
5000 // on the global level.
5001 ConstCfgOptionPtr cfg_global_options = cfg->getCfgOption();
5002 OptionCustomPtr opt_server_id = boost::dynamic_pointer_cast<OptionCustom>
5003 (cfg_global_options->get(DHCP4_OPTION_SPACE, DHO_DHCP_SERVER_IDENTIFIER).option_);
5004
5005 if (opt_server_id && (opt_server_id->readAddress() == server_id)) {
5006 return (true);
5007 }
5008
5009 // No matching...
5010 StatsMgr::instance().addValue("pkt4-not-for-us", static_cast<int64_t>(1));
5011 return (false);
5012}
5013
5014void
5016 switch (query->getType()) {
5017 case DHCPDISCOVER:
5018 // server-id is forbidden.
5019 sanityCheck(query, FORBIDDEN);
5020 break;
5021 case DHCPREQUEST:
5022 // Since we cannot distinguish between client states
5023 // we'll make server-id is optional for REQUESTs.
5024 sanityCheck(query, OPTIONAL);
5025 break;
5026 case DHCPRELEASE:
5027 // Server-id is mandatory in DHCPRELEASE (see table 5, RFC2131)
5028 // but ISC DHCP does not enforce this, so we'll follow suit.
5029 sanityCheck(query, OPTIONAL);
5030 break;
5031 case DHCPDECLINE:
5032 // Server-id is mandatory in DHCPDECLINE (see table 5, RFC2131)
5033 // but ISC DHCP does not enforce this, so we'll follow suit.
5034 sanityCheck(query, OPTIONAL);
5035 break;
5036 case DHCPINFORM:
5037 // server-id is supposed to be forbidden (as is requested address)
5038 // but ISC DHCP does not enforce either. So neither will we.
5039 sanityCheck(query, OPTIONAL);
5040 break;
5041 }
5042}
5043
5044void
5046 OptionPtr server_id = query->getOption(DHO_DHCP_SERVER_IDENTIFIER);
5047 switch (serverid) {
5048 case FORBIDDEN:
5049 if (server_id) {
5050 StatsMgr::instance().addValue("pkt4-rfc-violation",
5051 static_cast<int64_t>(1));
5052 isc_throw(RFCViolation, "Server-id option was not expected, but"
5053 << " received in message "
5054 << query->getName());
5055 }
5056 break;
5057
5058 case MANDATORY:
5059 if (!server_id) {
5060 StatsMgr::instance().addValue("pkt4-rfc-violation",
5061 static_cast<int64_t>(1));
5062 isc_throw(RFCViolation, "Server-id option was expected, but not"
5063 " received in message "
5064 << query->getName());
5065 }
5066 break;
5067
5068 case OPTIONAL:
5069 // do nothing here
5070 ;
5071 }
5072
5073 // If there is HWAddress set and it is non-empty, then we're good
5074 if (query->getHWAddr() && !query->getHWAddr()->hwaddr_.empty()) {
5075 return;
5076 }
5077
5078 // There has to be something to uniquely identify the client:
5079 // either non-zero MAC address or client-id option present (or both)
5080 OptionPtr client_id = query->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
5081
5082 // If there's no client-id (or a useless one is provided, i.e. 0 length)
5083 if (!client_id || client_id->len() == client_id->getHeaderLen()) {
5084 StatsMgr::instance().addValue("pkt4-rfc-violation",
5085 static_cast<int64_t>(1));
5086 isc_throw(RFCViolation, "Missing or useless client-id and no HW address"
5087 " provided in message "
5088 << query->getName());
5089 }
5090}
5091
5095
5097 // First collect required classes
5098 Pkt4Ptr query = ex.getQuery();
5099 ClientClasses classes = query->getAdditionalClasses();
5100 ConstSubnet4Ptr subnet = ex.getContext()->subnet_;
5101
5102 if (subnet) {
5103 // host reservation???
5104
5105 // Begin by the pool
5106 Pkt4Ptr resp = ex.getResponse();
5108 if (resp) {
5109 addr = resp->getYiaddr();
5110 }
5111 if (!addr.isV4Zero()) {
5112 PoolPtr pool = subnet->getPool(Lease::TYPE_V4, addr, false);
5113 if (pool) {
5114 const ClientClasses& pool_to_add = pool->getAdditionalClasses();
5115 for (auto const& cclass : pool_to_add) {
5116 classes.insert(cclass);
5117 }
5118 }
5119 }
5120
5121 // Followed by the subnet
5122 const ClientClasses& to_add = subnet->getAdditionalClasses();
5123 for (auto const& cclass : to_add) {
5124 classes.insert(cclass);
5125 }
5126
5127 // And finish by the shared-network
5128 SharedNetwork4Ptr network;
5129 subnet->getSharedNetwork(network);
5130 if (network) {
5131 const ClientClasses& net_to_add = network->getAdditionalClasses();
5132 for (auto const& cclass : net_to_add) {
5133 classes.insert(cclass);
5134 }
5135 }
5136 }
5137
5138 // Run match expressions
5139 // Note getClientClassDictionary() cannot be null
5140 const ClientClassDictionaryPtr& dict =
5141 CfgMgr::instance().getCurrentCfg()->getClientClassDictionary();
5142 for (auto const& cclass : classes) {
5143 const ClientClassDefPtr class_def = dict->findClass(cclass);
5144 if (!class_def) {
5147 .arg(cclass);
5148 // Ignore it as it can't have an attached action
5149 continue;
5150 }
5151 const ExpressionPtr& expr_ptr = class_def->getMatchExpr();
5152 // Add a class without an expression to evaluate
5153 if (!expr_ptr) {
5156 .arg(cclass);
5157 query->addClass(cclass);
5158 continue;
5159 }
5160 // Evaluate the expression which can return false (no match),
5161 // true (match) or raise an exception (error)
5162 try {
5163 bool status = evaluateBool(*expr_ptr, *query);
5165 .arg(query->getLabel())
5166 .arg(cclass)
5167 .arg(status ? "true" : "false");
5168 if (status) {
5169 // Matching: add the class
5170 query->addClass(cclass);
5171 }
5172 } catch (const Exception& e) {
5174 .arg(query->getLabel())
5175 .arg(cclass)
5176 .arg(e.what());
5177 }
5178 }
5179}
5180
5181void
5183 // Iterate on the list of deferred option codes
5184 for (auto const& code : query->getDeferredOptions()) {
5186 // Iterate on client classes
5187 const ClientClasses& classes = query->getClasses();
5188 for (auto const& cclass : classes) {
5189 // Get the client class definition for this class
5190 const ClientClassDefPtr& ccdef =
5192 getClientClassDictionary()->findClass(cclass);
5193 // If not found skip it
5194 if (!ccdef) {
5195 continue;
5196 }
5197 // If there is no option definition skip it
5198 if (!ccdef->getCfgOptionDef()) {
5199 continue;
5200 }
5201 def = ccdef->getCfgOptionDef()->get(DHCP4_OPTION_SPACE, code);
5202 // Stop at the first client class with a definition
5203 if (def) {
5204 break;
5205 }
5206 }
5207 // If not found try the global definition
5208 if (!def) {
5210 }
5211 if (!def) {
5213 }
5214 // Finish by last resort definition
5215 if (!def) {
5217 }
5218 // If not defined go to the next option
5219 if (!def) {
5220 continue;
5221 }
5222 // Get the existing option for its content and remove all
5223 OptionPtr opt = query->getOption(code);
5224 if (!opt) {
5225 // should not happen but do not crash anyway
5228 .arg(query->getLabel())
5229 .arg(code);
5230 continue;
5231 }
5232 // Because options have already been fused, the buffer contains entire
5233 // data.
5234 const OptionBuffer buf = opt->getData();
5235 try {
5236 // Unpack the option
5237 LibDHCP::sanityCheckScalarLength(def, std::distance(buf.begin(), buf.end()));
5238 opt = def->optionFactory(Option::V4, code, buf);
5239 } catch (const std::exception& e) {
5240 // Failed to parse the option.
5243 .arg(query->getLabel())
5244 .arg(code)
5245 .arg(e.what());
5246 continue;
5247 }
5248
5249 // Remove the packed options.
5250 while (query->delOption(code)) {
5251 // continue;
5252 }
5253
5254 // Add the unpacked option.
5255 query->addOption(opt);
5256 }
5257}
5258
5259void
5262 if (d2_mgr.ddnsEnabled()) {
5263 // Updates are enabled, so lets start the sender, passing in
5264 // our error handler.
5265 // This may throw so wherever this is called needs to ready.
5267 this, ph::_1, ph::_2));
5268 }
5269}
5270
5271void
5274 if (d2_mgr.ddnsEnabled()) {
5275 // Updates are enabled, so lets stop the sender
5276 d2_mgr.stop();
5277 d2_mgr.stopSender();
5278 }
5279}
5280
5281void
5285 .arg(NameChangeSender::resultToText(result))
5286 .arg((ncr ? ncr->toText() : " NULL "));
5287 // We cannot communicate with kea-dhcp-ddns, suspend further updates.
5291}
5292
5293std::string
5295 std::stringstream tmp;
5296
5297 tmp << VERSION;
5298 if (extended) {
5299 tmp << " (" << SOURCE_OF_INSTALLATION << ")" << endl;
5300 tmp << "premium: " << PREMIUM_EXTENDED_VERSION << endl;
5301 tmp << "linked with:" << endl;
5302 tmp << "- " << Logger::getVersion() << endl;
5303 tmp << "- " << CryptoLink::getVersion();
5305 if (info.size()) {
5306 tmp << endl << "lease backends:";
5307 for (auto const& version : info) {
5308 tmp << endl << "- " << version;
5309 }
5310 }
5312 if (info.size()) {
5313 tmp << endl << "host backends:";
5314 for (auto const& version : info) {
5315 tmp << endl << "- " << version;
5316 }
5317 }
5319 if (info.size()) {
5320 tmp << endl << "forensic backends:";
5321 for (auto const& version : info) {
5322 tmp << endl << "- " << version;
5323 }
5324 }
5325 // @todo: more details about database runtime
5326 }
5327
5328 return (tmp.str());
5329}
5330
5332 // Note that we're not bumping pkt4-received statistic as it was
5333 // increased early in the packet reception code.
5334
5335 string stat_name = "pkt4-unknown-received";
5336 try {
5337 switch (query->getType()) {
5338 case DHCPDISCOVER:
5339 stat_name = "pkt4-discover-received";
5340 break;
5341 case DHCPOFFER:
5342 // Should not happen, but let's keep a counter for it
5343 stat_name = "pkt4-offer-received";
5344 break;
5345 case DHCPREQUEST:
5346 stat_name = "pkt4-request-received";
5347 break;
5348 case DHCPACK:
5349 // Should not happen, but let's keep a counter for it
5350 stat_name = "pkt4-ack-received";
5351 break;
5352 case DHCPNAK:
5353 // Should not happen, but let's keep a counter for it
5354 stat_name = "pkt4-nak-received";
5355 break;
5356 case DHCPRELEASE:
5357 stat_name = "pkt4-release-received";
5358 break;
5359 case DHCPDECLINE:
5360 stat_name = "pkt4-decline-received";
5361 break;
5362 case DHCPINFORM:
5363 stat_name = "pkt4-inform-received";
5364 break;
5365 default:
5366 ; // do nothing
5367 }
5368 }
5369 catch (...) {
5370 // If the incoming packet doesn't have option 53 (message type)
5371 // or a hook set pkt4_receive_skip, then Pkt4::getType() may
5372 // throw an exception. That's ok, we'll then use the default
5373 // name of pkt4-unknown-received.
5374 }
5375
5376 StatsMgr::instance().addValue(stat_name, static_cast<int64_t>(1));
5377}
5378
5380 // Increase generic counter for sent packets.
5381 StatsMgr::instance().addValue("pkt4-sent", static_cast<int64_t>(1));
5382
5383 // Increase packet type specific counter for packets sent.
5384 string stat_name;
5385 switch (response->getType()) {
5386 case DHCPOFFER:
5387 stat_name = "pkt4-offer-sent";
5388 break;
5389 case DHCPACK:
5390 stat_name = "pkt4-ack-sent";
5391 break;
5392 case DHCPNAK:
5393 stat_name = "pkt4-nak-sent";
5394 break;
5395 default:
5396 // That should never happen
5397 return;
5398 }
5399
5400 StatsMgr::instance().addValue(stat_name, static_cast<int64_t>(1));
5401}
5402
5404 return (Hooks.hook_index_buffer4_receive_);
5405}
5406
5408 return (Hooks.hook_index_pkt4_receive_);
5409}
5410
5412 return (Hooks.hook_index_subnet4_select_);
5413}
5414
5416 return (Hooks.hook_index_lease4_release_);
5417}
5418
5420 return (Hooks.hook_index_pkt4_send_);
5421}
5422
5424 return (Hooks.hook_index_buffer4_send_);
5425}
5426
5428 return (Hooks.hook_index_lease4_decline_);
5429}
5430
5432 // Dump all of our current packets, anything that is mid-stream
5434}
5435
5437#ifdef FUZZING
5438 char const* const rotate(getenv("KEA_DHCP4_FUZZING_ROTATE_PORT"));
5439 if (rotate) {
5440 InterprocessSyncFile file("kea-dhcp4-fuzzing-rotate-port");
5442 while (!locker.lock()) {
5443 this_thread::sleep_for(1s);
5444 }
5445 fstream port_file;
5446 port_file.open("/tmp/port4.txt", ios::in);
5447 string line;
5448 int port;
5449 getline(port_file, line);
5450 port_file.close();
5451 if (line.empty()) {
5452 port = 2000;
5453 } else {
5454 port = stoi(line);
5455 if (port < 3000) {
5456 ++port;
5457 } else {
5458 port = 2000;
5459 }
5460 }
5461 port_file.open("/tmp/port4.txt", ios::out | ios::trunc);
5462 port_file << to_string(port) << endl;
5463 port_file.close();
5464 locker.unlock();
5465 return port;
5466 }
5467#endif // FUZZING
5468 return server_port_;
5469}
5470
5471std::list<std::list<std::string>> Dhcpv4Srv::jsonPathsToRedact() const {
5472 static std::list<std::list<std::string>> const list({
5473 {"config-control", "config-databases", "[]"},
5474 {"hooks-libraries", "[]", "parameters", "*"},
5475 {"hosts-database"},
5476 {"hosts-databases", "[]"},
5477 {"lease-database"},
5478 });
5479 return list;
5480}
5481
5482} // namespace dhcp
5483} // namespace isc
Defines elements for storing the names of client classes.
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.
boost::shared_ptr< ClientContext4 > ClientContext4Ptr
Pointer to the ClientContext4.
static uint32_t getValidLft(const ClientContext4 &ctx)
Returns the valid lifetime based on the v4 context.
Implementation of the mechanisms to control the use of the Configuration Backends by the DHCPv4 serve...
@ USE_ROUTING
Server uses routing to determine the right interface to send response.
Definition cfg_iface.h:148
@ SOCKET_UDP
Datagram socket, i.e. IP/UDP socket.
Definition cfg_iface.h:139
Configuration Manager.
Definition cfgmgr.h:71
D2ClientMgr & getD2ClientMgr()
Fetches the DHCP-DDNS manager.
Definition cfgmgr.cc:69
static CfgMgr & instance()
returns a single instance of Configuration Manager
Definition cfgmgr.cc:29
SrvConfigPtr getCurrentCfg()
Returns a pointer to the current configuration.
Definition cfgmgr.cc:116
static SubnetSelector initSelector(const Pkt4Ptr &query)
Build selector from a client's message.
Container for storing client class names.
Definition classify.h:111
void insert(const ClientClass &class_name)
Insert an element.
Definition classify.h:161
static std::string escape(const std::string &name, bool escape_escape=true)
Escape a client class name.
Definition classify.cc:164
bool empty() const
Check if classes is empty.
Definition classify.h:171
std::string toText(const std::string &separator=", ") const
Returns all class names as text.
Definition classify.cc:77
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:222
ReplaceClientNameMode
Defines the client name replacement modes.
D2ClientMgr isolates Kea from the details of being a D2 client.
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 getUpdateDirections(const T &fqdn_resp, bool &forward, bool &reverse)
Get directional update flags based on server FQDN flags.
void stop()
Stop the sender.
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.
void startSender(D2ClientErrorHandler error_handler, const isc::asiolink::IOServicePtr &io_service)
Enables sending NameChangeRequests to kea-dhcp-ddns.
Convenience container for conveying DDNS behavioral parameters It is intended to be created per Packe...
Definition ddns_params.h:23
bool getUpdateOnRenew() const
Returns whether or not DNS should be updated when leases renew.
bool getEnableUpdates() const
Returns whether or not DHCP DDNS updating is enabled.
void close()
Close communication socket.
static Dhcp4to6Ipc & instance()
Returns pointer to the sole instance of Dhcp4to6Ipc.
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:113
void deleteResponse()
Removes the response message by resetting the pointer to null.
Definition dhcp4_srv.h:108
Pkt4Ptr getQuery() const
Returns the pointer to the query from the client.
Definition dhcp4_srv.h:96
static void setHostIdentifiers(AllocEngine::ClientContext4Ptr context)
Set host identifiers within a context.
Definition dhcp4_srv.cc:466
static void classifyByVendor(const Pkt4Ptr &pkt)
Assign class using vendor-class-identifier option.
Definition dhcp4_srv.cc:628
void initResponse()
Initializes the instance of the response message.
Definition dhcp4_srv.cc:338
void setReservedMessageFields()
Sets reserved values of siaddr, sname and file in the server's response.
Definition dhcp4_srv.cc:606
CfgOptionList & getCfgOptionList()
Returns the configured option list (non-const version).
Definition dhcp4_srv.h:118
Pkt4Ptr getResponse() const
Returns the pointer to the server's response.
Definition dhcp4_srv.h:103
static void setReservedClientClasses(AllocEngine::ClientContext4Ptr context)
Assigns classes retrieved from host reservation database.
Definition dhcp4_srv.cc:582
void initResponse4o6()
Initializes the DHCPv6 part of the response message.
Definition dhcp4_srv.cc:364
static void evaluateClasses(const Pkt4Ptr &pkt, bool depend_on_known)
Evaluate classes.
Definition dhcp4_srv.cc:652
void setIPv6OnlyPreferred(bool ipv6_only_preferred)
Set the IPv6-Only Preferred flag.
Definition dhcp4_srv.h:135
Dhcpv4Exchange(const AllocEnginePtr &alloc_engine, const Pkt4Ptr &query, AllocEngine::ClientContext4Ptr &context, const ConstSubnet4Ptr &subnet, bool &drop)
Constructor.
Definition dhcp4_srv.cc:218
static void classifyPacket(const Pkt4Ptr &pkt)
Assigns incoming packet to zero or more classes.
Definition dhcp4_srv.cc:641
static void removeDependentEvaluatedClasses(const Pkt4Ptr &query)
Removed evaluated client classes.
Definition dhcp4_srv.cc:567
bool getIPv6OnlyPreferred() const
Returns the IPv6-Only Preferred flag.
Definition dhcp4_srv.h:128
void conditionallySetReservedClientClasses()
Assigns classes retrieved from host reservation database if they haven't been yet set.
Definition dhcp4_srv.cc:592
void initContext0(const Pkt4Ptr &query, AllocEngine::ClientContext4Ptr ctx)
Initialize client context (first part).
int run()
Main server processing loop.
void declineLease(const Lease4Ptr &lease, const Pkt4Ptr &decline, AllocEngine::ClientContext4Ptr &context)
Marks lease as declined.
void processPacketAndSendResponse(Pkt4Ptr query)
Process a single incoming DHCPv4 packet and sends the response.
void classifyPacket(const Pkt4Ptr &pkt)
Assigns incoming packet to zero or more classes.
void appendRequestedVendorOptions(Dhcpv4Exchange &ex)
Appends requested vendor options as requested by client.
void adjustIfaceData(Dhcpv4Exchange &ex)
Set IP/UDP and interface parameters for the DHCPv4 response.
static uint16_t checkRelayPort(const Dhcpv4Exchange &ex)
Check if the relay port RAI sub-option was set in the query.
virtual ~Dhcpv4Srv()
Destructor. Used during DHCPv4 service shutdown.
Definition dhcp4_srv.cc:740
virtual Pkt4Ptr receivePacket(int timeout)
dummy wrapper around IfaceMgr::receive4
bool accept(const Pkt4Ptr &query)
Checks whether received message should be processed or discarded.
void setTeeTimes(const Lease4Ptr &lease, const ConstSubnet4Ptr &subnet, Pkt4Ptr resp)
Adds the T1 and T2 timers to the outbound response as appropriate.
static void appendServerID(Dhcpv4Exchange &ex)
Adds server identifier option to the server's response.
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.
bool use_bcast_
Should broadcast be enabled on sockets (if true).
Definition dhcp4_srv.h:1275
void runOne()
Main server processing step.
void startD2()
Starts DHCP_DDNS client IO if DDNS updates are enabled.
static int getHookIndexBuffer4Receive()
Returns the index for "buffer4_receive" hook point.
Pkt4Ptr processRequest(Pkt4Ptr &request, AllocEngine::ClientContext4Ptr &context)
Processes incoming REQUEST and returns REPLY response.
static void processStatsReceived(const Pkt4Ptr &query)
Class methods for DHCPv4-over-DHCPv6 handler.
static int getHookIndexPkt4Send()
Returns the index for "pkt4_send" hook point.
void processDecline(Pkt4Ptr &decline, AllocEngine::ClientContext4Ptr &context)
Process incoming DHCPDECLINE messages.
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:678
static int getHookIndexSubnet4Select()
Returns the index for "subnet4_select" hook point.
isc::dhcp::ConstSubnet4Ptr selectSubnet(const Pkt4Ptr &query, bool &drop, bool allow_answer_park=true)
Selects a subnet for a given client's packet.
Definition dhcp4_srv.cc:791
static void processStatsSent(const Pkt4Ptr &response)
Updates statistics for transmitted packets.
void shutdown() override
Instructs the server to shut down.
Definition dhcp4_srv.cc:785
static int getHookIndexLease4Release()
Returns the index for "lease4_release" hook point.
void adjustRemoteAddr(Dhcpv4Exchange &ex)
Sets remote addresses for outgoing packet.
static int getHookIndexPkt4Receive()
Returns the index for "pkt4_receive" hook point.
void assignLease(Dhcpv4Exchange &ex)
Assigns a lease and appends corresponding options.
void evaluateAdditionalClasses(Dhcpv4Exchange &ex)
Evaluates classes in the additional classes lists.
Pkt4Ptr processDhcp4Query(Pkt4Ptr query, bool allow_answer_park)
Process a single incoming DHCPv4 query.
asiolink::IOServicePtr & getIOService()
Returns pointer to the IO service used by the server.
Definition dhcp4_srv.h:318
void setFixedFields(Dhcpv4Exchange &ex)
Sets fixed fields of the outgoing packet.
void appendBasicOptions(Dhcpv4Exchange &ex)
Append basic options if they are not present.
void recoverStashedAgentOption(const Pkt4Ptr &query)
Recover stashed agent options from client address lease.
void processClientName(Dhcpv4Exchange &ex)
Processes Client FQDN and Hostname Options sent by a client.
boost::shared_ptr< AllocEngine > alloc_engine_
Allocation Engine.
Definition dhcp4_srv.h:1272
void serverDecline(hooks::CalloutHandlePtr &callout_handle, Pkt4Ptr &query, Lease4Ptr lease, bool lease_exists)
Renders a lease declined after the server has detected, via ping-check or other means,...
Pkt4Ptr processInform(Pkt4Ptr &inform, AllocEngine::ClientContext4Ptr &context)
Processes incoming DHCPINFORM messages.
uint16_t client_port_
UDP port number to which server sends all responses.
Definition dhcp4_srv.h:1262
void serverDeclineNoThrow(hooks::CalloutHandlePtr &callout_handle, Pkt4Ptr &query, Lease4Ptr lease, bool lease_exists)
Exception safe wrapper around serverDecline().
void processPacketPktSend(hooks::CalloutHandlePtr &callout_handle, Pkt4Ptr &query, Pkt4Ptr &rsp, ConstSubnet4Ptr &subnet)
Executes pkt4_send callout.
void processPacketAndSendResponseNoThrow(Pkt4Ptr query)
Process a single incoming DHCPv4 packet and sends the response.
std::list< std::list< std::string > > jsonPathsToRedact() const final override
Return a list of all paths that contain passwords or secrets for kea-dhcp4.
static std::string srvidToString(const OptionPtr &opt)
converts server-id to text Converts content of server-id option to a text representation,...
bool acceptServerId(const Pkt4Ptr &pkt) const
Verifies if the server id belongs to our server.
static const std::string VENDOR_CLASS_PREFIX
this is a prefix added to the content of vendor-class option
Definition dhcp4_srv.h:940
void createNameChangeRequests(const Lease4Ptr &lease, const Lease4Ptr &old_lease, const DdnsParams &ddns_params)
Creates NameChangeRequests which correspond to the lease which has been acquired.
void appendRequestedOptions(Dhcpv4Exchange &ex)
Appends options requested by client.
void setPacketStatisticsDefaults()
This function sets statistics related to DHCPv4 packets processing to their initial values.
Definition dhcp4_srv.cc:730
void processLocalizedQuery4AndSendResponse(Pkt4Ptr query, AllocEngine::ClientContext4Ptr &ctx, bool allow_answer_park)
Process a localized incoming DHCPv4 query.
static std::string getVersion(bool extended)
returns Kea version on stdout and exit.
void buildCfgOptionList(Dhcpv4Exchange &ex)
Build the configured option list.
volatile bool shutdown_
Indicates if shutdown is in progress.
Definition dhcp4_srv.h:1266
uint16_t server_port_
UDP port number on which server listens.
Definition dhcp4_srv.h:1259
void sendResponseNoThrow(hooks::CalloutHandlePtr &callout_handle, Pkt4Ptr &query, Pkt4Ptr &rsp, ConstSubnet4Ptr &subnet)
Process an unparked DHCPv4 packet and sends the response.
bool earlyGHRLookup(const Pkt4Ptr &query, AllocEngine::ClientContext4Ptr ctx)
Initialize client context and perform early global reservations lookup.
NetworkStatePtr network_state_
Holds information about disabled DHCP service and/or disabled subnet/network scopes.
Definition dhcp4_srv.h:1279
void processDhcp4QueryAndSendResponse(Pkt4Ptr query, bool allow_answer_park)
Process a single incoming DHCPv4 query.
bool getSendResponsesToSource() const
Returns value of the test_send_responses_to_source_ flag.
Definition dhcp4_srv.h:508
Pkt4Ptr processDiscover(Pkt4Ptr &discover, AllocEngine::ClientContext4Ptr &context)
Processes incoming DISCOVER and returns response.
virtual void d2ClientErrorHandler(const dhcp_ddns::NameChangeSender::Result result, dhcp_ddns::NameChangeRequestPtr &ncr)
Implements the error handler for DHCP_DDNS IO errors.
uint16_t getServerPort() const
Get UDP port on which server should listen.
virtual void sendPacket(const Pkt4Ptr &pkt)
dummy wrapper around IfaceMgr::send()
static int getHookIndexBuffer4Send()
Returns the index for "buffer4_send" hook point.
void stopD2()
Stops DHCP_DDNS client IO if DDNS updates are enabled.
static void sanityCheck(const Pkt4Ptr &query)
Verifies if specified packet meets RFC requirements.
bool acceptMessageType(const Pkt4Ptr &query) const
Check if received message type is valid for the server to process.
void discardPackets()
Discards parked packets Clears the packet parking lots of all packets.
isc::dhcp::ConstSubnet4Ptr selectSubnet4o6(const Pkt4Ptr &query, bool &drop, bool allow_answer_park=true)
Selects a subnet for a given client's DHCP4o6 packet.
Definition dhcp4_srv.cc:926
static int getHookIndexLease4Decline()
Returns the index for "lease4_decline" hook point.
void processRelease(Pkt4Ptr &release, AllocEngine::ClientContext4Ptr &context)
Processes incoming DHCPRELEASE messages.
bool acceptDirectRequest(const Pkt4Ptr &query)
Check if a message sent by directly connected client should be accepted or discarded.
CBControlDHCPv4Ptr cb_control_
Controls access to the configuration backends.
Definition dhcp4_srv.h:1282
RequirementLevel
defines if certain option may, must or must not appear
Definition dhcp4_srv.h:276
Pkt4Ptr processPacket(Pkt4Ptr query, bool allow_answer_park=true)
Process a single incoming DHCPv4 packet.
void processPacketBufferSend(hooks::CalloutHandlePtr &callout_handle, Pkt4Ptr &rsp)
Executes buffer4_send callout and sends the response.
bool assignZero(ConstSubnet4Ptr &subnet, const ClientClasses &client_classes)
Assign the 0.0.0.0 address to an IPv6-Only client.
void deferredUnpack(Pkt4Ptr &query)
Perform deferred option unpacking.
void reject(Dhcpv4Exchange &ex)
Return a NAK.
Pkt4Ptr processLocalizedQuery4(AllocEngine::ClientContext4Ptr &ctx, bool allow_answer_park)
Process a localized incoming DHCPv4 query.
Exception thrown when host name sanitizing reduces the domain name to an empty string.
static std::list< std::string > getDBVersions()
Return extended version info for registered backends.
static void create()
Creates new instance of the HostMgr.
Definition host_mgr.cc:52
std::string getIdentifierAsText() const
Returns host identifier in a textual form.
Definition host.cc:319
IdentifierType
Type of the host identifier.
Definition host.h:337
@ IDENT_FLEX
Flexible host identifier.
Definition host.h:342
@ IDENT_CLIENT_ID
Definition host.h:341
@ IDENT_CIRCUIT_ID
Definition host.h:340
static IfaceMgr & instance()
IfaceMgr is a singleton class.
Definition iface_mgr.cc:52
bool send(const Pkt6Ptr &pkt)
Sends an IPv6 packet.
void closeSockets()
Closes all open sockets.
Definition iface_mgr.cc:313
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.
static TrackingLeaseMgr & instance()
Return current lease manager.
static std::list< std::string > getDBVersions()
Return extended version info for registered backends.
static void destroy()
Destroy lease manager.
virtual Lease4Ptr getLease4(const isc::asiolink::IOAddress &addr) const =0
Returns an IPv4 lease for specified IPv4 address.
virtual bool addLease(const Lease4Ptr &lease)=0
Adds an IPv4 lease.
virtual bool deleteLease(const Lease4Ptr &lease)=0
Deletes an IPv4 lease.
virtual void updateLease4(const Lease4Ptr &lease4)=0
Updates IPv4 lease.
static std::list< std::string > getDBVersions()
Return extended version info for registered backends.
static OptionDefinitionPtr getOptionDef(const std::string &space, const uint16_t code)
Return the first option definition matching a particular option code.
Definition libdhcp++.cc:132
static void sanityCheckScalarLength(const OptionDefinitionPtr &def, uint16_t opt_len)
Validates a scalar option's length against it's defined length.
Definition libdhcp++.cc:719
static const OptionDefinition & DHO_DHCP_SERVER_IDENTIFIER_DEF()
Get definition of DHO_DHCP_SERVER_IDENTIFIER option.
static const OptionDefinition & DHO_DHCP_AGENT_OPTIONS_DEF()
Get definition of DHO_DHCP_AGENT_OPTIONS option.
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:195
static OptionDefinitionPtr getLastResortOptionDef(const std::string &space, const uint16_t code)
Returns last resort option definition by space and option code.
Definition libdhcp++.cc:253
Controls the DHCP service enabling status.
Attempt to update lease that was not there.
std::vector< isc::asiolink::IOAddress > AddressContainer
Defines a collection of IPv4 addresses.
Represents DHCPv4 Client FQDN Option (code 81).
static const uint8_t FLAG_N
Bit N.
bool getFlag(const uint8_t flag) const
Checks if the specified flag of the DHCPv4 Client FQDN Option is set.
static const uint8_t FLAG_S
Bit S.
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.
static unsigned int getLabelCount(const std::string &text_name)
Return the number of labels in the Name.
Base class representing a DHCP option definition.
Option descriptor.
Definition cfg_option.h:49
OptionPtr option_
Option instance.
Definition cfg_option.h:52
bool allowedForClientClasses(const ClientClasses &cclasses) const
Validates an OptionDescriptor's client-classes against a list of classes.
Definition cfg_option.cc:72
Forward declaration to OptionInt.
Definition option_int.h:49
This class represents vendor-specific information option.
static const size_t OPTION4_HDR_LEN
length of the usual DHCPv4 option header (there are exceptions)
Definition option.h:84
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:29
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
Resource race avoidance RAII handler for DHCPv4.
bool tryLock4(const asiolink::IOAddress &addr)
Tries to acquires a resource.
RAII object enabling copying options retrieved from the packet.
Definition pkt.h:46
Exception thrown when a call to select is interrupted by a signal.
Definition iface_mgr.h:58
Exception thrown during option unpacking This exception is thrown when an error has occurred,...
Definition option.h:52
static std::string const & resultToText(Result const &result)
Convert enum to string.
Definition ncr_io.h:490
Result
Defines the outcome of an asynchronous NCR send.
Definition ncr_io.h:478
@ NEXT_STEP_PARK
park the packet
@ NEXT_STEP_CONTINUE
continue normally
@ NEXT_STEP_DROP
drop the packet
@ NEXT_STEP_SKIP
skip the next processing step
static int registerHook(const std::string &name)
Register Hook.
static bool calloutsPresent(int index)
Are callouts present?
static std::vector< std::string > getLibraryNames()
Return list of loaded libraries.
static bool unloadLibraries()
Unload libraries.
static void park(const std::string &hook_name, T parked_object, std::function< void()> unpark_callback)
Park an object (packet).
static void callCallouts(int index, CalloutHandle &handle)
Calls the callouts for a given hook.
static void prepareUnloadLibraries()
Prepare the unloading of libraries.
static bool drop(const std::string &hook_name, T parked_object)
Removes parked object without calling a callback.
static void clearParkingLots()
Clears any parking packets.
Wrapper class around callout handle which automatically resets handle's state.
static ServerHooks & getServerHooks()
Return ServerHooks object.
static std::string getVersion()
Version.
Definition log/logger.cc:60
bool lock()
Acquire the lock (blocks if something else has acquired a lock on the same task name).
int getExitValue()
Fetches the exit value.
Definition daemon.h:235
Statistics Manager class.
static StatsMgr & instance()
Statistics Manager accessor method.
static std::string generateName(const std::string &context, Type index, const std::string &stat_name)
Generates statistic name in a given context.
RAII class creating a critical section.
static MultiThreadingMgr & instance()
Returns a single instance of Multi Threading Manager.
ThreadPool< std::function< void()> > & getThreadPool()
Get the dhcp thread pool.
void apply(bool enabled, uint32_t thread_count, uint32_t queue_size)
Apply the multi-threading related settings.
Read mutex RAII handler.
Defines classes for storing client class definitions.
int version()
returns Kea hooks version.
Defines the D2ClientConfig class.
Defines the D2ClientMgr class.
Contains declarations for loggers used by the DHCPv4 server component.
Dhcp4Hooks Hooks
Definition dhcp4_srv.cc:213
Defines the Dhcp4o6Ipc class.
@ D6O_INTERFACE_ID
Definition dhcp6.h:38
@ DHCPV6_DHCPV4_RESPONSE
Definition dhcp6.h:232
#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
OptionIntArray< uint8_t > OptionUint8Array
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.
int get(CalloutHandle &handle)
The gss-tsig-get command.
When a message is logged with DEBUG severity, the debug level associated with the message is also spe...
#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
boost::shared_ptr< const Element > ConstElementPtr
Definition data.h:30
@ info
Definition db_log.h:126
boost::shared_ptr< NameChangeRequest > NameChangeRequestPtr
Defines a pointer to a NameChangeRequest.
Definition ncr_msg.h:241
const isc::log::MessageID DHCP4_PACKET_NAK_0005
const isc::log::MessageID DHCP4_BUFFER_RECEIVE_FAIL
boost::shared_ptr< OptionVendor > OptionVendorPtr
Pointer to a vendor option.
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_HOOK_SUBNET4_SELECT_PARKING_LOT_FULL
const isc::log::MessageID DHCP4_DEFERRED_OPTION_UNPACK_FAIL
const isc::log::MessageID DHCP4_PACKET_DROP_0001
const isc::log::MessageID DHCP4_QUERY_DATA
const isc::log::MessageID DHCP4_NO_LEASE_INIT_REBOOT
const isc::log::MessageID DHCP4_INFORM_DIRECT_REPLY
const isc::log::MessageID DHCP4_SERVER_INITIATED_DECLINE_ADD_FAILED
boost::shared_ptr< Lease4Collection > Lease4CollectionPtr
A shared pointer to the collection of IPv4 leases.
Definition lease.h:523
const isc::log::MessageID DHCP4_HOOK_LEASE4_OFFER_ARGUMENT_MISSING
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 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_V6_ONLY_PREFERRED
Definition dhcp4.h:172
@ DHO_DHCP_SERVER_IDENTIFIER
Definition dhcp4.h:123
@ DHO_HOST_NAME
Definition dhcp4.h:81
@ DHO_DHCP_CLIENT_IDENTIFIER
Definition dhcp4.h:130
@ DHO_VIVCO_SUBOPTIONS
Definition dhcp4.h:188
@ DHO_DHCP_REQUESTED_ADDRESS
Definition dhcp4.h:119
@ DHO_DHCP_AGENT_OPTIONS
Definition dhcp4.h:151
@ DHO_SUBNET_SELECTION
Definition dhcp4.h:182
@ DHO_DHCP_PARAMETER_REQUEST_LIST
Definition dhcp4.h:124
@ DHO_FQDN
Definition dhcp4.h:150
@ DHO_VIVSO_SUBOPTIONS
Definition dhcp4.h:189
@ DHO_DHCP_RENEWAL_TIME
Definition dhcp4.h:127
@ DHO_DHCP_LEASE_TIME
Definition dhcp4.h:120
const isc::log::MessageID DHCP4_PACKET_PROCESS_EXCEPTION_MAIN
const isc::log::MessageID DHCP4_PACKET_DROP_0008
const isc::log::MessageID DHCP4_RELEASE_EXPIRED
const isc::log::MessageID DHCP4_HOOK_LEASES4_COMMITTED_DROP
const isc::log::MessageID DHCP4_HOOK_SUBNET4_SELECT_4O6_PARKING_LOT_FULL
const isc::log::MessageID DHCP4_DHCP4O6_SUBNET_SELECTION_FAILED
const isc::log::MessageID DHCP4_RELEASE_FAIL_WRONG_CLIENT
const isc::log::MessageID DHCP4_HOOK_LEASES4_COMMITTED_PARKING_LOT_FULL
const isc::log::MessageID DHCP4_HOOK_BUFFER_RCVD_DROP
boost::shared_ptr< const Subnet4 > ConstSubnet4Ptr
A const pointer to a Subnet4 object.
Definition subnet.h:455
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:556
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
const isc::log::MessageID DHCP4_CLIENT_FQDN_SCRUBBED_EMPTY
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_RECOVERED_STASHED_RELAY_AGENT_INFO
const isc::log::MessageID DHCP4_LEASE_REUSE
const isc::log::MessageID DHCP4_HOOK_SUBNET4_SELECT_PARK
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:522
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.
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_HOOK_LEASE4_OFFER_PARK
const isc::log::MessageID DHCP4_DECLINE_LEASE_MISMATCH
const isc::log::MessageID DHCP4_SRV_UNLOAD_LIBRARIES_ERROR
const isc::log::MessageID DHCP4_ADDITIONAL_CLASS_EVAL_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_LEASE_OFFER
const isc::log::MessageID DHCP4_PACKET_DROP_0009
const isc::log::MessageID DHCP4_RELEASE_FAIL_NOT_ASSIGNED
const isc::log::MessageID DHCP4_PACKET_RECEIVED
boost::shared_ptr< Pkt4o6 > Pkt4o6Ptr
A pointer to Pkt4o6 object.
Definition pkt4o6.h:83
const isc::log::MessageID DHCP4_RELEASE_DELETED
const isc::log::MessageID DHCP4_BUFFER_UNPACK
const isc::log::MessageID DHCP4_CLIENT_HOSTNAME_DATA
OptionContainer::nth_index< 5 >::type OptionContainerCancelIndex
Type of the index #5 - option cancellation flag.
Definition cfg_option.h:366
const isc::log::MessageID DHCP4_CLASSES_ASSIGNED_AFTER_SUBNET_SELECTION
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:364
boost::shared_ptr< OptionDefinition > OptionDefinitionPtr
Pointer to option definition object.
const isc::log::MessageID DHCP4_DHCP4O6_SUBNET_DATA
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_HOOK_DDNS_UPDATE
const isc::log::MessageID DHCP4_SRV_CONSTRUCT_ERROR
const isc::log::MessageID DHCP4_SERVER_INITIATED_DECLINE
boost::shared_ptr< Expression > ExpressionPtr
Definition token.h:31
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:726
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_V6_ONLY_PREFERRED_MISSING_IN_ACK
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_SERVER_INITIATED_DECLINE_UPDATE_FAILED
const isc::log::MessageID DHCP4_RESPONSE_FQDN_DATA
boost::shared_ptr< ClientId > ClientIdPtr
Shared pointer to a Client ID.
Definition duid.h:216
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:350
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:237
@ DHCP_TYPES_EOF
Definition dhcp4.h:253
@ DHCPOFFER
Definition dhcp4.h:236
@ DHCPDECLINE
Definition dhcp4.h:238
@ DHCPNAK
Definition dhcp4.h:240
@ DHCPRELEASE
Definition dhcp4.h:241
@ DHCPDISCOVER
Definition dhcp4.h:235
@ DHCP_NOTYPE
Message Type option missing.
Definition dhcp4.h:234
@ DHCPINFORM
Definition dhcp4.h:242
@ DHCPACK
Definition dhcp4.h:239
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.
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:34
const isc::log::MessageID DHCP4_SUBNET_SELECTION_FAILED
boost::shared_ptr< const Host > ConstHostPtr
Const pointer to the Host object.
Definition host.h:840
const isc::log::MessageID DHCP4_RESPONSE_DATA
const isc::log::MessageID DHCP4_ADDITIONAL_CLASS_NO_TEST
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:359
const isc::log::MessageID DHCP4_DECLINE_LEASE
const isc::log::MessageID DHCP4_PACKET_SEND
boost::shared_ptr< OptionVendorClass > OptionVendorClassPtr
Defines a pointer to the OptionVendorClass.
const isc::log::MessageID DHCP4_RELEASE
const isc::log::MessageID DHCP4_HOOK_LEASE4_OFFER_DROP
const isc::log::MessageID DHCP4_HOOK_BUFFER_RCVD_SKIP
const isc::log::MessageID DHCP4_UNKNOWN_ADDRESS_REQUESTED
boost::shared_ptr< Pkt6 > Pkt6Ptr
A pointer to Pkt6 packet.
Definition pkt6.h:31
const isc::log::MessageID DHCP4_PACKET_PROCESS_STD_EXCEPTION_MAIN
const isc::log::MessageID DHCP4_DHCP4O6_HOOK_SUBNET4_SELECT_DROP
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
const isc::log::MessageID DHCP4_CLASSES_ASSIGNED
@ RAI_OPTION_SERVER_ID_OVERRIDE
Definition dhcp4.h:275
@ RAI_OPTION_AGENT_CIRCUIT_ID
Definition dhcp4.h:265
@ RAI_OPTION_RELAY_PORT
Definition dhcp4.h:283
const isc::log::MessageID DHCP4_QUERY_LABEL
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:520
const isc::log::MessageID DHCP4_HOOK_BUFFER_SEND_SKIP
const isc::log::MessageID DHCP4_PACKET_PROCESS_EXCEPTION
const isc::log::MessageID DHCP4_V6_ONLY_PREFERRED_MISSING_IN_OFFER
std::pair< OptionContainerCancelIndex::const_iterator, OptionContainerCancelIndex::const_iterator > OptionContainerCancelRange
Pair of iterators to represent the range of options having the same cancellation flag.
Definition cfg_option.h:371
const isc::log::MessageID DHCP4_PACKET_OPTIONS_SKIPPED
const isc::log::MessageID DHCP4_EMPTY_HOSTNAME
const isc::log::MessageID DHCP4_REQUEST
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:315
const isc::log::MessageID DHCP4_SERVER_INITIATED_DECLINE_RESOURCE_BUSY
const isc::log::MessageID DHCP4_CLASS_UNCONFIGURED
const isc::log::MessageID DHCP4_DHCP4O6_SUBNET_SELECTED
boost::shared_ptr< Option > OptionPtr
Definition option.h:37
const isc::log::MessageID DHCP4_HOOK_LEASE4_OFFER_PARKING_LOT_FULL
const int DBG_DHCP4_START
Debug level used to log information during server startup.
Definition dhcp4_log.h:24
const isc::log::MessageID DHCP4_HOOK_LEASES4_COMMITTED_PARK
const isc::log::MessageID DHCP4_ADDITIONAL_CLASS_UNDEFINED
const isc::log::MessageID DHCP4_ADDITIONAL_CLASS_EVAL_RESULT
const isc::log::MessageID DHCP4_DHCP4O6_HOOK_SUBNET4_SELECT_SKIP
const isc::log::MessageID DHCP4_PACKET_DROP_0014
std::list< ConstCfgOptionPtr > CfgOptionList
Const pointer list.
Definition cfg_option.h:979
const isc::log::MessageID DHCP4_DISCOVER
const isc::log::MessageID DHCP4_CLIENT_HOSTNAME_SCRUBBED_EMPTY
boost::shared_ptr< const CfgOption > ConstCfgOptionPtr
Const pointer.
Definition cfg_option.h:976
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.
boost::shared_ptr< ParkingLot > ParkingLotPtr
Type of the pointer to the parking lot.
const int DBGLVL_TRACE_BASIC
Trace basic operations.
const int DBGLVL_PKT_HANDLING
This debug level is reserved for logging the details of packet handling, such as dropping the packet ...
const char * MessageID
std::unique_ptr< StringSanitizer > StringSanitizerPtr
Type representing the pointer to the StringSanitizer.
Definition str.h:263
void decodeFormattedHexString(const string &hex_string, vector< uint8_t > &binary)
Converts a formatted string of hexadecimal digits into a vector.
Definition str.cc:212
string trim(const string &input)
Trim leading and trailing spaces.
Definition str.cc:32
Defines the logger used by the top-level component of kea-lfc.
This file defines abstract classes for exchanging NameChangeRequests.
This file provides the classes needed to embody, compose, and decompose DNS update requests that are ...
Standard implementation of read-write mutexes with writer preference using C++11 mutex and condition ...
#define DHCP4_OPTION_SPACE
global std option spaces
Context information for the DHCPv4 lease allocation.
static const uint32_t INFINITY_LFT
Infinity (means static, i.e. never expire).
Definition lease.h:34
static constexpr uint32_t STATE_DEFAULT
A lease in the default state.
Definition lease.h:69
static std::string lifetimeToText(uint32_t lifetime)
Print lifetime.
Definition lease.cc:34
static std::string basicStatesToText(const uint32_t state)
Returns name(s) of the basic lease state(s).
Definition lease.cc:89
static constexpr uint32_t STATE_RELEASED
Released lease held in the database for lease affinity.
Definition lease.h:78
@ TYPE_V4
IPv4 lease.
Definition lease.h:50
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.
bool add(const WorkItemPtr &item)
add a work item to the thread pool