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-2022, 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 NFD_LOG_INIT(UdpChannel);
37 
38 namespace ip = boost::asio::ip;
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(ip::udp::socket::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,
101  [=] (auto&&... args) {
102  this->handleNewPeer(std::forward<decltype(args)>(args)..., onFaceCreated, onReceiveFailed);
103  });
104 }
105 
106 void
107 UdpChannel::handleNewPeer(const boost::system::error_code& error,
108  size_t nBytesReceived,
109  const FaceCreatedCallback& onFaceCreated,
110  const FaceCreationFailedCallback& onReceiveFailed)
111 {
112  if (error) {
113  if (error != boost::asio::error::operation_aborted) {
114  NFD_LOG_CHAN_DEBUG("Receive failed: " << error.message());
115  if (onReceiveFailed)
116  onReceiveFailed(500, "Receive failed: " + error.message());
117  }
118  return;
119  }
120 
121  NFD_LOG_CHAN_TRACE("New peer " << m_remoteEndpoint);
122 
123  bool isCreated = false;
124  shared_ptr<Face> face;
125  try {
126  FaceParams params;
127  params.persistency = ndn::nfd::FACE_PERSISTENCY_ON_DEMAND;
128  params.mtu = getDefaultMtu();
129  std::tie(isCreated, face) = createFace(m_remoteEndpoint, params);
130  }
131  catch (const boost::system::system_error& e) {
132  NFD_LOG_CHAN_DEBUG("Face creation for " << m_remoteEndpoint << " failed: " << e.what());
133  if (onReceiveFailed)
134  onReceiveFailed(504, "Face creation failed: "s + e.what());
135  return;
136  }
137 
138  if (isCreated)
139  onFaceCreated(face);
140  else
141  NFD_LOG_CHAN_DEBUG("Received datagram for existing face");
142 
143  // dispatch the datagram to the face for processing
144  auto* transport = static_cast<UnicastUdpTransport*>(face->getTransport());
145  transport->receiveDatagram(ndn::make_span(m_receiveBuffer).first(nBytesReceived), error);
146 
147  waitForNewPeer(onFaceCreated, onReceiveFailed);
148 }
149 
150 std::pair<bool, shared_ptr<Face>>
151 UdpChannel::createFace(const udp::Endpoint& remoteEndpoint,
152  const FaceParams& params)
153 {
154  auto it = m_channelFaces.find(remoteEndpoint);
155  if (it != m_channelFaces.end()) {
156  // we already have a face for this endpoint, so reuse it
157  NFD_LOG_CHAN_TRACE("Reusing existing face for " << remoteEndpoint);
158  return {false, it->second};
159  }
160 
161  // else, create a new face
162  ip::udp::socket socket(getGlobalIoService(), m_localEndpoint.protocol());
163  socket.set_option(ip::udp::socket::reuse_address(true));
164  socket.bind(m_localEndpoint);
165  socket.connect(remoteEndpoint);
166 
167  GenericLinkService::Options options;
168  options.allowFragmentation = true;
169  options.allowReassembly = true;
170  options.reliabilityOptions.isEnabled = params.wantLpReliability;
171 
172  if (boost::logic::indeterminate(params.wantCongestionMarking)) {
173  // Use default value for this channel if parameter is indeterminate
174  options.allowCongestionMarking = m_wantCongestionMarking;
175  }
176  else {
177  options.allowCongestionMarking = bool(params.wantCongestionMarking);
178  }
179 
180  if (params.baseCongestionMarkingInterval) {
181  options.baseCongestionMarkingInterval = *params.baseCongestionMarkingInterval;
182  }
183  if (params.defaultCongestionThreshold) {
184  options.defaultCongestionThreshold = *params.defaultCongestionThreshold;
185  }
186 
187  options.overrideMtu = params.mtu.value_or(getDefaultMtu());
188 
189  auto linkService = make_unique<GenericLinkService>(options);
190  auto transport = make_unique<UnicastUdpTransport>(std::move(socket), params.persistency,
191  m_idleFaceTimeout);
192  auto face = make_shared<Face>(std::move(linkService), std::move(transport));
193  face->setChannel(weak_from_this());
194 
195  m_channelFaces[remoteEndpoint] = face;
196  connectFaceClosedSignal(*face, [this, remoteEndpoint] { m_channelFaces.erase(remoteEndpoint); });
197 
198  return {true, face};
199 }
200 
201 } // 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:56
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:92
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:88
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_service & getGlobalIoService()
Returns the global io_service 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:85