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