blob: 66957dbd084be9bc7b1c5fcc9f36426d623a3240 [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/>.
24 **/
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 Pesaventob60cc122014-03-19 19:26:02 +010028#include "core/network-interface.hpp"
Davide Pesavento44deacc2014-02-19 10:48:07 +010029
30#include <pcap/pcap.h>
31
Davide Pesaventob60cc122014-03-19 19:26:02 +010032#include <cstring> // for std::strncpy()
Davide Pesavento44deacc2014-02-19 10:48:07 +010033#include <arpa/inet.h> // for htons() and ntohs()
34#include <net/ethernet.h> // for struct ether_header
35#include <net/if.h> // for struct ifreq
36#include <stdio.h> // for snprintf()
37#include <sys/ioctl.h> // for ioctl()
38#include <unistd.h> // for dup()
39
Alexander Afanasyevd9479aa2014-06-26 13:52:02 -070040#if !defined(PCAP_NETMASK_UNKNOWN)
41/*
42 * Value to pass to pcap_compile() as the netmask if you don't know what
43 * the netmask is.
44 */
45#define PCAP_NETMASK_UNKNOWN 0xffffffff
46#endif
47
Davide Pesavento44deacc2014-02-19 10:48:07 +010048namespace nfd {
49
Davide Pesavento1bdef282014-04-08 20:59:50 +020050NFD_LOG_INIT("EthernetFace");
Davide Pesavento44deacc2014-02-19 10:48:07 +010051
Davide Pesavento44deacc2014-02-19 10:48:07 +010052EthernetFace::EthernetFace(const shared_ptr<boost::asio::posix::stream_descriptor>& socket,
Davide Pesaventob60cc122014-03-19 19:26:02 +010053 const shared_ptr<NetworkInterfaceInfo>& interface,
Davide Pesavento44deacc2014-02-19 10:48:07 +010054 const ethernet::Address& address)
Junxiao Shi79494162014-04-02 18:25:11 -070055 : Face(FaceUri(address), FaceUri::fromDev(interface->name))
Alexander Afanasyeva39b90b2014-03-05 15:31:00 +000056 , m_socket(socket)
Davide Pesaventob60cc122014-03-19 19:26:02 +010057 , m_interfaceName(interface->name)
58 , m_srcAddress(interface->etherAddress)
Davide Pesavento44deacc2014-02-19 10:48:07 +010059 , m_destAddress(address)
60{
Davide Pesaventob60cc122014-03-19 19:26:02 +010061 NFD_LOG_INFO("Creating ethernet face on " << m_interfaceName << ": "
62 << m_srcAddress << " <--> " << m_destAddress);
Davide Pesavento44deacc2014-02-19 10:48:07 +010063 pcapInit();
64
65 int fd = pcap_get_selectable_fd(m_pcap);
66 if (fd < 0)
67 throw Error("pcap_get_selectable_fd() failed");
68
69 // need to duplicate the fd, otherwise both pcap_close()
70 // and stream_descriptor::close() will try to close the
71 // same fd and one of them will fail
72 m_socket->assign(::dup(fd));
73
Davide Pesavento44deacc2014-02-19 10:48:07 +010074 m_interfaceMtu = getInterfaceMtu();
Davide Pesaventob60cc122014-03-19 19:26:02 +010075 NFD_LOG_DEBUG("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +010076 << "] Interface MTU is: " << m_interfaceMtu);
77
78 char filter[100];
79 ::snprintf(filter, sizeof(filter),
80 "(ether proto 0x%x) && (ether dst %s) && (not ether src %s)",
81 ETHERTYPE_NDN,
Davide Pesaventoedae3532014-04-09 03:07:11 +020082 m_destAddress.toString().c_str(),
83 m_srcAddress.toString().c_str());
Davide Pesavento44deacc2014-02-19 10:48:07 +010084 setPacketFilter(filter);
85
86 m_socket->async_read_some(boost::asio::null_buffers(),
87 bind(&EthernetFace::handleRead, this,
88 boost::asio::placeholders::error,
89 boost::asio::placeholders::bytes_transferred));
90}
91
92EthernetFace::~EthernetFace()
93{
Alexander Afanasyev251f3c12014-06-02 18:39:58 +030094 onFail.clear(); // no reason to call onFail anymore
Davide Pesavento44deacc2014-02-19 10:48:07 +010095 close();
96}
97
98void
99EthernetFace::sendInterest(const Interest& interest)
100{
Alexander Afanasyev7e698e62014-03-07 16:48:35 +0000101 onSendInterest(interest);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100102 sendPacket(interest.wireEncode());
103}
104
105void
106EthernetFace::sendData(const Data& data)
107{
Alexander Afanasyev7e698e62014-03-07 16:48:35 +0000108 onSendData(data);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100109 sendPacket(data.wireEncode());
110}
111
112void
113EthernetFace::close()
114{
115 if (m_pcap)
116 {
117 boost::system::error_code error;
118 m_socket->close(error); // ignore errors
119 pcap_close(m_pcap);
120 m_pcap = 0;
Alexander Afanasyev251f3c12014-06-02 18:39:58 +0300121
Junxiao Shi08d07a72014-06-09 23:17:57 -0700122 fail("Face closed");
Davide Pesavento44deacc2014-02-19 10:48:07 +0100123 }
124}
125
126void
127EthernetFace::pcapInit()
128{
Davide Pesavento44deacc2014-02-19 10:48:07 +0100129 char errbuf[PCAP_ERRBUF_SIZE];
130 errbuf[0] = '\0';
Davide Pesaventob60cc122014-03-19 19:26:02 +0100131 m_pcap = pcap_create(m_interfaceName.c_str(), errbuf);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100132 if (!m_pcap)
133 throw Error("pcap_create(): " + std::string(errbuf));
134
Davide Pesaventof0ae4422014-05-05 16:32:12 +0200135#ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
136 // Enable "immediate mode", effectively disabling any read buffering in the kernel.
137 // This corresponds to the BIOCIMMEDIATE ioctl on BSD-like systems (including OS X)
138 // where libpcap uses a BPF device. On Linux this forces libpcap not to use TPACKET_V3,
139 // even if the kernel supports it, thus preventing bug #1511.
140 pcap_set_immediate_mode(m_pcap, 1);
141#endif
142
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100143 /// \todo Do not rely on promisc mode, see task #1278
144 if (!m_destAddress.isBroadcast())
145 pcap_set_promisc(m_pcap, 1);
146
Davide Pesavento44deacc2014-02-19 10:48:07 +0100147 if (pcap_activate(m_pcap) < 0)
148 throw Error("pcap_activate() failed");
149
Davide Pesavento44deacc2014-02-19 10:48:07 +0100150 if (pcap_set_datalink(m_pcap, DLT_EN10MB) < 0)
151 throw Error("pcap_set_datalink(): " + std::string(pcap_geterr(m_pcap)));
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100152
153 if (pcap_setdirection(m_pcap, PCAP_D_IN) < 0)
154 // no need to throw on failure, BPF will filter unwanted packets anyway
155 NFD_LOG_WARN("pcap_setdirection(): " << pcap_geterr(m_pcap));
Davide Pesavento44deacc2014-02-19 10:48:07 +0100156}
157
158void
159EthernetFace::setPacketFilter(const char* filterString)
160{
161 bpf_program filter;
162 if (pcap_compile(m_pcap, &filter, filterString, 1, PCAP_NETMASK_UNKNOWN) < 0)
163 throw Error("pcap_compile(): " + std::string(pcap_geterr(m_pcap)));
164
165 int ret = pcap_setfilter(m_pcap, &filter);
166 pcap_freecode(&filter);
167 if (ret < 0)
168 throw Error("pcap_setfilter(): " + std::string(pcap_geterr(m_pcap)));
169}
170
171void
172EthernetFace::sendPacket(const ndn::Block& block)
173{
174 if (!m_pcap)
175 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100176 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +0100177 << "] Trying to send on closed face");
Junxiao Shi08d07a72014-06-09 23:17:57 -0700178 fail("Face closed");
Davide Pesavento44deacc2014-02-19 10:48:07 +0100179 return;
180 }
181
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100182 /// \todo Fragmentation
Davide Pesavento44deacc2014-02-19 10:48:07 +0100183 if (block.size() > m_interfaceMtu)
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100184 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100185 NFD_LOG_ERROR("[id:" << getId() << ",endpoint:" << m_interfaceName
186 << "] Fragmentation not implemented: dropping packet larger than MTU");
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100187 return;
188 }
Davide Pesavento44deacc2014-02-19 10:48:07 +0100189
190 /// \todo Right now there is no reserve when packet is received, but
191 /// we should reserve some space at the beginning and at the end
192 ndn::EncodingBuffer buffer(block);
193
Davide Pesaventoe4631002014-03-21 20:55:36 +0100194 // pad with zeroes if the payload is too short
Davide Pesavento44deacc2014-02-19 10:48:07 +0100195 if (block.size() < ethernet::MIN_DATA_LEN)
196 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100197 static const uint8_t padding[ethernet::MIN_DATA_LEN] = {0};
198 buffer.appendByteArray(padding, ethernet::MIN_DATA_LEN - block.size());
Davide Pesavento44deacc2014-02-19 10:48:07 +0100199 }
200
201 // construct and prepend the ethernet header
202 static uint16_t ethertype = htons(ETHERTYPE_NDN);
203 buffer.prependByteArray(reinterpret_cast<const uint8_t*>(&ethertype), ethernet::TYPE_LEN);
Davide Pesaventob60cc122014-03-19 19:26:02 +0100204 buffer.prependByteArray(m_srcAddress.data(), m_srcAddress.size());
Davide Pesavento44deacc2014-02-19 10:48:07 +0100205 buffer.prependByteArray(m_destAddress.data(), m_destAddress.size());
206
207 // send the packet
208 int sent = pcap_inject(m_pcap, buffer.buf(), buffer.size());
209 if (sent < 0)
210 {
211 throw Error("pcap_inject(): " + std::string(pcap_geterr(m_pcap)));
212 }
213 else if (static_cast<size_t>(sent) < buffer.size())
214 {
215 throw Error("Failed to send packet");
216 }
217
Davide Pesaventob60cc122014-03-19 19:26:02 +0100218 NFD_LOG_TRACE("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento4c1a0782014-08-14 16:13:20 +0200219 << "] Successfully sent: " << block.size() << " bytes");
220 this->getMutableCounters().getNOutBytes() += block.size();
Davide Pesavento44deacc2014-02-19 10:48:07 +0100221}
222
223void
224EthernetFace::handleRead(const boost::system::error_code& error, size_t)
225{
226 if (error)
227 return processErrorCode(error);
228
229 pcap_pkthdr* pktHeader;
230 const uint8_t* packet;
231 int ret = pcap_next_ex(m_pcap, &pktHeader, &packet);
232 if (ret < 0)
233 {
234 throw Error("pcap_next_ex(): " + std::string(pcap_geterr(m_pcap)));
235 }
236 else if (ret == 0)
237 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100238 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +0100239 << "] pcap_next_ex() timed out");
240 }
241 else
242 {
243 size_t length = pktHeader->caplen;
244 if (length < ethernet::HDR_LEN + ethernet::MIN_DATA_LEN)
245 throw Error("Received packet is too short");
246
247 const ether_header* eh = reinterpret_cast<const ether_header*>(packet);
248 if (ntohs(eh->ether_type) != ETHERTYPE_NDN)
249 throw Error("Unrecognized ethertype");
250
251 packet += ethernet::HDR_LEN;
252 length -= ethernet::HDR_LEN;
Davide Pesavento44deacc2014-02-19 10:48:07 +0100253
Alexander Afanasyev5a8d8d82014-03-21 14:08:41 -0700254 /// \todo Reserve space in front and at the back
255 /// of the underlying buffer
256 Block element;
257 bool isOk = Block::fromBuffer(packet, length, element);
258 if (isOk)
259 {
Davide Pesavento4c1a0782014-08-14 16:13:20 +0200260 NFD_LOG_TRACE("[id:" << getId() << ",endpoint:" << m_interfaceName
261 << "] Received: " << element.size() << " bytes");
262 this->getMutableCounters().getNInBytes() += element.size();
263
Alexander Afanasyev5a8d8d82014-03-21 14:08:41 -0700264 if (!decodeAndDispatchInput(element))
265 {
266 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
267 << "] Received unrecognized block of type " << element.type());
268 // ignore unknown packet
269 }
270 }
271 else
272 {
273 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
274 << "] Received block is invalid or too large to process");
275 }
Davide Pesavento44deacc2014-02-19 10:48:07 +0100276 }
277
278 m_socket->async_read_some(boost::asio::null_buffers(),
279 bind(&EthernetFace::handleRead, this,
280 boost::asio::placeholders::error,
281 boost::asio::placeholders::bytes_transferred));
282}
283
284void
285EthernetFace::processErrorCode(const boost::system::error_code& error)
286{
287 if (error == boost::system::errc::operation_canceled)
288 // when socket is closed by someone
289 return;
290
291 if (!m_pcap)
292 {
Junxiao Shi08d07a72014-06-09 23:17:57 -0700293 fail("Face closed");
Davide Pesavento44deacc2014-02-19 10:48:07 +0100294 return;
295 }
296
297 std::string msg;
298 if (error == boost::asio::error::eof)
299 {
300 msg = "Face closed";
Davide Pesaventob60cc122014-03-19 19:26:02 +0100301 NFD_LOG_INFO("[id:" << getId() << ",endpoint:" << m_interfaceName << "] " << msg);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100302 }
303 else
304 {
Davide Pesavento4c1a0782014-08-14 16:13:20 +0200305 msg = "Receive operation failed, closing face: " + error.message();
Davide Pesaventob60cc122014-03-19 19:26:02 +0100306 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName << "] " << msg);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100307 }
308
309 close();
Junxiao Shi08d07a72014-06-09 23:17:57 -0700310 fail(msg);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100311}
312
Davide Pesavento44deacc2014-02-19 10:48:07 +0100313size_t
314EthernetFace::getInterfaceMtu() const
315{
316 size_t mtu = ethernet::MAX_DATA_LEN;
317
318#ifdef SIOCGIFMTU
Alexander Afanasyevf4e89b42014-05-31 15:54:18 +0300319 ifreq ifr = boost::initialized_value;
Davide Pesaventob60cc122014-03-19 19:26:02 +0100320 std::strncpy(ifr.ifr_name, m_interfaceName.c_str(), sizeof(ifr.ifr_name) - 1);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100321
322 if (::ioctl(m_socket->native_handle(), SIOCGIFMTU, &ifr) < 0)
323 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100324 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +0100325 << "] Failed to get interface MTU, assuming " << mtu);
326 }
327 else
328 {
329 mtu = std::min(mtu, static_cast<size_t>(ifr.ifr_mtu));
330 }
331#endif
332
333 return mtu;
334}
335
336} // namespace nfd