udp-channel.cpp
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 #include "udp-channel.hpp"
27 #include "face.hpp"
28 #include "generic-link-service.hpp"
30 #include "common/global.hpp"
31 
32 #include <boost/asio/ip/v6_only.hpp>
33 
34 namespace nfd::face {
35 
36 namespace ip = boost::asio::ip;
37 
38 NFD_LOG_INIT(UdpChannel);
39 
41  time::nanoseconds idleTimeout,
42  bool wantCongestionMarking,
43  size_t defaultMtu)
44  : m_localEndpoint(localEndpoint)
45  , m_socket(getGlobalIoService())
46  , m_idleFaceTimeout(idleTimeout)
47  , m_wantCongestionMarking(wantCongestionMarking)
48 {
49  setUri(FaceUri(m_localEndpoint));
50  setDefaultMtu(defaultMtu);
51  NFD_LOG_CHAN_INFO("Creating channel");
52 }
53 
54 void
55 UdpChannel::connect(const udp::Endpoint& remoteEndpoint,
56  const FaceParams& params,
57  const FaceCreatedCallback& onFaceCreated,
58  const FaceCreationFailedCallback& onConnectFailed)
59 {
60  shared_ptr<Face> face;
61  try {
62  face = createFace(remoteEndpoint, params).second;
63  }
64  catch (const boost::system::system_error& e) {
65  NFD_LOG_CHAN_DEBUG("Face creation for " << remoteEndpoint << " failed: " << e.what());
66  if (onConnectFailed)
67  onConnectFailed(504, "Face creation failed: "s + e.what());
68  return;
69  }
70 
71  // Need to invoke the callback regardless of whether or not we had already
72  // created the face so that control responses and such can be sent
73  onFaceCreated(face);
74 }
75 
76 void
78  const FaceCreationFailedCallback& onFaceCreationFailed)
79 {
80  if (isListening()) {
81  NFD_LOG_CHAN_WARN("Already listening");
82  return;
83  }
84 
85  m_socket.open(m_localEndpoint.protocol());
86  m_socket.set_option(boost::asio::socket_base::reuse_address(true));
87  if (m_localEndpoint.address().is_v6()) {
88  m_socket.set_option(ip::v6_only(true));
89  }
90  m_socket.bind(m_localEndpoint);
91 
92  waitForNewPeer(onFaceCreated, onFaceCreationFailed);
93  NFD_LOG_CHAN_DEBUG("Started listening");
94 }
95 
96 void
97 UdpChannel::waitForNewPeer(const FaceCreatedCallback& onFaceCreated,
98  const FaceCreationFailedCallback& onReceiveFailed)
99 {
100  m_socket.async_receive_from(boost::asio::buffer(m_receiveBuffer), m_remoteEndpoint, [=] (auto&&... args) {
101  handleNewPeer(std::forward<decltype(args)>(args)..., onFaceCreated, onReceiveFailed);
102  });
103 }
104 
105 void
106 UdpChannel::handleNewPeer(const boost::system::error_code& error,
107  size_t nBytesReceived,
108  const FaceCreatedCallback& onFaceCreated,
109  const FaceCreationFailedCallback& onReceiveFailed)
110 {
111  if (error) {
112  if (error != boost::asio::error::operation_aborted) {
113  NFD_LOG_CHAN_DEBUG("Receive failed: " << error.message());
114  if (onReceiveFailed)
115  onReceiveFailed(500, "Receive failed: " + error.message());
116  }
117  return;
118  }
119 
120  NFD_LOG_CHAN_TRACE("New peer " << m_remoteEndpoint);
121 
122  bool isCreated = false;
123  shared_ptr<Face> face;
124  try {
125  FaceParams params;
126  params.persistency = ndn::nfd::FACE_PERSISTENCY_ON_DEMAND;
127  params.mtu = getDefaultMtu();
128  std::tie(isCreated, face) = createFace(m_remoteEndpoint, params);
129  }
130  catch (const boost::system::system_error& e) {
131  NFD_LOG_CHAN_DEBUG("Face creation for " << m_remoteEndpoint << " failed: " << e.what());
132  if (onReceiveFailed)
133  onReceiveFailed(504, "Face creation failed: "s + e.what());
134  return;
135  }
136 
137  if (isCreated)
138  onFaceCreated(face);
139  else
140  NFD_LOG_CHAN_DEBUG("Received datagram for existing face");
141 
142  // dispatch the datagram to the face for processing
143  auto* transport = static_cast<UnicastUdpTransport*>(face->getTransport());
144  transport->receiveDatagram(ndn::span(m_receiveBuffer).first(nBytesReceived), error);
145 
146  waitForNewPeer(onFaceCreated, onReceiveFailed);
147 }
148 
149 std::pair<bool, shared_ptr<Face>>
150 UdpChannel::createFace(const udp::Endpoint& remoteEndpoint,
151  const FaceParams& params)
152 {
153  auto it = m_channelFaces.find(remoteEndpoint);
154  if (it != m_channelFaces.end()) {
155  // we already have a face for this endpoint, so reuse it
156  NFD_LOG_CHAN_TRACE("Reusing existing face for " << remoteEndpoint);
157  return {false, it->second};
158  }
159 
160  // else, create a new face
161  ip::udp::socket socket(getGlobalIoService(), m_localEndpoint.protocol());
162  socket.set_option(boost::asio::socket_base::reuse_address(true));
163  socket.bind(m_localEndpoint);
164  socket.connect(remoteEndpoint);
165 
167  options.allowFragmentation = true;
168  options.allowReassembly = true;
169  options.reliabilityOptions.isEnabled = params.wantLpReliability;
170 
171  if (boost::logic::indeterminate(params.wantCongestionMarking)) {
172  // Use default value for this channel if parameter is indeterminate
173  options.allowCongestionMarking = m_wantCongestionMarking;
174  }
175  else {
176  options.allowCongestionMarking = bool(params.wantCongestionMarking);
177  }
178 
179  if (params.baseCongestionMarkingInterval) {
180  options.baseCongestionMarkingInterval = *params.baseCongestionMarkingInterval;
181  }
182  if (params.defaultCongestionThreshold) {
183  options.defaultCongestionThreshold = *params.defaultCongestionThreshold;
184  }
185 
186  options.overrideMtu = params.mtu.value_or(getDefaultMtu());
187 
188  auto linkService = make_unique<GenericLinkService>(options);
189  auto transport = make_unique<UnicastUdpTransport>(std::move(socket), params.persistency,
190  m_idleFaceTimeout);
191  auto face = make_shared<Face>(std::move(linkService), std::move(transport));
192  face->setChannel(weak_from_this());
193 
194  m_channelFaces[remoteEndpoint] = face;
195  connectFaceClosedSignal(*face, [this, remoteEndpoint] { m_channelFaces.erase(remoteEndpoint); });
196 
197  return {true, face};
198 }
199 
200 } // namespace nfd::face
void setUri(const FaceUri &uri) noexcept
Definition: channel.cpp:34
size_t getDefaultMtu() const noexcept
Returns the default MTU for all faces created by this channel.
Definition: channel.hpp:58
void setDefaultMtu(size_t mtu) noexcept
Definition: channel.cpp:40
void listen(const FaceCreatedCallback &onFaceCreated, const FaceCreationFailedCallback &onFaceCreationFailed)
Start listening.
Definition: udp-channel.cpp:77
void connect(const udp::Endpoint &remoteEndpoint, const FaceParams &params, const FaceCreatedCallback &onFaceCreated, const FaceCreationFailedCallback &onConnectFailed)
Create a unicast UDP face toward remoteEndpoint.
Definition: udp-channel.cpp:55
UdpChannel(const udp::Endpoint &localEndpoint, time::nanoseconds idleTimeout, bool wantCongestionMarking, size_t defaultMtu)
Create a UDP channel on the given localEndpoint.
Definition: udp-channel.cpp:40
bool isListening() const final
Returns whether the channel is listening.
Definition: udp-channel.hpp:55
#define NFD_LOG_CHAN_DEBUG(msg)
Log a message at DEBUG level.
Definition: channel-log.hpp:49
#define NFD_LOG_CHAN_INFO(msg)
Log a message at INFO level.
Definition: channel-log.hpp:52
#define NFD_LOG_CHAN_WARN(msg)
Log a message at WARN level.
Definition: channel-log.hpp:55
#define NFD_LOG_CHAN_TRACE(msg)
Log a message at TRACE level.
Definition: channel-log.hpp:46
#define NFD_LOG_INIT(name)
Definition: logger.hpp:31
std::function< void(uint32_t status, const std::string &reason)> FaceCreationFailedCallback
Prototype for the callback that is invoked when a face fails to be created.
Definition: channel.hpp:94
std::function< void(const shared_ptr< Face > &)> FaceCreatedCallback
Prototype for the callback that is invoked when a face is created (in response to an incoming connect...
Definition: channel.hpp:90
void connectFaceClosedSignal(Face &face, std::function< void()> f)
Invokes a callback when a face is closed.
Definition: channel.cpp:46
boost::asio::ip::udp::endpoint Endpoint
boost::asio::io_context & getGlobalIoService()
Returns the global io_context instance for the calling thread.
Definition: global.cpp:36
Parameters used to set Transport properties or LinkService options on a newly created face.
Definition: face-common.hpp:87