Loading...
Searching...
No Matches
datagram-transport.hpp
Go to the documentation of this file.
1/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2/*
3 * Copyright (c) 2014-2024, Regents of the University of California,
4 * Arizona Board of Regents,
5 * Colorado State University,
6 * University Pierre & Marie Curie, Sorbonne University,
7 * Washington University in St. Louis,
8 * Beijing Institute of Technology,
9 * The University of Memphis.
10 *
11 * This file is part of NFD (Named Data Networking Forwarding Daemon).
12 * See AUTHORS.md for complete list of NFD authors and contributors.
13 *
14 * NFD is free software: you can redistribute it and/or modify it under the terms
15 * of the GNU General Public License as published by the Free Software Foundation,
16 * either version 3 of the License, or (at your option) any later version.
17 *
18 * NFD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
19 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
20 * PURPOSE. See the GNU General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License along with
23 * NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
24 */
25
26#ifndef NFD_DAEMON_FACE_DATAGRAM_TRANSPORT_HPP
27#define NFD_DAEMON_FACE_DATAGRAM_TRANSPORT_HPP
28
29#include "transport.hpp"
30#include "socket-utils.hpp"
31#include "common/global.hpp"
32
33#include <array>
34
35#include <boost/asio/defer.hpp>
36
37namespace nfd::face {
38
39struct Unicast {};
40struct Multicast {};
41
48template<class Protocol, class Addressing>
50{
51public:
52 using protocol = Protocol;
53 using addressing = Addressing;
54
60 explicit
61 DatagramTransport(typename protocol::socket&& socket);
62
63 ssize_t
65
69 void
70 receiveDatagram(span<const uint8_t> buffer, const boost::system::error_code& error);
71
72protected:
73 void
74 doClose() override;
75
76 void
77 doSend(const Block& packet) override;
78
79 void
80 handleSend(const boost::system::error_code& error, size_t nBytesSent);
81
82 void
83 handleReceive(const boost::system::error_code& error, size_t nBytesReceived);
84
85 void
86 processErrorCode(const boost::system::error_code& error);
87
88 bool
90
91 void
93
94protected:
95 typename protocol::socket m_socket;
96 typename protocol::endpoint m_sender;
97
99
100private:
101 std::array<uint8_t, ndn::MAX_NDN_PACKET_SIZE> m_receiveBuffer;
102 bool m_hasRecentlyReceived = false;
103};
104
105
106template<class T, class U>
107DatagramTransport<T, U>::DatagramTransport(typename DatagramTransport::protocol::socket&& socket)
108 : m_socket(std::move(socket))
109{
110 boost::asio::socket_base::send_buffer_size sendBufferSizeOption;
111 boost::system::error_code error;
112 m_socket.get_option(sendBufferSizeOption, error);
113 if (error) {
114 NFD_LOG_FACE_WARN("Failed to obtain send queue capacity from socket: " << error.message());
116 }
117 else {
118 this->setSendQueueCapacity(sendBufferSizeOption.value());
119 }
120
121 m_socket.async_receive_from(boost::asio::buffer(m_receiveBuffer), m_sender,
122 [this] (auto&&... args) {
123 this->handleReceive(std::forward<decltype(args)>(args)...);
124 });
125}
126
127template<class T, class U>
128ssize_t
130{
131 ssize_t queueLength = getTxQueueLength(m_socket.native_handle());
132 if (queueLength == QUEUE_ERROR) {
133 NFD_LOG_FACE_WARN("Failed to obtain send queue length from socket: " << std::strerror(errno));
134 }
135 return queueLength;
136}
137
138template<class T, class U>
139void
141{
142 NFD_LOG_FACE_TRACE(__func__);
143
144 if (m_socket.is_open()) {
145 // Cancel all outstanding operations and close the socket.
146 // Use the non-throwing variants and ignore errors, if any.
147 boost::system::error_code error;
148 m_socket.cancel(error);
149 m_socket.close(error);
150 }
151
152 // Ensure that the Transport stays alive at least until
153 // all pending handlers are dispatched
154 boost::asio::defer(getGlobalIoService(), [this] {
155 this->setState(TransportState::CLOSED);
156 });
157}
158
159template<class T, class U>
160void
162{
163 NFD_LOG_FACE_TRACE(__func__);
164
165 m_socket.async_send(boost::asio::buffer(packet),
166 // 'packet' is copied into the lambda to retain the underlying Buffer
167 [this, packet] (auto&&... args) {
168 this->handleSend(std::forward<decltype(args)>(args)...);
169 });
170}
171
172template<class T, class U>
173void
175 const boost::system::error_code& error)
176{
177 if (error)
178 return processErrorCode(error);
179
180 NFD_LOG_FACE_TRACE("Received: " << buffer.size() << " bytes from " << m_sender);
181
182 auto [isOk, element] = Block::fromBuffer(buffer);
183 if (!isOk) {
184 NFD_LOG_FACE_WARN("Failed to parse incoming packet from " << m_sender);
185 // This packet won't extend the face lifetime
186 return;
187 }
188 if (element.size() != buffer.size()) {
189 NFD_LOG_FACE_WARN("Received datagram size and decoded element size don't match");
190 // This packet won't extend the face lifetime
191 return;
192 }
193 m_hasRecentlyReceived = true;
194
195 if constexpr (std::is_same_v<addressing, Multicast>)
196 this->receive(element, m_sender);
197 else
198 this->receive(element);
199}
200
201template<class T, class U>
202void
203DatagramTransport<T, U>::handleReceive(const boost::system::error_code& error, size_t nBytesReceived)
204{
205 receiveDatagram(ndn::make_span(m_receiveBuffer).first(nBytesReceived), error);
206
207 if (m_socket.is_open())
208 m_socket.async_receive_from(boost::asio::buffer(m_receiveBuffer), m_sender,
209 [this] (auto&&... args) {
210 this->handleReceive(std::forward<decltype(args)>(args)...);
211 });
212}
213
214template<class T, class U>
215void
216DatagramTransport<T, U>::handleSend(const boost::system::error_code& error, size_t nBytesSent)
217{
218 if (error)
219 return processErrorCode(error);
220
221 NFD_LOG_FACE_TRACE("Successfully sent: " << nBytesSent << " bytes");
222}
223
224template<class T, class U>
225void
226DatagramTransport<T, U>::processErrorCode(const boost::system::error_code& error)
227{
228 NFD_LOG_FACE_TRACE(__func__);
229
230 if (getState() == TransportState::CLOSING ||
231 getState() == TransportState::FAILED ||
232 getState() == TransportState::CLOSED ||
233 error == boost::asio::error::operation_aborted) {
234 // transport is shutting down, ignore any errors
235 return;
236 }
237
238 if (getPersistency() == ndn::nfd::FACE_PERSISTENCY_PERMANENT) {
239 NFD_LOG_FACE_DEBUG("Permanent face ignores error: " << error.message());
240 return;
241 }
242
243 NFD_LOG_FACE_ERROR("Send or receive operation failed: " << error.message());
244 this->setState(TransportState::FAILED);
245 doClose();
246}
247
248template<class T, class U>
249bool
251{
252 return m_hasRecentlyReceived;
253}
254
255template<class T, class U>
256void
258{
259 m_hasRecentlyReceived = false;
260}
261
262} // namespace nfd::face
263
264#endif // NFD_DAEMON_FACE_DATAGRAM_TRANSPORT_HPP
Implements a Transport for datagram-based protocols.
void processErrorCode(const boost::system::error_code &error)
ssize_t getSendQueueLength() override
Returns the current send queue length of the transport (in octets).
DatagramTransport(typename protocol::socket &&socket)
Construct datagram transport.
void doSend(const Block &packet) override
Performs Transport specific operations to send a packet.
void handleSend(const boost::system::error_code &error, size_t nBytesSent)
void receiveDatagram(span< const uint8_t > buffer, const boost::system::error_code &error)
Receive datagram, translate buffer into packet, deliver to parent class.
void handleReceive(const boost::system::error_code &error, size_t nBytesReceived)
void doClose() override
Performs Transport specific operations to close the transport.
The lower half of a Face.
void setSendQueueCapacity(ssize_t sendQueueCapacity) noexcept
#define NFD_LOG_FACE_ERROR(msg)
Log a message at ERROR level.
#define NFD_LOG_FACE_DEBUG(msg)
Log a message at DEBUG level.
#define NFD_LOG_FACE_WARN(msg)
Log a message at WARN level.
#define NFD_LOG_FACE_TRACE(msg)
Log a message at TRACE level.
#define NFD_LOG_MEMBER_DECL()
Definition logger.hpp:32
@ CLOSED
the transport is closed, and can be safely deallocated
@ CLOSING
the transport is being closed gracefully, either by the peer or by a call to close()
@ FAILED
the transport is being closed due to a failure
constexpr ssize_t QUEUE_ERROR
Indicates that the transport was unable to retrieve the queue capacity/length.
ssize_t getTxQueueLength(int fd)
Obtain send queue length from a specified system socket.
boost::asio::io_context & getGlobalIoService()
Returns the global io_context instance for the calling thread.
Definition global.cpp:36