Kea 2.5.8
ncr_udp.cc
Go to the documentation of this file.
1// Copyright (C) 2013-2024 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
10#include <dhcp_ddns/ncr_udp.h>
11#include <stats/stats_mgr.h>
12
13#include <functional>
14
15namespace ph = std::placeholders;
16
17namespace isc {
18namespace dhcp_ddns {
19
20//*************************** UDPCallback ***********************
21UDPCallback::UDPCallback (RawBufferPtr& buffer, const size_t buf_size,
22 UDPEndpointPtr& data_source,
23 const UDPCompletionHandler& handler)
24 : handler_(handler), data_(new Data(buffer, buf_size, data_source)) {
25 if (!handler) {
26 isc_throw(NcrUDPError, "UDPCallback - handler can't be null");
27 }
28
29 if (!buffer) {
30 isc_throw(NcrUDPError, "UDPCallback - buffer can't be null");
31 }
32}
33
34void
35UDPCallback::operator ()(const boost::system::error_code error_code,
36 const size_t bytes_transferred) {
37
38 // Save the result state and number of bytes transferred.
39 setErrorCode(error_code);
40 setBytesTransferred(bytes_transferred);
41
42 // Invoke the NameChangeRequest layer completion handler.
43 // First argument is a boolean indicating success or failure.
44 // The second is a pointer to "this" callback object. By passing
45 // ourself in, we make all of the service related data available
46 // to the completion handler.
47 handler_(!error_code, this);
48}
49
50void
51UDPCallback::putData(const uint8_t* src, size_t len) {
52 if (!src) {
53 isc_throw(NcrUDPError, "UDPCallback putData, data source is NULL");
54 }
55
56 if (len > data_->buf_size_) {
57 isc_throw(NcrUDPError, "UDPCallback putData, data length too large");
58 }
59
60 memcpy (data_->buffer_.get(), src, len);
61 data_->put_len_ = len;
62}
63
64//*************************** NameChangeUDPListener ***********************
67 const uint32_t port, const NameChangeFormat format,
68 RequestReceiveHandler& ncr_recv_handler,
69 const bool reuse_address)
70 : NameChangeListener(ncr_recv_handler), ip_address_(ip_address),
71 port_(port), format_(format), reuse_address_(reuse_address) {
72 // Instantiate the receive callback. This gets passed into each receive.
73 // Note that the callback constructor is passed an instance method
74 // pointer to our completion handler method, receiveCompletionHandler.
75 RawBufferPtr buffer(new uint8_t[RECV_BUF_MAX]);
76 UDPEndpointPtr data_source(new asiolink::UDPEndpoint());
77 recv_callback_.reset(new UDPCallback(buffer, RECV_BUF_MAX, data_source,
79 this, ph::_1, ph::_2)));
80}
81
83 // Clean up.
85}
86
87void
89 // create our endpoint and bind the low level socket to it.
90 isc::asiolink::UDPEndpoint endpoint(ip_address_, port_);
91
92 io_service_ = io_service;
93
94 // Create the low level socket.
95 try {
96 asio_socket_.reset(new boost::asio::ip::udp::
97 socket(io_service_->getInternalIOService(),
98 (ip_address_.isV4() ? boost::asio::ip::udp::v4() :
99 boost::asio::ip::udp::v6())));
100
101 // Set the socket option to reuse addresses if it is enabled.
102 if (reuse_address_) {
103 asio_socket_->set_option(boost::asio::socket_base::reuse_address(true));
104 }
105
106 // Bind the low level socket to our endpoint.
107 asio_socket_->bind(endpoint.getASIOEndpoint());
108 } catch (const boost::system::system_error& ex) {
109 asio_socket_.reset();
110 io_service_.reset();
111 isc_throw (NcrUDPError, ex.code().message());
112 }
113
114 // Create the asiolink socket from the low level socket.
115 socket_.reset(new NameChangeUDPSocket(*asio_socket_));
116}
117
118void
120 // Call the socket's asynchronous receiving, passing ourself in as callback.
121 RawBufferPtr recv_buffer = recv_callback_->getBuffer();
122 socket_->asyncReceive(recv_buffer.get(), recv_callback_->getBufferSize(),
123 0, recv_callback_->getDataSource().get(),
124 *recv_callback_);
125}
126
127void
129 // Whether we think we are listening or not, make sure we aren't.
130 // Since we are managing our own socket, we need to close it ourselves.
131 // NOTE that if there is a pending receive, it will be canceled, which
132 // WILL generate an invocation of the callback with error code of
133 // "operation aborted".
134 if (asio_socket_) {
135 if (asio_socket_->is_open()) {
136 try {
137 asio_socket_->close();
138 } catch (const boost::system::system_error& ex) {
139 // It is really unlikely that this will occur.
140 // If we do reopen later it will be with a new socket
141 // instance. Repackage exception as one that is conformant
142 // with the interface.
143 isc_throw (NcrUDPError, ex.code().message());
144 }
145 }
146
147 asio_socket_.reset();
148 }
149
150 if (socket_) {
151 socket_->close();
152 }
153 socket_.reset();
154 io_service_.reset();
155}
156
157void
159 const UDPCallback *callback) {
161 Result result = SUCCESS;
162
163 if (successful) {
164 // Make an InputBuffer from our internal array
165 isc::util::InputBuffer input_buffer(callback->getData(),
166 callback->getBytesTransferred());
167
168 try {
169 ncr = NameChangeRequest::fromFormat(format_, input_buffer);
171 static_cast<int64_t>(1));
172 } catch (const NcrMessageError& ex) {
173 // log it and go back to listening
176 static_cast<int64_t>(1));
177
178 // Queue up the next receive.
179 // NOTE: We must call the base class, NEVER doReceive
180 receiveNext();
181 return;
182 }
183 } else {
184 boost::system::error_code error_code = callback->getErrorCode();
185 if (error_code.value() == boost::asio::error::operation_aborted) {
186 // A shutdown cancels all outstanding reads. For this reason,
187 // it can be an expected event, so log it as a debug message.
190 result = STOPPED;
191 } else {
193 .arg(error_code.message());
195 static_cast<int64_t>(1));
196 result = ERROR;
197 }
198 }
199
200 // Call the application's registered request receive handler.
201 invokeRecvHandler(result, ncr);
202}
203
204//*************************** NameChangeUDPSender ***********************
205
208 const uint32_t port,
209 const isc::asiolink::IOAddress& server_address,
210 const uint32_t server_port, const NameChangeFormat format,
211 RequestSendHandler& ncr_send_handler,
212 const size_t send_que_max, const bool reuse_address)
213 : NameChangeSender(ncr_send_handler, send_que_max),
214 ip_address_(ip_address), port_(port), server_address_(server_address),
215 server_port_(server_port), format_(format),
216 reuse_address_(reuse_address) {
217 // Instantiate the send callback. This gets passed into each send.
218 // Note that the callback constructor is passed the an instance method
219 // pointer to our completion handler, sendCompletionHandler.
220 RawBufferPtr buffer(new uint8_t[SEND_BUF_MAX]);
221 UDPEndpointPtr data_source(new asiolink::UDPEndpoint());
222 send_callback_.reset(new UDPCallback(buffer, SEND_BUF_MAX, data_source,
224 this, ph::_1, ph::_2)));
225}
226
228 // Clean up.
229 stopSending();
230}
231
232void
234 // create our endpoint and bind the low level socket to it.
235 isc::asiolink::UDPEndpoint endpoint(ip_address_, port_);
236
237 io_service_ = io_service;
238
239 // Create the low level socket.
240 try {
241 asio_socket_.reset(new boost::asio::ip::udp::
242 socket(io_service_->getInternalIOService(),
243 (ip_address_.isV4() ? boost::asio::ip::udp::v4() :
244 boost::asio::ip::udp::v6())));
245
246 // Set the socket option to reuse addresses if it is enabled.
247 if (reuse_address_) {
248 asio_socket_->set_option(boost::asio::socket_base::reuse_address(true));
249 }
250
251 // Bind the low level socket to our endpoint.
252 asio_socket_->bind(endpoint.getASIOEndpoint());
253 } catch (const boost::system::system_error& ex) {
254 asio_socket_.reset();
255 io_service_.reset();
256 isc_throw (NcrUDPError, ex.code().message());
257 }
258
259 // Create the asiolink socket from the low level socket.
260 socket_.reset(new NameChangeUDPSocket(*asio_socket_));
261
262 // Create the server endpoint
263 server_endpoint_.reset(new isc::asiolink::
264 UDPEndpoint(server_address_, server_port_));
265
266 send_callback_->setDataSource(server_endpoint_);
267
268 closeWatchSocket();
269 watch_socket_.reset(new util::WatchSocket());
270}
271
272void
274 // Whether we think we are sending or not, make sure we aren't.
275 // Since we are managing our own socket, we need to close it ourselves.
276 // NOTE that if there is a pending send, it will be canceled, which
277 // WILL generate an invocation of the callback with error code of
278 // "operation aborted".
279 if (asio_socket_) {
280 if (asio_socket_->is_open()) {
281 try {
282 asio_socket_->close();
283 } catch (const boost::system::system_error& ex) {
284 // It is really unlikely that this will occur.
285 // If we do reopen later it will be with a new socket
286 // instance. Repackage exception as one that is conformant
287 // with the interface.
288 isc_throw (NcrUDPError, ex.code().message());
289 }
290 }
291
292 asio_socket_.reset();
293 }
294
295 if (socket_) {
296 socket_->close();
297 }
298 socket_.reset();
299
300 closeWatchSocket();
301 watch_socket_.reset();
302 io_service_.reset();
303}
304
305void
307 // Now use the NCR to write JSON to an output buffer.
309 ncr->toFormat(format_, ncr_buffer);
310
311 // Copy the wire-ized request to callback. This way we know after
312 // send completes what we sent (or attempted to send).
313 send_callback_->putData(ncr_buffer.getData(), ncr_buffer.getLength());
314
315 // Call the socket's asynchronous send, passing our callback
316 socket_->asyncSend(send_callback_->getData(), send_callback_->getPutLen(),
317 send_callback_->getDataSource().get(), *send_callback_);
318
319 // Set IO ready marker so sender activity is visible to select() or poll().
320 // Note, if this call throws it will manifest itself as a throw from
321 // from sendRequest() which the application calls directly and is documented
322 // as throwing exceptions; or caught inside invokeSendHandler() which
323 // will invoke the application's send_handler with an error status.
324 watch_socket_->markReady();
325}
326
327void
329 const UDPCallback *send_callback) {
330 // Clear the IO ready marker.
331 try {
332 watch_socket_->clearReady();
333 } catch (const std::exception& ex) {
334 // This can only happen if the WatchSocket's select_fd has been
335 // compromised which is a programmatic error. We'll log the error
336 // here, then continue on and process the IO result we were given.
337 // WatchSocket issue will resurface on the next send as a closed
338 // fd in markReady(). This allows application's handler to deal
339 // with watch errors more uniformly.
341 .arg(ex.what());
342 }
343
344 Result result;
345 if (successful) {
346 result = SUCCESS;
347 } else {
348 // On a failure, log the error and set the result to ERROR.
349 boost::system::error_code error_code = send_callback->getErrorCode();
350 if (error_code.value() == boost::asio::error::operation_aborted) {
352 .arg(error_code.message());
353 result = STOPPED;
354 } else {
356 .arg(error_code.message());
357 result = ERROR;
358 }
359 }
360
361 // Call the application's registered request send handler.
362 invokeSendHandler(result);
363}
364
365int
367 if (!amSending()) {
368 isc_throw(NotImplemented, "NameChangeUDPSender::getSelectFd"
369 " not in send mode");
370 }
371
372 return(watch_socket_->getSelectFd());
373}
374
375bool
377 if (watch_socket_) {
378 return (watch_socket_->isReady());
379 }
380
381 return (false);
382}
383
384void
385NameChangeUDPSender::closeWatchSocket() {
386 if (watch_socket_) {
387 std::string error_string;
388 watch_socket_->closeSocket(error_string);
389 if (!error_string.empty()) {
391 .arg(error_string);
392 }
393 }
394}
395
396} // end of isc::dhcp_ddns namespace
397} // end of isc namespace
virtual const char * what() const
Returns a C-style character string of the cause of the exception.
A generic exception that is thrown when a function is not implemented.
Abstract class for defining application layer receive callbacks.
Definition: ncr_io.h:182
Abstract interface for receiving NameChangeRequests.
Definition: ncr_io.h:166
void stopListening()
Closes the IO source and stops listen logic.
Definition: ncr_io.cc:93
void invokeRecvHandler(const Result result, NameChangeRequestPtr &ncr)
Calls the NCR receive handler registered with the listener.
Definition: ncr_io.cc:110
Result
Defines the outcome of an asynchronous NCR receive.
Definition: ncr_io.h:170
void receiveNext()
Initiates an asynchronous receive.
Definition: ncr_io.cc:87
static NameChangeRequestPtr fromFormat(const NameChangeFormat format, isc::util::InputBuffer &buffer)
Static method for creating a NameChangeRequest from a buffer containing a marshalled request in a giv...
Definition: ncr_msg.cc:299
Abstract class for defining application layer send callbacks.
Definition: ncr_io.h:486
Abstract interface for sending NameChangeRequests.
Definition: ncr_io.h:464
asiolink::IOServicePtr io_service_
Pointer to the IOService currently being used by the sender.
Definition: ncr_io.h:826
void stopSending()
Closes the IO sink and stops send logic.
Definition: ncr_io.cc:206
bool amSending() const
Returns true if the sender is in send mode, false otherwise.
Definition: ncr_io.h:731
void invokeSendHandler(const NameChangeSender::Result result)
Calls the NCR send completion handler registered with the sender.
Definition: ncr_io.cc:294
Result
Defines the outcome of an asynchronous NCR send.
Definition: ncr_io.h:474
virtual void close()
Closes the UDPSocket.
Definition: ncr_udp.cc:128
virtual void open(const isc::asiolink::IOServicePtr &io_service)
Opens a UDP socket using the given IOService.
Definition: ncr_udp.cc:88
virtual ~NameChangeUDPListener()
Destructor.
Definition: ncr_udp.cc:82
static const size_t RECV_BUF_MAX
Defines the maximum size packet that can be received.
Definition: ncr_udp.h:321
void receiveCompletionHandler(const bool successful, const UDPCallback *recv_callback)
Implements the NameChangeRequest level receive completion handler.
Definition: ncr_udp.cc:158
void doReceive()
Initiates an asynchronous read on the socket.
Definition: ncr_udp.cc:119
NameChangeUDPListener(const isc::asiolink::IOAddress &ip_address, const uint32_t port, const NameChangeFormat format, RequestReceiveHandler &ncr_recv_handler, const bool reuse_address=false)
Constructor.
Definition: ncr_udp.cc:66
void sendCompletionHandler(const bool successful, const UDPCallback *send_callback)
Implements the NameChangeRequest level send completion handler.
Definition: ncr_udp.cc:328
virtual bool ioReady()
Returns whether or not the sender has IO ready to process.
Definition: ncr_udp.cc:376
static const size_t SEND_BUF_MAX
Defines the maximum size packet that can be sent.
Definition: ncr_udp.h:448
virtual void open(const isc::asiolink::IOServicePtr &io_service)
Opens a UDP socket using the given IOService.
Definition: ncr_udp.cc:233
virtual int getSelectFd()
Returns a file descriptor suitable for use with select.
Definition: ncr_udp.cc:366
virtual void close()
Closes the UDPSocket.
Definition: ncr_udp.cc:273
NameChangeUDPSender(const isc::asiolink::IOAddress &ip_address, const uint32_t port, const isc::asiolink::IOAddress &server_address, const uint32_t server_port, const NameChangeFormat format, RequestSendHandler &ncr_send_handler, const size_t send_que_max=NameChangeSender::MAX_QUEUE_DEFAULT, const bool reuse_address=false)
Constructor.
Definition: ncr_udp.cc:207
virtual void doSend(NameChangeRequestPtr &ncr)
Sends a given request asynchronously over the socket.
Definition: ncr_udp.cc:306
virtual ~NameChangeUDPSender()
Destructor.
Definition: ncr_udp.cc:227
Exception thrown when NameChangeRequest marshalling error occurs.
Definition: ncr_msg.h:30
Thrown when a UDP level exception occurs.
Definition: ncr_udp.h:121
Implements the callback class passed into UDPSocket calls.
Definition: ncr_udp.h:146
size_t getBytesTransferred() const
Returns the number of bytes transferred by the completed IO service.
Definition: ncr_udp.h:230
void setErrorCode(const boost::system::error_code value)
Sets the completed IO layer service outcome status.
Definition: ncr_udp.h:249
const uint8_t * getData() const
Returns a pointer the data transfer buffer content.
Definition: ncr_udp.h:264
void putData(const uint8_t *src, size_t len)
Copies data into the data transfer buffer.
Definition: ncr_udp.cc:51
UDPCallback(RawBufferPtr &buffer, const size_t buf_size, UDPEndpointPtr &data_source, const UDPCompletionHandler &handler)
Used as the callback object for UDPSocket services.
Definition: ncr_udp.cc:21
void setBytesTransferred(const size_t value)
Sets the number of bytes transferred.
Definition: ncr_udp.h:237
void operator()(const boost::system::error_code error_code, const size_t bytes_transferred)
Operator that will be invoked by the asiolink layer.
Definition: ncr_udp.cc:35
boost::system::error_code getErrorCode() const
Returns the completed IO layer service outcome status.
Definition: ncr_udp.h:242
static StatsMgr & instance()
Statistics Manager accessor method.
The InputBuffer class is a buffer abstraction for manipulating read-only data.
Definition: buffer.h:82
The OutputBuffer class is a buffer abstraction for manipulating mutable data.
Definition: buffer.h:347
const uint8_t * getData() const
Return a pointer to the head of the data stored in the buffer.
Definition: buffer.h:398
size_t getLength() const
Return the length of data written in the buffer.
Definition: buffer.h:412
Provides an IO "ready" semaphore for use with select() or poll() WatchSocket exposes a single open fi...
Definition: watch_socket.h:47
#define isc_throw(type, stream)
A shortcut macro to insert known values into exception arguments.
void addValue(const std::string &name, const int64_t value)
Records incremental integer observation.
#define LOG_ERROR(LOGGER, MESSAGE)
Macro to conveniently test error output and log it.
Definition: macros.h:32
#define LOG_DEBUG(LOGGER, LEVEL, MESSAGE)
Macro to conveniently test debug output and log it.
Definition: macros.h:14
const isc::log::MessageID DHCP_DDNS_NCR_UDP_RECV_ERROR
isc::log::Logger dhcp_ddns_logger("libdhcp-ddns")
Defines the logger used within lib dhcp_ddns.
Definition: dhcp_ddns_log.h:18
NameChangeFormat
Defines the list of data wire formats supported.
Definition: ncr_msg.h:59
const isc::log::MessageID DHCP_DDNS_NCR_UDP_SEND_CANCELED
const isc::log::MessageID DHCP_DDNS_NCR_UDP_SEND_ERROR
const isc::log::MessageID DHCP_DDNS_NCR_UDP_CLEAR_READY_ERROR
std::function< void(const bool, const UDPCallback *)> UDPCompletionHandler
Defines a function pointer for NameChangeRequest completion handlers.
Definition: ncr_udp.h:130
const isc::log::MessageID DHCP_DDNS_NCR_UDP_RECV_CANCELED
isc::asiolink::UDPSocket< UDPCallback > NameChangeUDPSocket
Convenience type for UDP socket based listener.
Definition: ncr_udp.h:310
boost::shared_ptr< NameChangeRequest > NameChangeRequestPtr
Defines a pointer to a NameChangeRequest.
Definition: ncr_msg.h:241
const isc::log::MessageID DHCP_DDNS_INVALID_NCR
boost::shared_array< uint8_t > RawBufferPtr
Defines a dynamically allocated shared array.
Definition: ncr_udp.h:133
boost::shared_ptr< asiolink::UDPEndpoint > UDPEndpointPtr
Definition: ncr_udp.h:135
const isc::log::MessageID DHCP_DDNS_UDP_SENDER_WATCH_SOCKET_CLOSE_ERROR
const int DBGLVL_TRACE_BASIC
Trace basic operations.
Definition: log_dbglevels.h:69
Defines the logger used by the top-level component of kea-lfc.
This file provides UDP socket based implementation for sending and receiving NameChangeRequests.
Container class which stores service invocation related data.
Definition: ncr_udp.h:156