blob: 4ffb9db530975d1708bcf7ac08d22468564d25de [file] [log] [blame]
Davide Pesavento44deacc2014-02-19 10:48:07 +01001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2/**
Junxiao Shi08d07a72014-06-09 23:17:57 -07003 * Copyright (c) 2014, 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
Alexander Afanasyev9bcbc7c2014-04-06 19:37:37 -070010 *
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/>.
Junxiao Shi3ffe66d2014-11-06 15:37:59 -070024 */
Davide Pesavento44deacc2014-02-19 10:48:07 +010025
26#include "ethernet-face.hpp"
Steve DiBenedettobf6a93d2014-03-21 14:03:02 -060027#include "core/logger.hpp"
Davide Pesavento44deacc2014-02-19 10:48:07 +010028
29#include <pcap/pcap.h>
30
Davide Pesavento10783f22014-03-15 04:40:01 +010031#include <cerrno> // for errno
32#include <cstdio> // for std::snprintf()
33#include <cstring> // for std::strerror() and std::strncpy()
Davide Pesavento44deacc2014-02-19 10:48:07 +010034#include <arpa/inet.h> // for htons() and ntohs()
35#include <net/ethernet.h> // for struct ether_header
36#include <net/if.h> // for struct ifreq
Davide Pesavento44deacc2014-02-19 10:48:07 +010037#include <sys/ioctl.h> // for ioctl()
38#include <unistd.h> // for dup()
39
Davide Pesavento10783f22014-03-15 04:40:01 +010040#if defined(__linux__)
41#include <netpacket/packet.h> // for struct packet_mreq
42#include <sys/socket.h> // for setsockopt()
43#endif
44
45#ifdef SIOCADDMULTI
46#if defined(__APPLE__) || defined(__FreeBSD__)
47#include <net/if_dl.h> // for struct sockaddr_dl
48#endif
49#endif
50
Alexander Afanasyevd9479aa2014-06-26 13:52:02 -070051#if !defined(PCAP_NETMASK_UNKNOWN)
52/*
53 * Value to pass to pcap_compile() as the netmask if you don't know what
54 * the netmask is.
55 */
56#define PCAP_NETMASK_UNKNOWN 0xffffffff
57#endif
58
Davide Pesavento44deacc2014-02-19 10:48:07 +010059namespace nfd {
60
Davide Pesavento1bdef282014-04-08 20:59:50 +020061NFD_LOG_INIT("EthernetFace");
Davide Pesavento44deacc2014-02-19 10:48:07 +010062
Davide Pesavento44deacc2014-02-19 10:48:07 +010063EthernetFace::EthernetFace(const shared_ptr<boost::asio::posix::stream_descriptor>& socket,
Davide Pesaventob499a602014-11-18 22:36:56 +010064 const NetworkInterfaceInfo& interface,
Davide Pesavento44deacc2014-02-19 10:48:07 +010065 const ethernet::Address& address)
Davide Pesaventob499a602014-11-18 22:36:56 +010066 : Face(FaceUri(address), FaceUri::fromDev(interface.name))
Alexander Afanasyeva39b90b2014-03-05 15:31:00 +000067 , m_socket(socket)
Davide Pesavento10783f22014-03-15 04:40:01 +010068#if defined(__linux__)
69 , m_interfaceIndex(interface.index)
70#endif
Davide Pesaventob499a602014-11-18 22:36:56 +010071 , m_interfaceName(interface.name)
72 , m_srcAddress(interface.etherAddress)
Davide Pesavento44deacc2014-02-19 10:48:07 +010073 , m_destAddress(address)
74{
Davide Pesaventob60cc122014-03-19 19:26:02 +010075 NFD_LOG_INFO("Creating ethernet face on " << m_interfaceName << ": "
76 << m_srcAddress << " <--> " << m_destAddress);
Davide Pesavento44deacc2014-02-19 10:48:07 +010077 pcapInit();
78
79 int fd = pcap_get_selectable_fd(m_pcap);
80 if (fd < 0)
81 throw Error("pcap_get_selectable_fd() failed");
82
83 // need to duplicate the fd, otherwise both pcap_close()
84 // and stream_descriptor::close() will try to close the
85 // same fd and one of them will fail
86 m_socket->assign(::dup(fd));
87
Davide Pesavento44deacc2014-02-19 10:48:07 +010088 m_interfaceMtu = getInterfaceMtu();
Davide Pesaventob60cc122014-03-19 19:26:02 +010089 NFD_LOG_DEBUG("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +010090 << "] Interface MTU is: " << m_interfaceMtu);
91
92 char filter[100];
Davide Pesavento10783f22014-03-15 04:40:01 +010093 std::snprintf(filter, sizeof(filter),
94 "(ether proto 0x%x) && (ether dst %s) && (not ether src %s)",
95 ethernet::ETHERTYPE_NDN,
96 m_destAddress.toString().c_str(),
97 m_srcAddress.toString().c_str());
Davide Pesavento44deacc2014-02-19 10:48:07 +010098 setPacketFilter(filter);
99
Davide Pesavento10783f22014-03-15 04:40:01 +0100100 joinMulticastGroup();
101
Davide Pesavento44deacc2014-02-19 10:48:07 +0100102 m_socket->async_read_some(boost::asio::null_buffers(),
103 bind(&EthernetFace::handleRead, this,
104 boost::asio::placeholders::error,
105 boost::asio::placeholders::bytes_transferred));
106}
107
108EthernetFace::~EthernetFace()
109{
Alexander Afanasyev251f3c12014-06-02 18:39:58 +0300110 onFail.clear(); // no reason to call onFail anymore
Davide Pesavento44deacc2014-02-19 10:48:07 +0100111 close();
112}
113
114void
115EthernetFace::sendInterest(const Interest& interest)
116{
Alexander Afanasyev7e698e62014-03-07 16:48:35 +0000117 onSendInterest(interest);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100118 sendPacket(interest.wireEncode());
119}
120
121void
122EthernetFace::sendData(const Data& data)
123{
Alexander Afanasyev7e698e62014-03-07 16:48:35 +0000124 onSendData(data);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100125 sendPacket(data.wireEncode());
126}
127
128void
129EthernetFace::close()
130{
131 if (m_pcap)
132 {
133 boost::system::error_code error;
134 m_socket->close(error); // ignore errors
135 pcap_close(m_pcap);
136 m_pcap = 0;
Alexander Afanasyev251f3c12014-06-02 18:39:58 +0300137
Junxiao Shi08d07a72014-06-09 23:17:57 -0700138 fail("Face closed");
Davide Pesavento44deacc2014-02-19 10:48:07 +0100139 }
140}
141
142void
143EthernetFace::pcapInit()
144{
Davide Pesavento44deacc2014-02-19 10:48:07 +0100145 char errbuf[PCAP_ERRBUF_SIZE];
146 errbuf[0] = '\0';
Davide Pesaventob60cc122014-03-19 19:26:02 +0100147 m_pcap = pcap_create(m_interfaceName.c_str(), errbuf);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100148 if (!m_pcap)
149 throw Error("pcap_create(): " + std::string(errbuf));
150
Davide Pesaventof0ae4422014-05-05 16:32:12 +0200151#ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
152 // Enable "immediate mode", effectively disabling any read buffering in the kernel.
153 // This corresponds to the BIOCIMMEDIATE ioctl on BSD-like systems (including OS X)
154 // where libpcap uses a BPF device. On Linux this forces libpcap not to use TPACKET_V3,
155 // even if the kernel supports it, thus preventing bug #1511.
156 pcap_set_immediate_mode(m_pcap, 1);
157#endif
158
Davide Pesavento44deacc2014-02-19 10:48:07 +0100159 if (pcap_activate(m_pcap) < 0)
160 throw Error("pcap_activate() failed");
161
Davide Pesavento44deacc2014-02-19 10:48:07 +0100162 if (pcap_set_datalink(m_pcap, DLT_EN10MB) < 0)
163 throw Error("pcap_set_datalink(): " + std::string(pcap_geterr(m_pcap)));
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100164
165 if (pcap_setdirection(m_pcap, PCAP_D_IN) < 0)
166 // no need to throw on failure, BPF will filter unwanted packets anyway
167 NFD_LOG_WARN("pcap_setdirection(): " << pcap_geterr(m_pcap));
Davide Pesavento44deacc2014-02-19 10:48:07 +0100168}
169
170void
171EthernetFace::setPacketFilter(const char* filterString)
172{
173 bpf_program filter;
174 if (pcap_compile(m_pcap, &filter, filterString, 1, PCAP_NETMASK_UNKNOWN) < 0)
175 throw Error("pcap_compile(): " + std::string(pcap_geterr(m_pcap)));
176
177 int ret = pcap_setfilter(m_pcap, &filter);
178 pcap_freecode(&filter);
179 if (ret < 0)
180 throw Error("pcap_setfilter(): " + std::string(pcap_geterr(m_pcap)));
181}
182
183void
Davide Pesavento10783f22014-03-15 04:40:01 +0100184EthernetFace::joinMulticastGroup()
185{
186#if defined(__linux__)
187 packet_mreq mr{};
188 mr.mr_ifindex = m_interfaceIndex;
189 mr.mr_type = PACKET_MR_MULTICAST;
190 mr.mr_alen = m_destAddress.size();
191 std::copy(m_destAddress.begin(), m_destAddress.end(), mr.mr_address);
192
193 if (::setsockopt(m_socket->native_handle(), SOL_PACKET,
194 PACKET_ADD_MEMBERSHIP, &mr, sizeof(mr)) == 0)
195 return; // success
196
197 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
198 << "] setsockopt(PACKET_ADD_MEMBERSHIP) failed: " << std::strerror(errno));
199#endif
200
201#if defined(SIOCADDMULTI)
202 ifreq ifr{};
203 std::strncpy(ifr.ifr_name, m_interfaceName.c_str(), sizeof(ifr.ifr_name) - 1);
204
205#if defined(__APPLE__) || defined(__FreeBSD__)
206 /*
207 * Differences between Linux and the BSDs (including OS X):
208 * o BSD does not have ifr_hwaddr; use ifr_addr instead.
209 * o While OS X seems to accept both AF_LINK and AF_UNSPEC as the address
210 * family, FreeBSD explicitly requires AF_LINK, so we have to use AF_LINK
211 * and sockaddr_dl instead of the generic sockaddr structure.
212 * o BSD's sockaddr (and sockaddr_dl in particular) contains an additional
213 * field, sa_len (sdl_len), which must be set to the total length of the
214 * structure, including the length field itself.
215 * o We do not specify the interface name, thus sdl_nlen is left at 0 and
216 * LLADDR is effectively the same as sdl_data.
217 */
218 sockaddr_dl* sdl = reinterpret_cast<sockaddr_dl*>(&ifr.ifr_addr);
219 sdl->sdl_len = sizeof(ifr.ifr_addr);
220 sdl->sdl_family = AF_LINK;
221 sdl->sdl_alen = m_destAddress.size();
222 std::copy(m_destAddress.begin(), m_destAddress.end(), LLADDR(sdl));
223
224 static_assert(sizeof(ifr.ifr_addr) >= offsetof(sockaddr_dl, sdl_data) + ethernet::ADDR_LEN,
225 "ifr_addr in struct ifreq is too small on this platform");
226#else
227 ifr.ifr_hwaddr.sa_family = AF_UNSPEC;
228 std::copy(m_destAddress.begin(), m_destAddress.end(), ifr.ifr_hwaddr.sa_data);
229
230 static_assert(sizeof(ifr.ifr_hwaddr) >= offsetof(sockaddr, sa_data) + ethernet::ADDR_LEN,
231 "ifr_hwaddr in struct ifreq is too small on this platform");
232#endif
233
234 if (::ioctl(m_socket->native_handle(), SIOCADDMULTI, &ifr) >= 0)
235 return; // success
236
237 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
238 << "] ioctl(SIOCADDMULTI) failed: " << std::strerror(errno));
239#endif
240
241 if (!m_destAddress.isBroadcast())
242 {
243 NFD_LOG_DEBUG("[id:" << getId() << ",endpoint:" << m_interfaceName
244 << "] Falling back to promiscuous mode");
245 pcap_set_promisc(m_pcap, 1);
246 }
247}
248
249void
Davide Pesavento44deacc2014-02-19 10:48:07 +0100250EthernetFace::sendPacket(const ndn::Block& block)
251{
252 if (!m_pcap)
253 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100254 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +0100255 << "] Trying to send on closed face");
Junxiao Shi08d07a72014-06-09 23:17:57 -0700256 fail("Face closed");
Davide Pesavento44deacc2014-02-19 10:48:07 +0100257 return;
258 }
259
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100260 /// \todo Fragmentation
Davide Pesavento44deacc2014-02-19 10:48:07 +0100261 if (block.size() > m_interfaceMtu)
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100262 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100263 NFD_LOG_ERROR("[id:" << getId() << ",endpoint:" << m_interfaceName
264 << "] Fragmentation not implemented: dropping packet larger than MTU");
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100265 return;
266 }
Davide Pesavento44deacc2014-02-19 10:48:07 +0100267
268 /// \todo Right now there is no reserve when packet is received, but
269 /// we should reserve some space at the beginning and at the end
270 ndn::EncodingBuffer buffer(block);
271
Davide Pesaventoe4631002014-03-21 20:55:36 +0100272 // pad with zeroes if the payload is too short
Davide Pesavento44deacc2014-02-19 10:48:07 +0100273 if (block.size() < ethernet::MIN_DATA_LEN)
274 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100275 static const uint8_t padding[ethernet::MIN_DATA_LEN] = {0};
276 buffer.appendByteArray(padding, ethernet::MIN_DATA_LEN - block.size());
Davide Pesavento44deacc2014-02-19 10:48:07 +0100277 }
278
279 // construct and prepend the ethernet header
Junxiao Shi3ffe66d2014-11-06 15:37:59 -0700280 static uint16_t ethertype = htons(ethernet::ETHERTYPE_NDN);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100281 buffer.prependByteArray(reinterpret_cast<const uint8_t*>(&ethertype), ethernet::TYPE_LEN);
Davide Pesaventob60cc122014-03-19 19:26:02 +0100282 buffer.prependByteArray(m_srcAddress.data(), m_srcAddress.size());
Davide Pesavento44deacc2014-02-19 10:48:07 +0100283 buffer.prependByteArray(m_destAddress.data(), m_destAddress.size());
284
285 // send the packet
286 int sent = pcap_inject(m_pcap, buffer.buf(), buffer.size());
287 if (sent < 0)
288 {
289 throw Error("pcap_inject(): " + std::string(pcap_geterr(m_pcap)));
290 }
291 else if (static_cast<size_t>(sent) < buffer.size())
292 {
293 throw Error("Failed to send packet");
294 }
295
Davide Pesaventob60cc122014-03-19 19:26:02 +0100296 NFD_LOG_TRACE("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento4c1a0782014-08-14 16:13:20 +0200297 << "] Successfully sent: " << block.size() << " bytes");
298 this->getMutableCounters().getNOutBytes() += block.size();
Davide Pesavento44deacc2014-02-19 10:48:07 +0100299}
300
301void
302EthernetFace::handleRead(const boost::system::error_code& error, size_t)
303{
304 if (error)
305 return processErrorCode(error);
306
307 pcap_pkthdr* pktHeader;
308 const uint8_t* packet;
309 int ret = pcap_next_ex(m_pcap, &pktHeader, &packet);
310 if (ret < 0)
311 {
312 throw Error("pcap_next_ex(): " + std::string(pcap_geterr(m_pcap)));
313 }
314 else if (ret == 0)
315 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100316 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +0100317 << "] pcap_next_ex() timed out");
318 }
319 else
320 {
321 size_t length = pktHeader->caplen;
322 if (length < ethernet::HDR_LEN + ethernet::MIN_DATA_LEN)
323 throw Error("Received packet is too short");
324
325 const ether_header* eh = reinterpret_cast<const ether_header*>(packet);
Junxiao Shi3ffe66d2014-11-06 15:37:59 -0700326 if (ntohs(eh->ether_type) != ethernet::ETHERTYPE_NDN)
Davide Pesavento44deacc2014-02-19 10:48:07 +0100327 throw Error("Unrecognized ethertype");
328
329 packet += ethernet::HDR_LEN;
330 length -= ethernet::HDR_LEN;
Davide Pesavento44deacc2014-02-19 10:48:07 +0100331
Alexander Afanasyev5a8d8d82014-03-21 14:08:41 -0700332 /// \todo Reserve space in front and at the back
333 /// of the underlying buffer
334 Block element;
335 bool isOk = Block::fromBuffer(packet, length, element);
336 if (isOk)
337 {
Davide Pesavento4c1a0782014-08-14 16:13:20 +0200338 NFD_LOG_TRACE("[id:" << getId() << ",endpoint:" << m_interfaceName
339 << "] Received: " << element.size() << " bytes");
340 this->getMutableCounters().getNInBytes() += element.size();
341
Alexander Afanasyev5a8d8d82014-03-21 14:08:41 -0700342 if (!decodeAndDispatchInput(element))
343 {
344 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
345 << "] Received unrecognized block of type " << element.type());
346 // ignore unknown packet
347 }
348 }
349 else
350 {
351 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
352 << "] Received block is invalid or too large to process");
353 }
Davide Pesavento44deacc2014-02-19 10:48:07 +0100354 }
355
356 m_socket->async_read_some(boost::asio::null_buffers(),
357 bind(&EthernetFace::handleRead, this,
358 boost::asio::placeholders::error,
359 boost::asio::placeholders::bytes_transferred));
360}
361
362void
363EthernetFace::processErrorCode(const boost::system::error_code& error)
364{
365 if (error == boost::system::errc::operation_canceled)
366 // when socket is closed by someone
367 return;
368
369 if (!m_pcap)
370 {
Junxiao Shi08d07a72014-06-09 23:17:57 -0700371 fail("Face closed");
Davide Pesavento44deacc2014-02-19 10:48:07 +0100372 return;
373 }
374
375 std::string msg;
376 if (error == boost::asio::error::eof)
377 {
378 msg = "Face closed";
Davide Pesaventob60cc122014-03-19 19:26:02 +0100379 NFD_LOG_INFO("[id:" << getId() << ",endpoint:" << m_interfaceName << "] " << msg);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100380 }
381 else
382 {
Davide Pesavento4c1a0782014-08-14 16:13:20 +0200383 msg = "Receive operation failed, closing face: " + error.message();
Davide Pesaventob60cc122014-03-19 19:26:02 +0100384 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName << "] " << msg);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100385 }
386
387 close();
Junxiao Shi08d07a72014-06-09 23:17:57 -0700388 fail(msg);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100389}
390
Davide Pesavento44deacc2014-02-19 10:48:07 +0100391size_t
392EthernetFace::getInterfaceMtu() const
393{
394 size_t mtu = ethernet::MAX_DATA_LEN;
395
396#ifdef SIOCGIFMTU
Davide Pesavento10783f22014-03-15 04:40:01 +0100397 ifreq ifr{};
Davide Pesaventob60cc122014-03-19 19:26:02 +0100398 std::strncpy(ifr.ifr_name, m_interfaceName.c_str(), sizeof(ifr.ifr_name) - 1);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100399
400 if (::ioctl(m_socket->native_handle(), SIOCGIFMTU, &ifr) < 0)
401 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100402 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento10783f22014-03-15 04:40:01 +0100403 << "] Failed to get interface MTU: " << std::strerror(errno));
Davide Pesavento44deacc2014-02-19 10:48:07 +0100404 }
405 else
406 {
407 mtu = std::min(mtu, static_cast<size_t>(ifr.ifr_mtu));
408 }
409#endif
410
411 return mtu;
412}
413
414} // namespace nfd