31 #include <boost/lexical_cast.hpp>
32 #include <boost/range/adaptor/map.hpp>
33 #include <boost/range/algorithm/copy.hpp>
37 namespace ip = boost::asio::ip;
38 namespace net = ndn::net;
46 static std::string id(
"udp");
53 m_netifAddConn =
netmon->onInterfaceAdded.connect([
this] (
const auto& netif) {
54 this->applyMcastConfigToNetif(netif);
87 bool wantListen =
true;
89 bool enableV4 =
false;
90 bool enableV6 =
false;
91 uint32_t idleTimeout = 600;
92 size_t unicastMtu = ndn::MAX_NDN_PACKET_SIZE;
93 MulticastConfig mcastConfig;
97 enableV4 = enableV6 = mcastConfig.isEnabled =
true;
99 for (
const auto& pair : *configSection) {
100 const std::string& key = pair.first;
103 if (key ==
"listen") {
106 else if (key ==
"port") {
107 port = ConfigFile::parseNumber<uint16_t>(pair,
"face_system.udp");
109 else if (key ==
"enable_v4") {
112 else if (key ==
"enable_v6") {
115 else if (key ==
"idle_timeout") {
116 idleTimeout = ConfigFile::parseNumber<uint32_t>(pair,
"face_system.udp");
118 else if (key ==
"unicast_mtu") {
119 unicastMtu = ConfigFile::parseNumber<size_t>(pair,
"face_system.udp");
121 "unicast_mtu",
"face_system.udp");
123 else if (key ==
"keep_alive_interval") {
126 else if (key ==
"mcast") {
129 else if (key ==
"mcast_group") {
130 const std::string& valueStr = value.get_value<std::string>();
131 boost::system::error_code ec;
132 mcastConfig.group.address(ip::address_v4::from_string(valueStr, ec));
134 NDN_THROW(ConfigFile::Error(
"face_system.udp.mcast_group: '" +
135 valueStr +
"' cannot be parsed as an IPv4 address"));
137 else if (!mcastConfig.group.address().is_multicast()) {
138 NDN_THROW(ConfigFile::Error(
"face_system.udp.mcast_group: '" +
139 valueStr +
"' is not a multicast address"));
142 else if (key ==
"mcast_port") {
143 mcastConfig.group.port(ConfigFile::parseNumber<uint16_t>(pair,
"face_system.udp"));
145 else if (key ==
"mcast_group_v6") {
146 const std::string& valueStr = value.get_value<std::string>();
147 boost::system::error_code ec;
148 mcastConfig.groupV6.address(ip::address_v6::from_string(valueStr, ec));
150 NDN_THROW(ConfigFile::Error(
"face_system.udp.mcast_group_v6: '" +
151 valueStr +
"' cannot be parsed as an IPv6 address"));
153 else if (!mcastConfig.groupV6.address().is_multicast()) {
154 NDN_THROW(ConfigFile::Error(
"face_system.udp.mcast_group_v6: '" +
155 valueStr +
"' is not a multicast address"));
158 else if (key ==
"mcast_port_v6") {
159 mcastConfig.groupV6.port(ConfigFile::parseNumber<uint16_t>(pair,
"face_system.udp"));
161 else if (key ==
"mcast_ad_hoc") {
163 mcastConfig.linkType = wantAdHoc ? ndn::nfd::LINK_TYPE_AD_HOC : ndn::nfd::LINK_TYPE_MULTI_ACCESS;
165 else if (key ==
"whitelist") {
166 mcastConfig.netifPredicate.parseWhitelist(value);
168 else if (key ==
"blacklist") {
169 mcastConfig.netifPredicate.parseBlacklist(value);
172 NDN_THROW(ConfigFile::Error(
"Unrecognized option face_system.udp." + key));
176 if (!enableV4 && !enableV6 && !mcastConfig.isEnabled) {
177 NDN_THROW(ConfigFile::Error(
178 "IPv4 and IPv6 UDP channels and UDP multicast have been disabled. "
179 "Remove face_system.udp section to disable UDP channels or enable at least one of them."));
187 m_defaultUnicastMtu = unicastMtu;
191 shared_ptr<UdpChannel> v4Channel = this->
createChannel(endpoint, time::seconds(idleTimeout));
192 if (wantListen && !v4Channel->isListening()) {
193 v4Channel->listen(this->
addFace,
nullptr);
199 NFD_LOG_WARN(
"Cannot close udp4 channel after its creation");
204 shared_ptr<UdpChannel> v6Channel = this->
createChannel(endpoint, time::seconds(idleTimeout));
205 if (wantListen && !v6Channel->isListening()) {
206 v6Channel->listen(this->
addFace,
nullptr);
212 NFD_LOG_WARN(
"Cannot close udp6 channel after its creation");
215 if (m_mcastConfig.isEnabled != mcastConfig.isEnabled) {
216 if (mcastConfig.isEnabled) {
217 NFD_LOG_INFO(
"enabling multicast on " << mcastConfig.group);
218 NFD_LOG_INFO(
"enabling multicast on " << mcastConfig.groupV6);
224 else if (mcastConfig.isEnabled) {
225 if (m_mcastConfig.linkType != mcastConfig.linkType && !m_mcastFaces.empty()) {
226 NFD_LOG_WARN(
"Cannot change ad hoc setting on existing faces");
228 if (m_mcastConfig.group != mcastConfig.group) {
229 NFD_LOG_INFO(
"changing IPv4 multicast group from " << m_mcastConfig.group <<
230 " to " << mcastConfig.group);
232 if (m_mcastConfig.groupV6 != mcastConfig.groupV6) {
233 NFD_LOG_INFO(
"changing IPv6 multicast group from " << m_mcastConfig.groupV6 <<
234 " to " << mcastConfig.groupV6);
236 if (m_mcastConfig.netifPredicate != mcastConfig.netifPredicate) {
243 m_mcastConfig = mcastConfig;
244 this->applyMcastConfig(context);
248 UdpFactory::doCreateFace(
const CreateFaceRequest& req,
253 NFD_LOG_TRACE(
"Cannot create unicast UDP face with LocalUri");
254 onFailure(406,
"Unicast UDP faces cannot be created with a LocalUri");
258 if (req.params.persistency == ndn::nfd::FACE_PERSISTENCY_ON_DEMAND) {
259 NFD_LOG_TRACE(
"createFace does not support FACE_PERSISTENCY_ON_DEMAND");
260 onFailure(406,
"Outgoing UDP faces do not support on-demand persistency");
264 udp::Endpoint endpoint(ip::address::from_string(req.remoteUri.getHost()),
265 boost::lexical_cast<uint16_t>(req.remoteUri.getPort()));
267 if (endpoint.address().is_multicast()) {
268 NFD_LOG_TRACE(
"createFace does not support multicast faces");
269 onFailure(406,
"Cannot create multicast UDP faces");
273 if (req.params.wantLocalFields) {
275 NFD_LOG_TRACE(
"createFace cannot create non-local face with local fields enabled");
276 onFailure(406,
"Local fields can only be enabled on faces with local scope");
280 if (req.params.mtu && *req.params.mtu <
MIN_MTU) {
283 onFailure(406,
"Override MTU cannot be less than " + to_string(
MIN_MTU));
288 for (
const auto& i : m_channels) {
289 if ((i.first.address().is_v4() && endpoint.address().is_v4()) ||
290 (i.first.address().is_v6() && endpoint.address().is_v6())) {
291 i.second->connect(endpoint, req.params, onCreated, onFailure);
296 NFD_LOG_TRACE(
"No channels available to connect to " << endpoint);
297 onFailure(504,
"No channels available to connect");
300 shared_ptr<UdpChannel>
302 time::nanoseconds idleTimeout)
304 auto it = m_channels.find(localEndpoint);
305 if (it != m_channels.end())
309 if (m_mcastFaces.find(localEndpoint) != m_mcastFaces.end()) {
310 NDN_THROW(
Error(
"Cannot create UDP channel on " + boost::lexical_cast<std::string>(localEndpoint) +
311 ", endpoint already allocated to a UDP multicast face"));
314 auto channel = std::make_shared<UdpChannel>(localEndpoint, idleTimeout,
315 m_wantCongestionMarking, m_defaultUnicastMtu);
316 m_channels[localEndpoint] = channel;
320 std::vector<shared_ptr<const Channel>>
321 UdpFactory::doGetChannels()
const
328 const ip::address& localAddress,
331 BOOST_ASSERT(multicastEndpoint.address().is_multicast());
333 udp::Endpoint localEp(localAddress, multicastEndpoint.port());
334 BOOST_ASSERT(localEp.protocol() == multicastEndpoint.protocol());
336 auto mcastEp = multicastEndpoint;
337 if (mcastEp.address().is_v6()) {
339 auto mcastAddress = mcastEp.address().to_v6();
340 mcastAddress.scope_id(netif.getIndex());
341 mcastEp.address(mcastAddress);
345 auto it = m_mcastFaces.find(localEp);
346 if (it != m_mcastFaces.end()) {
347 if (it->second->getRemoteUri() == FaceUri(mcastEp))
350 NDN_THROW(
Error(
"Cannot create UDP multicast face on " + boost::lexical_cast<std::string>(localEp) +
351 ", endpoint already allocated to a different UDP multicast face"));
355 if (m_channels.find(localEp) != m_channels.end()) {
356 NDN_THROW(
Error(
"Cannot create UDP multicast face on " + boost::lexical_cast<std::string>(localEp) +
357 ", endpoint already allocated to a UDP channel"));
367 auto linkService = make_unique<GenericLinkService>(options);
368 auto transport = make_unique<MulticastUdpTransport>(mcastEp, std::move(rxSock), std::move(txSock),
369 m_mcastConfig.linkType);
370 auto face = make_shared<Face>(std::move(linkService), std::move(transport));
372 m_mcastFaces[localEp] = face;
376 auto channelIt = std::find_if(m_channels.begin(), m_channels.end(),
377 [isV4 = localEp.address().is_v4()] (
const auto& it) {
378 return it.first.address().is_v4() == isV4;
380 face->setChannel(channelIt != m_channels.end() ? channelIt->second :
nullptr);
385 static std::optional<ip::address>
386 pickAddress(
const net::NetworkInterface& netif, net::AddressFamily af)
388 for (
const auto& na : netif.getNetworkAddresses()) {
389 if (na.getFamily() == af &&
390 (na.getScope() == net::AddressScope::LINK || na.getScope() == net::AddressScope::GLOBAL)) {
397 std::vector<shared_ptr<Face>>
398 UdpFactory::applyMcastConfigToNetif(
const shared_ptr<const net::NetworkInterface>& netif)
400 BOOST_ASSERT(netif !=
nullptr);
402 if (!m_mcastConfig.isEnabled) {
406 if (!netif->isUp()) {
407 NFD_LOG_DEBUG(
"Not creating multicast faces on " << netif->getName() <<
": netif is down");
411 if (netif->isLoopback()) {
412 NFD_LOG_DEBUG(
"Not creating multicast faces on " << netif->getName() <<
": netif is loopback");
416 if (!netif->canMulticast()) {
417 NFD_LOG_DEBUG(
"Not creating multicast faces on " << netif->getName() <<
": netif cannot multicast");
421 if (!m_mcastConfig.netifPredicate(*netif)) {
422 NFD_LOG_DEBUG(
"Not creating multicast faces on " << netif->getName() <<
": rejected by whitelist/blacklist");
426 std::vector<ip::address> addrs;
427 for (
auto af : {net::AddressFamily::V4, net::AddressFamily::V6}) {
430 addrs.push_back(*addr);
434 NFD_LOG_DEBUG(
"Not creating multicast faces on " << netif->getName() <<
": no viable IP address");
436 m_netifConns[netif->getIndex()].addrAddConn =
437 netif->onAddressAdded.connect([=] (
auto&&...) { this->applyMcastConfigToNetif(netif); });
441 NFD_LOG_DEBUG(
"Creating multicast faces on " << netif->getName());
443 std::vector<shared_ptr<Face>> faces;
444 for (
const auto& addr : addrs) {
446 addr.is_v4() ? m_mcastConfig.group : m_mcastConfig.groupV6);
451 faces.push_back(std::move(face));
458 UdpFactory::applyMcastConfig(
const FaceSystem::ConfigContext&)
461 std::set<shared_ptr<Face>> facesToClose;
462 boost::copy(m_mcastFaces | boost::adaptors::map_values,
463 std::inserter(facesToClose, facesToClose.end()));
466 for (
const auto& netif :
netmon->listNetworkInterfaces()) {
467 auto facesToKeep = this->applyMcastConfigToNetif(netif);
468 for (
const auto& face : facesToKeep) {
470 facesToClose.erase(face);
475 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
Options that control the behavior of GenericLinkService.
bool allowCongestionMarking
Enables send queue congestion detection and marking.
static void openRxSocket(protocol::socket &sock, const protocol::endpoint &multicastGroup, const boost::asio::ip::address &localAddress={}, const ndn::net::NetworkInterface *netif=nullptr)
Opens and configures the receive-side socket.
static void openTxSocket(protocol::socket &sock, const protocol::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_service & getGlobalIoService()
Returns the global io_service instance for the calling thread.
#define NFD_REGISTER_PROTOCOL_FACTORY(PF)
Registers a protocol factory.
bool wantCongestionMarking
Parameters to ProtocolFactory constructor.