blob: 27f34eea9a5764c57b8f53b785a44b687fe3489b [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
Davide Pesavento44deacc2014-02-19 10:48:07 +010040namespace nfd {
41
Davide Pesavento1bdef282014-04-08 20:59:50 +020042NFD_LOG_INIT("EthernetFace");
Davide Pesavento44deacc2014-02-19 10:48:07 +010043
Davide Pesavento44deacc2014-02-19 10:48:07 +010044EthernetFace::EthernetFace(const shared_ptr<boost::asio::posix::stream_descriptor>& socket,
Davide Pesaventob60cc122014-03-19 19:26:02 +010045 const shared_ptr<NetworkInterfaceInfo>& interface,
Davide Pesavento44deacc2014-02-19 10:48:07 +010046 const ethernet::Address& address)
Junxiao Shi79494162014-04-02 18:25:11 -070047 : Face(FaceUri(address), FaceUri::fromDev(interface->name))
Alexander Afanasyeva39b90b2014-03-05 15:31:00 +000048 , m_socket(socket)
Davide Pesaventob60cc122014-03-19 19:26:02 +010049 , m_interfaceName(interface->name)
50 , m_srcAddress(interface->etherAddress)
Davide Pesavento44deacc2014-02-19 10:48:07 +010051 , m_destAddress(address)
52{
Davide Pesaventob60cc122014-03-19 19:26:02 +010053 NFD_LOG_INFO("Creating ethernet face on " << m_interfaceName << ": "
54 << m_srcAddress << " <--> " << m_destAddress);
Davide Pesavento44deacc2014-02-19 10:48:07 +010055 pcapInit();
56
57 int fd = pcap_get_selectable_fd(m_pcap);
58 if (fd < 0)
59 throw Error("pcap_get_selectable_fd() failed");
60
61 // need to duplicate the fd, otherwise both pcap_close()
62 // and stream_descriptor::close() will try to close the
63 // same fd and one of them will fail
64 m_socket->assign(::dup(fd));
65
Davide Pesavento44deacc2014-02-19 10:48:07 +010066 m_interfaceMtu = getInterfaceMtu();
Davide Pesaventob60cc122014-03-19 19:26:02 +010067 NFD_LOG_DEBUG("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +010068 << "] Interface MTU is: " << m_interfaceMtu);
69
70 char filter[100];
71 ::snprintf(filter, sizeof(filter),
72 "(ether proto 0x%x) && (ether dst %s) && (not ether src %s)",
73 ETHERTYPE_NDN,
Davide Pesaventoedae3532014-04-09 03:07:11 +020074 m_destAddress.toString().c_str(),
75 m_srcAddress.toString().c_str());
Davide Pesavento44deacc2014-02-19 10:48:07 +010076 setPacketFilter(filter);
77
78 m_socket->async_read_some(boost::asio::null_buffers(),
79 bind(&EthernetFace::handleRead, this,
80 boost::asio::placeholders::error,
81 boost::asio::placeholders::bytes_transferred));
82}
83
84EthernetFace::~EthernetFace()
85{
Alexander Afanasyev251f3c12014-06-02 18:39:58 +030086 onFail.clear(); // no reason to call onFail anymore
Davide Pesavento44deacc2014-02-19 10:48:07 +010087 close();
88}
89
90void
91EthernetFace::sendInterest(const Interest& interest)
92{
Alexander Afanasyev7e698e62014-03-07 16:48:35 +000093 onSendInterest(interest);
Davide Pesavento44deacc2014-02-19 10:48:07 +010094 sendPacket(interest.wireEncode());
95}
96
97void
98EthernetFace::sendData(const Data& data)
99{
Alexander Afanasyev7e698e62014-03-07 16:48:35 +0000100 onSendData(data);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100101 sendPacket(data.wireEncode());
102}
103
104void
105EthernetFace::close()
106{
107 if (m_pcap)
108 {
109 boost::system::error_code error;
110 m_socket->close(error); // ignore errors
111 pcap_close(m_pcap);
112 m_pcap = 0;
Alexander Afanasyev251f3c12014-06-02 18:39:58 +0300113
Junxiao Shi08d07a72014-06-09 23:17:57 -0700114 fail("Face closed");
Davide Pesavento44deacc2014-02-19 10:48:07 +0100115 }
116}
117
118void
119EthernetFace::pcapInit()
120{
Davide Pesavento44deacc2014-02-19 10:48:07 +0100121 char errbuf[PCAP_ERRBUF_SIZE];
122 errbuf[0] = '\0';
Davide Pesaventob60cc122014-03-19 19:26:02 +0100123 m_pcap = pcap_create(m_interfaceName.c_str(), errbuf);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100124 if (!m_pcap)
125 throw Error("pcap_create(): " + std::string(errbuf));
126
Davide Pesaventof0ae4422014-05-05 16:32:12 +0200127#ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
128 // Enable "immediate mode", effectively disabling any read buffering in the kernel.
129 // This corresponds to the BIOCIMMEDIATE ioctl on BSD-like systems (including OS X)
130 // where libpcap uses a BPF device. On Linux this forces libpcap not to use TPACKET_V3,
131 // even if the kernel supports it, thus preventing bug #1511.
132 pcap_set_immediate_mode(m_pcap, 1);
133#endif
134
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100135 /// \todo Do not rely on promisc mode, see task #1278
136 if (!m_destAddress.isBroadcast())
137 pcap_set_promisc(m_pcap, 1);
138
Davide Pesavento44deacc2014-02-19 10:48:07 +0100139 if (pcap_activate(m_pcap) < 0)
140 throw Error("pcap_activate() failed");
141
Davide Pesavento44deacc2014-02-19 10:48:07 +0100142 if (pcap_set_datalink(m_pcap, DLT_EN10MB) < 0)
143 throw Error("pcap_set_datalink(): " + std::string(pcap_geterr(m_pcap)));
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100144
145 if (pcap_setdirection(m_pcap, PCAP_D_IN) < 0)
146 // no need to throw on failure, BPF will filter unwanted packets anyway
147 NFD_LOG_WARN("pcap_setdirection(): " << pcap_geterr(m_pcap));
Davide Pesavento44deacc2014-02-19 10:48:07 +0100148}
149
150void
151EthernetFace::setPacketFilter(const char* filterString)
152{
153 bpf_program filter;
154 if (pcap_compile(m_pcap, &filter, filterString, 1, PCAP_NETMASK_UNKNOWN) < 0)
155 throw Error("pcap_compile(): " + std::string(pcap_geterr(m_pcap)));
156
157 int ret = pcap_setfilter(m_pcap, &filter);
158 pcap_freecode(&filter);
159 if (ret < 0)
160 throw Error("pcap_setfilter(): " + std::string(pcap_geterr(m_pcap)));
161}
162
163void
164EthernetFace::sendPacket(const ndn::Block& block)
165{
166 if (!m_pcap)
167 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100168 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +0100169 << "] Trying to send on closed face");
Junxiao Shi08d07a72014-06-09 23:17:57 -0700170 fail("Face closed");
Davide Pesavento44deacc2014-02-19 10:48:07 +0100171 return;
172 }
173
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100174 /// \todo Fragmentation
Davide Pesavento44deacc2014-02-19 10:48:07 +0100175 if (block.size() > m_interfaceMtu)
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100176 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100177 NFD_LOG_ERROR("[id:" << getId() << ",endpoint:" << m_interfaceName
178 << "] Fragmentation not implemented: dropping packet larger than MTU");
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100179 return;
180 }
Davide Pesavento44deacc2014-02-19 10:48:07 +0100181
182 /// \todo Right now there is no reserve when packet is received, but
183 /// we should reserve some space at the beginning and at the end
184 ndn::EncodingBuffer buffer(block);
185
Davide Pesaventoe4631002014-03-21 20:55:36 +0100186 // pad with zeroes if the payload is too short
Davide Pesavento44deacc2014-02-19 10:48:07 +0100187 if (block.size() < ethernet::MIN_DATA_LEN)
188 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100189 static const uint8_t padding[ethernet::MIN_DATA_LEN] = {0};
190 buffer.appendByteArray(padding, ethernet::MIN_DATA_LEN - block.size());
Davide Pesavento44deacc2014-02-19 10:48:07 +0100191 }
192
193 // construct and prepend the ethernet header
194 static uint16_t ethertype = htons(ETHERTYPE_NDN);
195 buffer.prependByteArray(reinterpret_cast<const uint8_t*>(&ethertype), ethernet::TYPE_LEN);
Davide Pesaventob60cc122014-03-19 19:26:02 +0100196 buffer.prependByteArray(m_srcAddress.data(), m_srcAddress.size());
Davide Pesavento44deacc2014-02-19 10:48:07 +0100197 buffer.prependByteArray(m_destAddress.data(), m_destAddress.size());
198
199 // send the packet
200 int sent = pcap_inject(m_pcap, buffer.buf(), buffer.size());
201 if (sent < 0)
202 {
203 throw Error("pcap_inject(): " + std::string(pcap_geterr(m_pcap)));
204 }
205 else if (static_cast<size_t>(sent) < buffer.size())
206 {
207 throw Error("Failed to send packet");
208 }
209
Davide Pesaventob60cc122014-03-19 19:26:02 +0100210 NFD_LOG_TRACE("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +0100211 << "] Successfully sent: " << buffer.size() << " bytes");
212}
213
214void
215EthernetFace::handleRead(const boost::system::error_code& error, size_t)
216{
217 if (error)
218 return processErrorCode(error);
219
220 pcap_pkthdr* pktHeader;
221 const uint8_t* packet;
222 int ret = pcap_next_ex(m_pcap, &pktHeader, &packet);
223 if (ret < 0)
224 {
225 throw Error("pcap_next_ex(): " + std::string(pcap_geterr(m_pcap)));
226 }
227 else if (ret == 0)
228 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100229 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +0100230 << "] pcap_next_ex() timed out");
231 }
232 else
233 {
234 size_t length = pktHeader->caplen;
235 if (length < ethernet::HDR_LEN + ethernet::MIN_DATA_LEN)
236 throw Error("Received packet is too short");
237
238 const ether_header* eh = reinterpret_cast<const ether_header*>(packet);
239 if (ntohs(eh->ether_type) != ETHERTYPE_NDN)
240 throw Error("Unrecognized ethertype");
241
242 packet += ethernet::HDR_LEN;
243 length -= ethernet::HDR_LEN;
Davide Pesaventob60cc122014-03-19 19:26:02 +0100244 NFD_LOG_TRACE("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +0100245 << "] Received: " << length << " bytes");
246
Alexander Afanasyev5a8d8d82014-03-21 14:08:41 -0700247 /// \todo Reserve space in front and at the back
248 /// of the underlying buffer
249 Block element;
250 bool isOk = Block::fromBuffer(packet, length, element);
251 if (isOk)
252 {
253 if (!decodeAndDispatchInput(element))
254 {
255 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
256 << "] Received unrecognized block of type " << element.type());
257 // ignore unknown packet
258 }
259 }
260 else
261 {
262 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
263 << "] Received block is invalid or too large to process");
264 }
Davide Pesavento44deacc2014-02-19 10:48:07 +0100265 }
266
267 m_socket->async_read_some(boost::asio::null_buffers(),
268 bind(&EthernetFace::handleRead, this,
269 boost::asio::placeholders::error,
270 boost::asio::placeholders::bytes_transferred));
271}
272
273void
274EthernetFace::processErrorCode(const boost::system::error_code& error)
275{
276 if (error == boost::system::errc::operation_canceled)
277 // when socket is closed by someone
278 return;
279
280 if (!m_pcap)
281 {
Junxiao Shi08d07a72014-06-09 23:17:57 -0700282 fail("Face closed");
Davide Pesavento44deacc2014-02-19 10:48:07 +0100283 return;
284 }
285
286 std::string msg;
287 if (error == boost::asio::error::eof)
288 {
289 msg = "Face closed";
Davide Pesaventob60cc122014-03-19 19:26:02 +0100290 NFD_LOG_INFO("[id:" << getId() << ",endpoint:" << m_interfaceName << "] " << msg);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100291 }
292 else
293 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100294 msg = "Receive operation failed, closing face: " + error.category().message(error.value());
295 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName << "] " << msg);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100296 }
297
298 close();
Junxiao Shi08d07a72014-06-09 23:17:57 -0700299 fail(msg);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100300}
301
Davide Pesavento44deacc2014-02-19 10:48:07 +0100302size_t
303EthernetFace::getInterfaceMtu() const
304{
305 size_t mtu = ethernet::MAX_DATA_LEN;
306
307#ifdef SIOCGIFMTU
Alexander Afanasyevf4e89b42014-05-31 15:54:18 +0300308 ifreq ifr = boost::initialized_value;
Davide Pesaventob60cc122014-03-19 19:26:02 +0100309 std::strncpy(ifr.ifr_name, m_interfaceName.c_str(), sizeof(ifr.ifr_name) - 1);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100310
311 if (::ioctl(m_socket->native_handle(), SIOCGIFMTU, &ifr) < 0)
312 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100313 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +0100314 << "] Failed to get interface MTU, assuming " << mtu);
315 }
316 else
317 {
318 mtu = std::min(mtu, static_cast<size_t>(ifr.ifr_mtu));
319 }
320#endif
321
322 return mtu;
323}
324
325} // namespace nfd