29 #include <pcap/pcap.h> 34 #include <arpa/inet.h> 35 #include <net/ethernet.h> 37 #include <sys/ioctl.h> 40 #if defined(__linux__) 41 #include <netpacket/packet.h> 42 #include <sys/socket.h> 46 #if defined(__APPLE__) || defined(__FreeBSD__) 47 #include <net/if_dl.h> 51 #if !defined(PCAP_NETMASK_UNKNOWN) 56 #define PCAP_NETMASK_UNKNOWN 0xffffffff 63 const time::nanoseconds EthernetFace::REASSEMBLER_LIFETIME = time::seconds(60);
69 , m_pcap(nullptr, pcap_close)
70 , m_socket(
std::move(socket))
71 #if defined(__linux__)
72 , m_interfaceIndex(interface.index)
74 , m_interfaceName(interface.
name)
75 , m_srcAddress(interface.etherAddress)
76 , m_destAddress(address)
84 int fd = pcap_get_selectable_fd(m_pcap.get());
86 BOOST_THROW_EXCEPTION(
Error(
"pcap_get_selectable_fd failed"));
91 m_socket.assign(::dup(fd));
93 m_interfaceMtu = getInterfaceMtu();
101 snprintf(filter,
sizeof(filter),
102 "(ether proto 0x%x) && (ether dst %s) && (not ether src %s)",
106 setPacketFilter(filter);
108 if (!m_destAddress.
isBroadcast() && !joinMulticastGroup())
111 pcap_set_promisc(m_pcap.get(), 1);
114 m_socket.async_read_some(boost::asio::null_buffers(),
115 bind(&EthernetFace::handleRead,
this,
116 boost::asio::placeholders::error,
117 boost::asio::placeholders::bytes_transferred));
128 for (
const auto& packet : *pa) {
141 for (
const auto& packet : *pa) {
154 boost::system::error_code error;
155 m_socket.cancel(error);
156 m_socket.close(error);
163 EthernetFace::pcapInit()
165 char errbuf[PCAP_ERRBUF_SIZE] = {};
166 m_pcap.reset(pcap_create(m_interfaceName.c_str(), errbuf));
168 BOOST_THROW_EXCEPTION(Error(
"pcap_create: " + std::string(errbuf)));
170 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE 175 pcap_set_immediate_mode(m_pcap.get(), 1);
178 if (pcap_activate(m_pcap.get()) < 0)
179 BOOST_THROW_EXCEPTION(Error(
"pcap_activate failed"));
181 if (pcap_set_datalink(m_pcap.get(), DLT_EN10MB) < 0)
182 BOOST_THROW_EXCEPTION(Error(
"pcap_set_datalink: " + std::string(pcap_geterr(m_pcap.get()))));
184 if (pcap_setdirection(m_pcap.get(), PCAP_D_IN) < 0)
190 EthernetFace::setPacketFilter(
const char* filterString)
194 BOOST_THROW_EXCEPTION(Error(
"pcap_compile: " + std::string(pcap_geterr(m_pcap.get()))));
196 int ret = pcap_setfilter(m_pcap.get(), &filter);
197 pcap_freecode(&filter);
199 BOOST_THROW_EXCEPTION(Error(
"pcap_setfilter: " + std::string(pcap_geterr(m_pcap.get()))));
203 EthernetFace::joinMulticastGroup()
205 #if defined(__linux__) 207 mr.mr_ifindex = m_interfaceIndex;
208 mr.mr_type = PACKET_MR_MULTICAST;
209 mr.mr_alen = m_destAddress.size();
210 std::copy(m_destAddress.begin(), m_destAddress.end(), mr.mr_address);
212 if (::setsockopt(m_socket.native_handle(), SOL_PACKET,
213 PACKET_ADD_MEMBERSHIP, &mr,
sizeof(mr)) == 0)
216 NFD_LOG_FACE_WARN(
"setsockopt(PACKET_ADD_MEMBERSHIP) failed: " << std::strerror(errno));
219 #if defined(SIOCADDMULTI) 221 std::strncpy(ifr.ifr_name, m_interfaceName.c_str(),
sizeof(ifr.ifr_name) - 1);
223 #if defined(__APPLE__) || defined(__FreeBSD__) 225 using boost::asio::ip::udp;
227 int fd = sock.native_handle();
241 sockaddr_dl* sdl =
reinterpret_cast<sockaddr_dl*
>(&ifr.ifr_addr);
242 sdl->sdl_len =
sizeof(ifr.ifr_addr);
243 sdl->sdl_family = AF_LINK;
244 sdl->sdl_alen = m_destAddress.size();
245 std::copy(m_destAddress.begin(), m_destAddress.end(), LLADDR(sdl));
247 static_assert(
sizeof(ifr.ifr_addr) >= offsetof(sockaddr_dl, sdl_data) +
ethernet::ADDR_LEN,
248 "ifr_addr in struct ifreq is too small on this platform");
250 int fd = m_socket.native_handle();
252 ifr.ifr_hwaddr.sa_family = AF_UNSPEC;
253 std::copy(m_destAddress.begin(), m_destAddress.end(), ifr.ifr_hwaddr.sa_data);
255 static_assert(
sizeof(ifr.ifr_hwaddr) >= offsetof(sockaddr, sa_data) +
ethernet::ADDR_LEN,
256 "ifr_hwaddr in struct ifreq is too small on this platform");
259 if (::ioctl(fd, SIOCADDMULTI, &ifr) == 0)
269 EthernetFace::sendPacket(
const ndn::Block& block)
274 return fail(
"Face closed");
277 BOOST_ASSERT(block.
size() <= m_interfaceMtu);
292 buffer.prependByteArray(reinterpret_cast<const uint8_t*>(ðertype),
ethernet::TYPE_LEN);
293 buffer.prependByteArray(m_srcAddress.data(), m_srcAddress.size());
294 buffer.prependByteArray(m_destAddress.data(), m_destAddress.size());
297 int sent = pcap_inject(m_pcap.get(), buffer.buf(), buffer.size());
300 return fail(
"pcap_inject: " + std::string(pcap_geterr(m_pcap.get())));
302 else if (static_cast<size_t>(sent) < buffer.size())
304 return fail(
"Failed to inject frame");
312 EthernetFace::handleRead(
const boost::system::error_code& error,
size_t)
315 return fail(
"Face closed");
318 return processErrorCode(error);
321 const uint8_t* packet;
322 int ret = pcap_next_ex(m_pcap.get(), &header, &packet);
325 return fail(
"pcap_next_ex: " + std::string(pcap_geterr(m_pcap.get())));
333 processIncomingPacket(header, packet);
338 ret = pcap_stats(m_pcap.get(), &ps);
345 if (ps.ps_drop - m_nDropped > 0)
347 m_nDropped = ps.ps_drop;
351 m_socket.async_read_some(boost::asio::null_buffers(),
352 bind(&EthernetFace::handleRead,
this,
353 boost::asio::placeholders::error,
354 boost::asio::placeholders::bytes_transferred));
358 EthernetFace::processIncomingPacket(
const pcap_pkthdr* header,
const uint8_t* packet)
360 size_t length = header->caplen;
366 const ether_header* eh =
reinterpret_cast<const ether_header*
>(packet);
371 "Received frame addressed to a different multicast group");
372 BOOST_ASSERT_MSG(sourceAddress != m_srcAddress,
373 "Received frame sent by this host");
375 "Received frame with unrecognized ethertype");
386 <<
" is invalid or too large to process");
391 << sourceAddress.toString());
394 Reassembler& reassembler = m_reassemblers[sourceAddress];
395 if (!reassembler.pms) {
397 reassembler.pms.reset(
new ndnlp::PartialMessageStore);
398 reassembler.pms->onReceive.connect(
399 [
this, sourceAddress] (
const Block& block) {
403 <<
" from " << sourceAddress.toString());
409 [
this, sourceAddress] {
410 BOOST_VERIFY(m_reassemblers.erase(sourceAddress) == 1);
416 NFD_LOG_FACE_WARN(
"Received invalid NDNLP fragment from " << sourceAddress.toString());
420 reassembler.pms->receive(fragment);
424 EthernetFace::processErrorCode(
const boost::system::error_code& error)
426 if (error == boost::asio::error::operation_aborted)
431 if (error == boost::asio::error::eof)
437 msg =
"Receive operation failed: " + error.message();
444 EthernetFace::getInterfaceMtu()
447 #if defined(__APPLE__) || defined(__FreeBSD__) 449 using boost::asio::ip::udp;
451 int fd = sock.native_handle();
453 int fd = m_socket.native_handle();
457 std::strncpy(ifr.ifr_name, m_interfaceName.c_str(),
sizeof(ifr.ifr_name) - 1);
459 if (::ioctl(fd, SIOCGIFMTU, &ifr) == 0)
460 return static_cast<size_t>(ifr.ifr_mtu);
const size_t ADDR_LEN
Octets in one Ethernet address.
static std::tuple< bool, Block > fromBuffer(ConstBufferPtr buffer, size_t offset)
Try to construct block from Buffer.
#define NFD_LOG_FACE_TRACE(msg)
Log a message at TRACE level.
provides fragmentation feature at sender
void cancel(const EventId &eventId)
cancel a scheduled event
represents an Ethernet hardware address
signal::Signal< Face, Interest > onSendInterest
fires when an Interest is sent out
represents the underlying protocol and address used by a Face
const ByteCounter & getNOutBytes() const
sent bytes
contains information about a network interface
bool decodeAndDispatchInput(const Block &element)
EthernetFace(boost::asio::posix::stream_descriptor socket, const NetworkInterfaceInfo &interface, const ethernet::Address &address)
void sendData(const Data &data) 1
send a Data
const size_t TYPE_LEN
Octets in Ethertype field.
Class representing a wire element of NDN-TLV packet format.
represents an Interest packet
static std::tuple< bool, NdnlpData > fromBlock(const Block &wire)
parse a NdnlpData packet
signal::Signal< Face, Data > onSendData
fires when a Data is sent out
void sendInterest(const Interest &interest) 1
send an Interest
EthernetFace-related error.
const size_t MIN_DATA_LEN
Min octets in Ethernet payload (assuming no 802.1Q tag)
#define emitSignal(...)
(implementation detail)
#define NFD_LOG_FACE_DEBUG(msg)
Log a message at DEBUG level.
void fail(const std::string &reason)
fail the face and raise onFail event if it's UP; otherwise do nothing
EncodingImpl< EncoderTag > EncodingBuffer
#define NFD_LOG_FACE_INFO(msg)
Log a message at INFO level.
Copyright (c) 2011-2015 Regents of the University of California.
shared_ptr< std::vector< Block > > PacketArray
void close() 1
Closes the face.
FaceCounters & getMutableCounters()
EventId schedule(const time::nanoseconds &after, const std::function< void()> &event)
schedule an event
#define PCAP_NETMASK_UNKNOWN
Copyright (c) 2014-2015, Regents of the University of California, Arizona Board of Regents...
const size_t MAX_DATA_LEN
Max octets in Ethernet payload.
bool isBroadcast() const
True if this is a broadcast address (ff:ff:ff:ff:ff:ff)
size_t wireEncode(EncodingImpl< TAG > &encoder) const
Fast encoding or block size estimation.
#define NFD_LOG_INIT(name)
const size_t HDR_LEN
Total octets in Ethernet header (without 802.1Q tag)
size_t wireEncode(EncodingImpl< TAG > &encoder, bool wantUnsignedPortionOnly=false) const
Fast encoding or block size estimation.
boost::asio::io_service & getGlobalIoService()
const uint16_t ETHERTYPE_NDN
const ByteCounter & getNInBytes() const
received bytes
std::string toString(char sep=':') const
Converts the address to a human-readable string.
#define NFD_LOG_FACE_WARN(msg)
Log a message at WARN level.