31 #include <boost/container/static_vector.hpp>
32 #include <boost/lexical_cast.hpp>
33 #include <boost/range/adaptor/map.hpp>
34 #include <boost/range/algorithm/copy.hpp>
38 namespace ip = boost::asio::ip;
39 namespace net = ndn::net;
47 static std::string id(
"udp");
54 m_netifAddConn =
netmon->onInterfaceAdded.connect([
this] (
const auto& netif) {
55 applyMcastConfigToNetif(netif);
88 bool wantListen =
true;
90 bool enableV4 =
false;
91 bool enableV6 =
false;
92 uint32_t idleTimeout = 600;
93 size_t unicastMtu = ndn::MAX_NDN_PACKET_SIZE;
94 MulticastConfig mcastConfig;
98 enableV4 = enableV6 = mcastConfig.isEnabled =
true;
100 for (
const auto& pair : *configSection) {
101 const std::string& key = pair.first;
104 if (key ==
"listen") {
107 else if (key ==
"port") {
108 port = ConfigFile::parseNumber<uint16_t>(pair,
"face_system.udp");
110 else if (key ==
"enable_v4") {
113 else if (key ==
"enable_v6") {
116 else if (key ==
"idle_timeout") {
117 idleTimeout = ConfigFile::parseNumber<uint32_t>(pair,
"face_system.udp");
119 else if (key ==
"unicast_mtu") {
120 unicastMtu = ConfigFile::parseNumber<size_t>(pair,
"face_system.udp");
122 "unicast_mtu",
"face_system.udp");
124 else if (key ==
"keep_alive_interval") {
127 else if (key ==
"mcast") {
130 else if (key ==
"mcast_group") {
131 const std::string& valueStr = value.get_value<std::string>();
132 boost::system::error_code ec;
133 mcastConfig.group.address(ip::make_address_v4(valueStr, ec));
135 NDN_THROW(ConfigFile::Error(
"face_system.udp.mcast_group: '" +
136 valueStr +
"' cannot be parsed as an IPv4 address"));
138 else if (!mcastConfig.group.address().is_multicast()) {
139 NDN_THROW(ConfigFile::Error(
"face_system.udp.mcast_group: '" +
140 valueStr +
"' is not a multicast address"));
143 else if (key ==
"mcast_port") {
144 mcastConfig.group.port(ConfigFile::parseNumber<uint16_t>(pair,
"face_system.udp"));
146 else if (key ==
"mcast_group_v6") {
147 const std::string& valueStr = value.get_value<std::string>();
148 boost::system::error_code ec;
149 mcastConfig.groupV6.address(ip::make_address_v6(valueStr, ec));
151 NDN_THROW(ConfigFile::Error(
"face_system.udp.mcast_group_v6: '" +
152 valueStr +
"' cannot be parsed as an IPv6 address"));
154 else if (!mcastConfig.groupV6.address().is_multicast()) {
155 NDN_THROW(ConfigFile::Error(
"face_system.udp.mcast_group_v6: '" +
156 valueStr +
"' is not a multicast address"));
159 else if (key ==
"mcast_port_v6") {
160 mcastConfig.groupV6.port(ConfigFile::parseNumber<uint16_t>(pair,
"face_system.udp"));
162 else if (key ==
"mcast_ad_hoc") {
164 mcastConfig.linkType = wantAdHoc ? ndn::nfd::LINK_TYPE_AD_HOC : ndn::nfd::LINK_TYPE_MULTI_ACCESS;
166 else if (key ==
"whitelist") {
167 mcastConfig.netifPredicate.parseWhitelist(value);
169 else if (key ==
"blacklist") {
170 mcastConfig.netifPredicate.parseBlacklist(value);
173 NDN_THROW(ConfigFile::Error(
"Unrecognized option face_system.udp." + key));
177 if (!enableV4 && !enableV6 && !mcastConfig.isEnabled) {
178 NDN_THROW(ConfigFile::Error(
179 "IPv4 and IPv6 UDP channels and UDP multicast have been disabled. "
180 "Remove face_system.udp section to disable UDP channels or enable at least one of them."));
188 m_defaultUnicastMtu = unicastMtu;
192 shared_ptr<UdpChannel> v4Channel = this->
createChannel(endpoint, time::seconds(idleTimeout));
193 if (wantListen && !v4Channel->isListening()) {
194 v4Channel->listen(this->
addFace,
nullptr);
200 NFD_LOG_WARN(
"Cannot close UDP channel after its creation");
205 shared_ptr<UdpChannel> v6Channel = this->
createChannel(endpoint, time::seconds(idleTimeout));
206 if (wantListen && !v6Channel->isListening()) {
207 v6Channel->listen(this->
addFace,
nullptr);
213 NFD_LOG_WARN(
"Cannot close UDP channel after its creation");
216 if (m_mcastConfig.isEnabled != mcastConfig.isEnabled) {
217 if (mcastConfig.isEnabled) {
218 NFD_LOG_INFO(
"enabling multicast on " << mcastConfig.group);
219 NFD_LOG_INFO(
"enabling multicast on " << mcastConfig.groupV6);
225 else if (mcastConfig.isEnabled) {
226 if (m_mcastConfig.linkType != mcastConfig.linkType && !m_mcastFaces.empty()) {
227 NFD_LOG_WARN(
"Cannot change ad hoc setting on existing faces");
229 if (m_mcastConfig.group != mcastConfig.group) {
230 NFD_LOG_INFO(
"changing IPv4 multicast group from " << m_mcastConfig.group <<
231 " to " << mcastConfig.group);
233 if (m_mcastConfig.groupV6 != mcastConfig.groupV6) {
234 NFD_LOG_INFO(
"changing IPv6 multicast group from " << m_mcastConfig.groupV6 <<
235 " to " << mcastConfig.groupV6);
237 if (m_mcastConfig.netifPredicate != mcastConfig.netifPredicate) {
244 m_mcastConfig = std::move(mcastConfig);
245 applyMcastConfig(context);
249 UdpFactory::doCreateFace(
const CreateFaceRequest& req,
255 onFailure(406,
"Unicast UDP faces cannot be created with a LocalUri");
259 if (req.params.persistency == ndn::nfd::FACE_PERSISTENCY_ON_DEMAND) {
261 onFailure(406,
"Outgoing UDP faces do not support on-demand persistency");
265 udp::Endpoint endpoint(ip::make_address(req.remoteUri.getHost()),
266 boost::lexical_cast<uint16_t>(req.remoteUri.getPort()));
268 if (endpoint.address().is_multicast()) {
270 onFailure(406,
"Cannot create multicast UDP faces");
274 if (req.params.wantLocalFields) {
276 NFD_LOG_TRACE(
"createFace: cannot create non-local face with local fields enabled");
277 onFailure(406,
"Local fields can only be enabled on faces with local scope");
281 if (req.params.mtu && *req.params.mtu <
MIN_MTU) {
284 onFailure(406,
"Override MTU cannot be less than " + std::to_string(
MIN_MTU));
289 for (
const auto& i : m_channels) {
290 if ((i.first.address().is_v4() && endpoint.address().is_v4()) ||
291 (i.first.address().is_v6() && endpoint.address().is_v6())) {
292 i.second->connect(endpoint, req.params, onCreated, onFailure);
297 NFD_LOG_TRACE(
"No channels available to connect to " << endpoint);
298 onFailure(504,
"No channels available to connect");
301 shared_ptr<UdpChannel>
303 time::nanoseconds idleTimeout)
305 auto it = m_channels.find(localEndpoint);
306 if (it != m_channels.end())
310 if (m_mcastFaces.find(localEndpoint) != m_mcastFaces.end()) {
311 NDN_THROW(
Error(
"Cannot create UDP channel on " + boost::lexical_cast<std::string>(localEndpoint) +
312 ", endpoint already allocated to a UDP multicast face"));
315 auto channel = std::make_shared<UdpChannel>(localEndpoint, idleTimeout,
316 m_wantCongestionMarking, m_defaultUnicastMtu);
317 m_channels[localEndpoint] = channel;
321 std::vector<shared_ptr<const Channel>>
322 UdpFactory::doGetChannels()
const
329 const ip::address& localAddress,
332 BOOST_ASSERT(multicastEndpoint.address().is_multicast());
334 udp::Endpoint localEp(localAddress, multicastEndpoint.port());
335 BOOST_ASSERT(localEp.protocol() == multicastEndpoint.protocol());
337 auto mcastEp = multicastEndpoint;
338 if (mcastEp.address().is_v6()) {
340 auto mcastAddress = mcastEp.address().to_v6();
341 mcastAddress.scope_id(netif.getIndex());
342 mcastEp.address(mcastAddress);
346 auto it = m_mcastFaces.find(localEp);
347 if (it != m_mcastFaces.end()) {
348 if (it->second->getRemoteUri() == FaceUri(mcastEp))
351 NDN_THROW(
Error(
"Cannot create UDP multicast face on " + boost::lexical_cast<std::string>(localEp) +
352 ", endpoint already allocated to a different UDP multicast face"));
356 if (m_channels.find(localEp) != m_channels.end()) {
357 NDN_THROW(
Error(
"Cannot create UDP multicast face on " + boost::lexical_cast<std::string>(localEp) +
358 ", endpoint already allocated to a UDP channel"));
368 auto linkService = make_unique<GenericLinkService>(options);
369 auto transport = make_unique<MulticastUdpTransport>(mcastEp, std::move(rxSock), std::move(txSock),
370 m_mcastConfig.linkType);
371 auto face = make_shared<Face>(std::move(linkService), std::move(transport));
373 m_mcastFaces[localEp] = face;
377 auto channelIt = std::find_if(m_channels.begin(), m_channels.end(),
378 [isV4 = localEp.address().is_v4()] (
const auto& it) {
379 return it.first.address().is_v4() == isV4;
381 if (channelIt != m_channels.end()) {
382 face->setChannel(channelIt->second);
388 static std::optional<ip::address>
389 pickAddress(
const net::NetworkInterface& netif, net::AddressFamily af)
391 for (
const auto& na : netif.getNetworkAddresses()) {
392 if (na.getFamily() == af &&
393 (na.getScope() == net::AddressScope::LINK || na.getScope() == net::AddressScope::GLOBAL)) {
400 std::vector<shared_ptr<Face>>
401 UdpFactory::applyMcastConfigToNetif(
const shared_ptr<const net::NetworkInterface>& netif)
403 BOOST_ASSERT(netif !=
nullptr);
405 if (!m_mcastConfig.isEnabled) {
409 if (!netif->isUp()) {
410 NFD_LOG_DEBUG(
"Not creating multicast faces on " << netif->getName() <<
": netif is down");
414 if (netif->isLoopback()) {
415 NFD_LOG_DEBUG(
"Not creating multicast faces on " << netif->getName() <<
": netif is loopback");
419 if (!netif->canMulticast()) {
420 NFD_LOG_DEBUG(
"Not creating multicast faces on " << netif->getName() <<
": netif cannot multicast");
424 if (!m_mcastConfig.netifPredicate(*netif)) {
425 NFD_LOG_DEBUG(
"Not creating multicast faces on " << netif->getName() <<
": rejected by whitelist/blacklist");
429 boost::container::static_vector<ip::address, 2> addrs;
430 for (
auto af : {net::AddressFamily::V4, net::AddressFamily::V6}) {
433 addrs.push_back(*addr);
437 NFD_LOG_DEBUG(
"Not creating multicast faces on " << netif->getName() <<
": no viable IP address");
439 m_netifConns[netif->getIndex()].addrAddConn =
440 netif->onAddressAdded.connect([=] (
auto&&...) { applyMcastConfigToNetif(netif); });
444 NFD_LOG_DEBUG(
"Creating multicast faces on " << netif->getName());
446 std::vector<shared_ptr<Face>> faces;
447 for (
const auto& addr : addrs) {
448 shared_ptr<Face> face;
450 face =
createMulticastFace(*netif, addr, addr.is_v4() ? m_mcastConfig.group : m_mcastConfig.groupV6);
452 catch (
const std::runtime_error& e) {
453 NFD_LOG_WARN(
"Cannot create multicast face on " << addr <<
": " << e.what());
460 faces.push_back(std::move(face));
467 UdpFactory::applyMcastConfig(
const FaceSystem::ConfigContext&)
470 std::set<shared_ptr<Face>> facesToClose;
471 boost::copy(m_mcastFaces | boost::adaptors::map_values,
472 std::inserter(facesToClose, facesToClose.end()));
475 for (
const auto& netif :
netmon->listNetworkInterfaces()) {
476 auto facesToKeep = applyMcastConfigToNetif(netif);
477 for (
const auto& face : facesToKeep) {
479 facesToClose.erase(face);
484 for (
const auto& face : facesToClose) {
static void checkRange(T value, T min, T max, const std::string &key, const std::string §ionName)
Check that a value is within the inclusive range [min, max].
static bool parseYesNo(const ConfigSection &node, const std::string &key, const std::string §ionName)
Parse a config option that can be either "yes" or "no".
Context for processing a config section in ProtocolFactory.
GeneralConfig generalConfig
static void openRxSocket(boost::asio::ip::udp::socket &sock, const boost::asio::ip::udp::endpoint &multicastGroup, const boost::asio::ip::address &localAddress={}, const ndn::net::NetworkInterface *netif=nullptr)
Opens and configures the receive-side socket.
static void openTxSocket(boost::asio::ip::udp::socket &sock, const boost::asio::ip::udp::endpoint &localEndpoint, const ndn::net::NetworkInterface *netif=nullptr, bool enableLoopback=false)
Opens and configures the transmit-side socket.
Provides support for an underlying protocol.
static std::vector< shared_ptr< const Channel > > getChannelsFromMap(const ChannelMap &channelMap)
std::set< std::string > providedSchemes
FaceUri schemes provided by this protocol factory.
FaceCreatedCallback addFace
callback when a new face is created
shared_ptr< ndn::net::NetworkMonitor > netmon
NetworkMonitor for listing available network interfaces and monitoring their changes.
Protocol factory for UDP over IPv4 and IPv6.
shared_ptr< Face > createMulticastFace(const ndn::net::NetworkInterface &netif, const boost::asio::ip::address &localAddress, const udp::Endpoint &multicastEndpoint)
Create a multicast UDP face.
UdpFactory(const CtorParams ¶ms)
static const std::string & getId() noexcept
shared_ptr< UdpChannel > createChannel(const udp::Endpoint &localEndpoint, time::nanoseconds idleTimeout)
Create UDP-based channel using udp::Endpoint.
#define NFD_LOG_INIT(name)
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.
constexpr FaceId INVALID_FACEID
Indicates an invalid FaceId.
static std::optional< ip::address > pickAddress(const net::NetworkInterface &netif, net::AddressFamily af)
constexpr ssize_t MIN_MTU
Minimum MTU that may be set.
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...
void connectFaceClosedSignal(Face &face, std::function< void()> f)
Invokes a callback when a face is closed.
boost::asio::ip::udp::endpoint Endpoint
boost::optional< const ConfigSection & > OptionalConfigSection
An optional configuration file section.
boost::property_tree::ptree ConfigSection
A configuration file section.
boost::asio::io_context & getGlobalIoService()
Returns the global io_context instance for the calling thread.
#define NFD_REGISTER_PROTOCOL_FACTORY(PF)
Registers a protocol factory.
bool wantCongestionMarking
Options that control the behavior of GenericLinkService.
bool allowCongestionMarking
Enables send queue congestion detection and marking.
Parameters to ProtocolFactory constructor.