NS-3 based Named Data Networking (NDN) simulator
ndnSIM 2.5: NDN, CCN, CCNx, content centric networks
API Documentation
network-monitor-impl-osx.cpp
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright (c) 2013-2019 Regents of the University of California.
4  *
5  * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
6  *
7  * ndn-cxx library is free software: you can redistribute it and/or modify it under the
8  * terms of the GNU Lesser General Public License as published by the Free Software
9  * Foundation, either version 3 of the License, or (at your option) any later version.
10  *
11  * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
12  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
13  * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
14  *
15  * You should have received copies of the GNU General Public License and GNU Lesser
16  * General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see
17  * <http://www.gnu.org/licenses/>.
18  *
19  * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
20  *
21  *
22  * Parts of this implementation is based on daemondo command of MacPorts
23  * (https://www.macports.org/):
24  *
25  * Copyright (c) 2005-2007 James Berry <jberry@macports.org>
26  * All rights reserved.
27  *
28  * Redistribution and use in source and binary forms, with or without
29  * modification, are permitted provided that the following conditions
30  * are met:
31  * 1. Redistributions of source code must retain the above copyright
32  * notice, this list of conditions and the following disclaimer.
33  * 2. Redistributions in binary form must reproduce the above copyright
34  * notice, this list of conditions and the following disclaimer in the
35  * documentation and/or other materials provided with the distribution.
36  * 3. Neither the name of The MacPorts Project nor the names of its contributors
37  * may be used to endorse or promote products derived from this software
38  * without specific prior written permission.
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
41  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
44  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
45  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
46  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
47  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
48  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
50  * POSSIBILITY OF SUCH DAMAGE.
51  */
52 
54 #include "ndn-cxx/name.hpp"
57 #include "ndn-cxx/util/logger.hpp"
58 
59 #include <ifaddrs.h> // for getifaddrs()
60 #include <net/if.h> // for if_nametoindex()
61 #include <net/if_dl.h> // for struct sockaddr_dl
62 #include <net/if_types.h> // for IFT_* constants
63 #include <netinet/in.h> // for struct sockaddr_in{,6}
64 
65 #include <boost/asio/io_service.hpp>
66 #include <boost/asio/ip/address.hpp>
67 #include <boost/asio/ip/udp.hpp>
68 #include <boost/range/adaptor/map.hpp>
69 #include <boost/range/algorithm_ext/push_back.hpp>
70 
71 NDN_LOG_INIT(ndn.NetworkMonitor);
72 
73 namespace ndn {
74 namespace net {
75 
76 using detail::CFReleaser;
77 
78 class IfAddrs : noncopyable
79 {
80 public:
82  {
83  if (::getifaddrs(&m_ifaList) < 0) {
84  NDN_THROW_ERRNO(NetworkMonitorImplOsx::Error("getifaddrs() failed"));
85  }
86  }
87 
89  {
90  if (m_ifaList != nullptr) {
91  ::freeifaddrs(m_ifaList);
92  }
93  }
94 
95  ifaddrs*
96  get() const noexcept
97  {
98  return m_ifaList;
99  }
100 
101 private:
102  ifaddrs* m_ifaList = nullptr;
103 };
104 
106  : m_scheduler(io)
107  , m_context{0, this, nullptr, nullptr, nullptr}
108  , m_scStore(SCDynamicStoreCreate(nullptr, CFSTR("net.named-data.ndn-cxx.NetworkMonitor"),
109  &NetworkMonitorImplOsx::onConfigChanged, &m_context))
110  , m_loopSource(SCDynamicStoreCreateRunLoopSource(nullptr, m_scStore.get(), 0))
111  , m_ioctlSocket(io, boost::asio::ip::udp::v4())
112 {
113  scheduleCfLoop();
114 
115  // Notifications from Darwin Notify Center:
116  //
117  // com.apple.system.config.network_change
118  //
119  CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
120  static_cast<void*>(this),
121  &NetworkMonitorImplOsx::afterNotificationCenterEvent,
122  CFSTR("com.apple.system.config.network_change"),
123  nullptr, // object to observe
124  CFNotificationSuspensionBehaviorDeliverImmediately);
125 
126  CFRunLoopAddSource(CFRunLoopGetCurrent(), m_loopSource.get(), kCFRunLoopDefaultMode);
127 
128  // Notifications from SystemConfiguration:
129  //
130  // State:/Network/Interface/.*/Link
131  // State:/Network/Interface/.*/IPv4
132  // State:/Network/Interface/.*/IPv6
133  // State:/Network/Interface/.*/AirPort (not used)
134  //
135  // https://developer.apple.com/library/content/documentation/Networking/Conceptual/SystemConfigFrameworks/SC_UnderstandSchema/SC_UnderstandSchema.html
136  //
137  auto patterns = CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
138  CFArrayAppendValue(patterns, CFSTR("State:/Network/Interface/.*/Link"));
139  CFArrayAppendValue(patterns, CFSTR("State:/Network/Interface/.*/IPv4"));
140  CFArrayAppendValue(patterns, CFSTR("State:/Network/Interface/.*/IPv6"));
141 
142  if (!SCDynamicStoreSetNotificationKeys(m_scStore.get(), nullptr, patterns)) {
143  NDN_THROW(Error("SCDynamicStoreSetNotificationKeys failed"));
144  }
145 
146  io.post([this] { enumerateInterfaces(); });
147 }
148 
150 {
151  CFRunLoopRemoveSource(CFRunLoopGetCurrent(), m_loopSource.get(), kCFRunLoopDefaultMode);
152 
153  CFNotificationCenterRemoveEveryObserver(CFNotificationCenterGetDarwinNotifyCenter(),
154  static_cast<void*>(this));
155 }
156 
157 shared_ptr<const NetworkInterface>
158 NetworkMonitorImplOsx::getNetworkInterface(const std::string& ifname) const
159 {
160  auto it = m_interfaces.find(ifname);
161  return it == m_interfaces.end() ? nullptr : it->second;
162 }
163 
164 std::vector<shared_ptr<const NetworkInterface>>
166 {
167  std::vector<shared_ptr<const NetworkInterface>> v;
168  v.reserve(m_interfaces.size());
169  boost::push_back(v, m_interfaces | boost::adaptors::map_values);
170  return v;
171 }
172 
173 void
174 NetworkMonitorImplOsx::afterNotificationCenterEvent(CFNotificationCenterRef center,
175  void* observer,
176  CFStringRef name,
177  const void* object,
178  CFDictionaryRef userInfo)
179 {
180  static_cast<NetworkMonitorImplOsx*>(observer)->emitSignal(onNetworkStateChanged);
181 }
182 
183 void
184 NetworkMonitorImplOsx::scheduleCfLoop()
185 {
186  // poll each second for new events
187  m_cfLoopEvent = m_scheduler.schedule(1_s, [this] {
188  // this should dispatch ready events and exit
189  CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, true);
190  scheduleCfLoop();
191  });
192 }
193 
194 void
195 NetworkMonitorImplOsx::enumerateInterfaces()
196 {
197  IfAddrs ifaList;
198  for (const auto& ifName : getInterfaceNames()) {
199  addNewInterface(ifName, ifaList);
200  }
202 }
203 
204 std::set<std::string>
205 NetworkMonitorImplOsx::getInterfaceNames() const
206 {
208  (CFDictionaryRef)SCDynamicStoreCopyValue(m_scStore.get(), CFSTR("State:/Network/Interface"));
209  if (dict.get() == nullptr) {
210  return {};
211  }
212 
213  CFArrayRef interfaces = (CFArrayRef)CFDictionaryGetValue(dict.get(), CFSTR("Interfaces"));
214  if (interfaces == nullptr) {
215  return {};
216  }
217 
218  std::set<std::string> ifNames;
219  size_t count = CFArrayGetCount(interfaces);
220  for (size_t i = 0; i != count; ++i) {
221  auto ifName = (CFStringRef)CFArrayGetValueAtIndex(interfaces, i);
222  ifNames.insert(detail::cfstring::toStdString(ifName));
223  }
224  return ifNames;
225 }
226 
227 void
228 NetworkMonitorImplOsx::addNewInterface(const std::string& ifName, const IfAddrs& ifaList)
229 {
230  shared_ptr<NetworkInterface> interface = makeNetworkInterface();
231  interface->setName(ifName);
232  interface->setState(getInterfaceState(*interface));
233  updateInterfaceInfo(*interface, ifaList);
234 
235  if (interface->getType() == InterfaceType::UNKNOWN) {
236  NDN_LOG_DEBUG("ignoring " << ifName << " due to unhandled interface type");
237  return;
238  }
239 
240  NDN_LOG_DEBUG("adding interface " << interface->getName());
241  m_interfaces[interface->getName()] = interface;
242  this->emitSignal(onInterfaceAdded, interface);
243 }
244 
246 NetworkMonitorImplOsx::getInterfaceState(const NetworkInterface& netif) const
247 {
248  CFReleaser<CFStringRef> linkName =
249  detail::cfstring::fromStdString("State:/Network/Interface/" + netif.getName() + "/Link");
250 
252  (CFDictionaryRef)SCDynamicStoreCopyValue(m_scStore.get(), linkName.get());
253  if (dict.get() == nullptr) {
255  }
256 
257  CFBooleanRef isActive = (CFBooleanRef)CFDictionaryGetValue(dict.get(), CFSTR("Active"));
258  if (isActive == nullptr) {
260  }
261 
262  return CFBooleanGetValue(isActive) ? InterfaceState::RUNNING : InterfaceState::DOWN;
263 }
264 
265 size_t
266 NetworkMonitorImplOsx::getInterfaceMtu(const NetworkInterface& netif)
267 {
268  ifreq ifr{};
269  std::strncpy(ifr.ifr_name, netif.getName().data(), sizeof(ifr.ifr_name) - 1);
270 
271  if (::ioctl(m_ioctlSocket.native_handle(), SIOCGIFMTU, &ifr) == 0) {
272  return static_cast<size_t>(ifr.ifr_mtu);
273  }
274 
275  NDN_LOG_WARN("failed to get MTU of " << netif.getName() << ": " << std::strerror(errno));
276  return ethernet::MAX_DATA_LEN;
277 }
278 
279 template<typename AddressBytes>
280 static uint8_t
281 computePrefixLength(const AddressBytes& mask)
282 {
283  uint8_t prefixLength = 0;
284  for (auto byte : mask) {
285  while (byte != 0) {
286  ++prefixLength;
287  byte <<= 1;
288  }
289  }
290  return prefixLength;
291 }
292 
293 void
294 NetworkMonitorImplOsx::updateInterfaceInfo(NetworkInterface& netif, const IfAddrs& ifaList)
295 {
296  BOOST_ASSERT(!netif.getName().empty());
297 
298  netif.setMtu(getInterfaceMtu(netif));
299 
300  for (ifaddrs* ifa = ifaList.get(); ifa != nullptr; ifa = ifa->ifa_next) {
301  if (ifa->ifa_name != netif.getName())
302  continue;
303 
304  netif.setFlags(ifa->ifa_flags);
305 
306  if (ifa->ifa_addr == nullptr)
307  continue;
308 
309  namespace ip = boost::asio::ip;
311  ip::address ipAddr, broadcastAddr;
312  uint8_t prefixLength = 0;
313 
314  switch (ifa->ifa_addr->sa_family) {
315  case AF_INET: {
316  addrFamily = AddressFamily::V4;
317 
318  const sockaddr_in* sin = reinterpret_cast<sockaddr_in*>(ifa->ifa_addr);
319  ip::address_v4::bytes_type bytes;
320  std::copy_n(reinterpret_cast<const unsigned char*>(&sin->sin_addr), bytes.size(), bytes.begin());
321  ipAddr = ip::address_v4(bytes);
322 
323  const sockaddr_in* sinMask = reinterpret_cast<sockaddr_in*>(ifa->ifa_netmask);
324  std::copy_n(reinterpret_cast<const unsigned char*>(&sinMask->sin_addr), bytes.size(), bytes.begin());
325  prefixLength = computePrefixLength(bytes);
326  break;
327  }
328 
329  case AF_INET6: {
330  addrFamily = AddressFamily::V6;
331 
332  const sockaddr_in6* sin6 = reinterpret_cast<sockaddr_in6*>(ifa->ifa_addr);
333  ip::address_v6::bytes_type bytes;
334  std::copy_n(reinterpret_cast<const unsigned char*>(&sin6->sin6_addr), bytes.size(), bytes.begin());
335  ip::address_v6 v6Addr(bytes);
336  if (v6Addr.is_link_local())
337  v6Addr.scope_id(if_nametoindex(netif.getName().data()));
338  ipAddr = v6Addr;
339 
340  const sockaddr_in6* sinMask = reinterpret_cast<sockaddr_in6*>(ifa->ifa_netmask);
341  std::copy_n(reinterpret_cast<const unsigned char*>(&sinMask->sin6_addr), bytes.size(), bytes.begin());
342  prefixLength = computePrefixLength(bytes);
343  break;
344  }
345 
346  case AF_LINK: {
347  const sockaddr_dl* sdl = reinterpret_cast<sockaddr_dl*>(ifa->ifa_addr);
348  netif.setIndex(sdl->sdl_index);
349 
350  if (sdl->sdl_type == IFT_ETHER && sdl->sdl_alen == ethernet::ADDR_LEN) {
352  netif.setEthernetAddress(ethernet::Address(reinterpret_cast<uint8_t*>(LLADDR(sdl))));
353  NDN_LOG_TRACE(netif.getName() << " has Ethernet address " << netif.getEthernetAddress());
354  }
355  else if (sdl->sdl_type == IFT_LOOP) {
357  }
358  else {
360  }
361  break;
362  }
363  }
364 
365  if (netif.canBroadcast()) {
367 
368  if (addrFamily == AddressFamily::V4 && ifa->ifa_broadaddr != nullptr) {
369  const sockaddr_in* sin = reinterpret_cast<sockaddr_in*>(ifa->ifa_broadaddr);
370  ip::address_v4::bytes_type bytes;
371  std::copy_n(reinterpret_cast<const unsigned char*>(&sin->sin_addr), bytes.size(), bytes.begin());
372  broadcastAddr = ip::address_v4(bytes);
373  }
374  }
375 
376  if (addrFamily == AddressFamily::UNSPECIFIED)
377  continue;
378 
380  if (ipAddr.is_loopback()) {
381  scope = AddressScope::HOST;
382  }
383  else if ((ipAddr.is_v4() && (ipAddr.to_v4().to_ulong() & 0xFFFF0000) == 0xA9FE0000) ||
384  (ipAddr.is_v6() && ipAddr.to_v6().is_link_local())) {
385  scope = AddressScope::LINK;
386  }
387 
388  netif.addNetworkAddress(NetworkAddress(addrFamily, ipAddr, broadcastAddr, prefixLength, scope, 0));
389  }
390 }
391 
392 void
393 NetworkMonitorImplOsx::onConfigChanged(SCDynamicStoreRef m_scStore, CFArrayRef changedKeys, void* context)
394 {
395  static_cast<NetworkMonitorImplOsx*>(context)->onConfigChanged(changedKeys);
396 }
397 
398 void
399 NetworkMonitorImplOsx::onConfigChanged(CFArrayRef changedKeys)
400 {
401  IfAddrs ifaList;
402 
403  size_t count = CFArrayGetCount(changedKeys);
404  for (size_t i = 0; i != count; ++i) {
405  Name key(detail::cfstring::toStdString((CFStringRef)CFArrayGetValueAtIndex(changedKeys, i)));
406  std::string ifName = key.at(-2).toUri();
407 
408  auto ifIt = m_interfaces.find(ifName);
409  if (ifIt == m_interfaces.end()) {
410  addNewInterface(ifName, ifaList);
411  return;
412  }
413 
414  auto removeInterface = [&] {
415  NDN_LOG_DEBUG("removing interface " << ifName);
416  shared_ptr<NetworkInterface> removedNetif = ifIt->second;
417  m_interfaces.erase(ifIt);
418  this->emitSignal(onInterfaceRemoved, removedNetif);
419  };
420 
421  NetworkInterface& netif = *ifIt->second;
422  std::string changedItem = key.at(-1).toUri();
423  if (changedItem == "Link") {
424  auto newState = getInterfaceState(netif);
425  if (newState == InterfaceState::UNKNOWN) {
426  // check if it is really unknown or interface removed
427  if (getInterfaceNames().count(ifName) == 0) {
428  removeInterface();
429  return;
430  }
431  }
432  NDN_LOG_TRACE(ifName << " status changed from " << netif.getState() << " to " << newState);
433  netif.setState(newState);
434  }
435  else if (changedItem == "IPv4" || changedItem == "IPv6") {
436  auto updatedNetif = makeNetworkInterface();
437  updatedNetif->setName(ifName);
438  updateInterfaceInfo(*updatedNetif, ifaList);
439  if (updatedNetif->getType() == InterfaceType::UNKNOWN) {
440  NDN_LOG_DEBUG(ifName << " type changed to unknown");
441  removeInterface();
442  return;
443  }
444 
445  const auto& newAddrs = updatedNetif->getNetworkAddresses();
446  const auto& oldAddrs = netif.getNetworkAddresses();
447  std::set<NetworkAddress> added;
448  std::set<NetworkAddress> removed;
449  std::set_difference(newAddrs.begin(), newAddrs.end(),
450  oldAddrs.begin(), oldAddrs.end(), std::inserter(added, added.end()));
451  std::set_difference(oldAddrs.begin(), oldAddrs.end(),
452  newAddrs.begin(), newAddrs.end(), std::inserter(removed, removed.end()));
453 
454  for (const auto& addr : removed) {
455  netif.removeNetworkAddress(addr);
456  }
457  for (const auto& addr : added) {
458  netif.addNetworkAddress(addr);
459  }
460  }
461  }
462 }
463 
464 } // namespace net
465 } // namespace ndn
interface is administratively down
CFReleaser< CFStringRef > fromStdString(const std::string &str)
Create a CFString by copying characters from a std::string.
This file contains utilities to deal with Apple Core Foundation&#39;s CFString and related types...
Copyright (c) 2011-2015 Regents of the University of California.
std::string toStdString(CFStringRef cfStr)
Convert a CFString to a std::string.
InterfaceState getState() const
Returns the current state of the interface.
interface is in an unknown state
interface can be used to send and receive packets
void setState(InterfaceState state)
static shared_ptr< NetworkInterface > makeNetworkInterface()
std::string getName() const
Returns the name of the interface, unique on the system.
const size_t ADDR_LEN
Octets in one Ethernet address.
Definition: ethernet.hpp:41
#define NDN_LOG_WARN(expression)
Definition: logger.hpp:101
NetworkMonitorImplOsx(boost::asio::io_service &io)
#define NDN_LOG_DEBUG(expression)
Definition: logger.hpp:99
#define emitSignal(...)
(implementation detail)
Definition: emit.hpp:76
InterfaceState
Indicates the state of a network interface.
bool canBroadcast() const
Returns true if the interface supports broadcast communication.
void setEthernetAddress(const ethernet::Address &address)
EventId schedule(time::nanoseconds after, EventCallback callback)
Schedule a one-time event after the specified delay.
Definition: scheduler.cpp:96
void setEthernetBroadcastAddress(const ethernet::Address &address)
#define NDN_THROW(e)
Definition: exception.hpp:61
util::Signal< NetworkMonitorImpl > onEnumerationCompleted
Represents one network interface attached to the host.
const Component & at(ssize_t i) const
Returns an immutable reference to the component at the specified index, with bounds checking...
Definition: name.cpp:171
NetworkMonitor::Error Error
Stores one IP address supported by a network interface.
Address getBroadcastAddress()
Returns the Ethernet broadcast address (ff:ff:ff:ff:ff:ff)
Definition: ethernet.cpp:115
std::vector< shared_ptr< const NetworkInterface > > listNetworkInterfaces() const final
bool removeNetworkAddress(const NetworkAddress &address)
util::Signal< NetworkMonitorImpl, shared_ptr< const NetworkInterface > > onInterfaceRemoved
void setFlags(uint32_t flags)
Represents an absolute name.
Definition: name.hpp:41
#define NDN_LOG_TRACE(expression)
Definition: logger.hpp:98
util::Signal< NetworkMonitorImpl, shared_ptr< const NetworkInterface > > onInterfaceAdded
Helper class to wrap CoreFoundation object pointers.
bool addNetworkAddress(const NetworkAddress &address)
shared_ptr< const NetworkInterface > getNetworkInterface(const std::string &ifname) const final
represents an Ethernet hardware address
Definition: ethernet.hpp:52
ifaddrs * get() const noexcept
ethernet::Address getEthernetAddress() const
Returns the link-layer (Ethernet) address of the interface.
#define NDN_LOG_INIT(name)
declare a log module
Definition: logger.hpp:81
util::Signal< NetworkMonitorImpl > onNetworkStateChanged
void setType(InterfaceType type)
const size_t MAX_DATA_LEN
Max octets in Ethernet payload.
Definition: ethernet.hpp:46
const std::set< NetworkAddress > & getNetworkAddresses() const
Returns a list of all network-layer addresses present on the interface.
#define NDN_THROW_ERRNO(e)
Definition: exception.hpp:68
void toUri(std::ostream &os, UriFormat format=UriFormat::DEFAULT) const
Write *this to the output stream, escaping characters according to the NDN URI format.
static uint8_t computePrefixLength(const AddressBytes &mask)