blob: 2fc24ab7bae5d3594b16092b5e6afac75197e71f [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 Pesaventob60cc122014-03-19 19:26:02 +010031#include <cstring> // for std::strncpy()
Davide Pesavento44deacc2014-02-19 10:48:07 +010032#include <arpa/inet.h> // for htons() and ntohs()
33#include <net/ethernet.h> // for struct ether_header
34#include <net/if.h> // for struct ifreq
35#include <stdio.h> // for snprintf()
36#include <sys/ioctl.h> // for ioctl()
37#include <unistd.h> // for dup()
38
Alexander Afanasyevd9479aa2014-06-26 13:52:02 -070039#if !defined(PCAP_NETMASK_UNKNOWN)
40/*
41 * Value to pass to pcap_compile() as the netmask if you don't know what
42 * the netmask is.
43 */
44#define PCAP_NETMASK_UNKNOWN 0xffffffff
45#endif
46
Davide Pesavento44deacc2014-02-19 10:48:07 +010047namespace nfd {
48
Davide Pesavento1bdef282014-04-08 20:59:50 +020049NFD_LOG_INIT("EthernetFace");
Davide Pesavento44deacc2014-02-19 10:48:07 +010050
Davide Pesavento44deacc2014-02-19 10:48:07 +010051EthernetFace::EthernetFace(const shared_ptr<boost::asio::posix::stream_descriptor>& socket,
Davide Pesaventob60cc122014-03-19 19:26:02 +010052 const shared_ptr<NetworkInterfaceInfo>& interface,
Davide Pesavento44deacc2014-02-19 10:48:07 +010053 const ethernet::Address& address)
Junxiao Shi79494162014-04-02 18:25:11 -070054 : Face(FaceUri(address), FaceUri::fromDev(interface->name))
Alexander Afanasyeva39b90b2014-03-05 15:31:00 +000055 , m_socket(socket)
Davide Pesaventob60cc122014-03-19 19:26:02 +010056 , m_interfaceName(interface->name)
57 , m_srcAddress(interface->etherAddress)
Davide Pesavento44deacc2014-02-19 10:48:07 +010058 , m_destAddress(address)
59{
Davide Pesaventob60cc122014-03-19 19:26:02 +010060 NFD_LOG_INFO("Creating ethernet face on " << m_interfaceName << ": "
61 << m_srcAddress << " <--> " << m_destAddress);
Davide Pesavento44deacc2014-02-19 10:48:07 +010062 pcapInit();
63
64 int fd = pcap_get_selectable_fd(m_pcap);
65 if (fd < 0)
66 throw Error("pcap_get_selectable_fd() failed");
67
68 // need to duplicate the fd, otherwise both pcap_close()
69 // and stream_descriptor::close() will try to close the
70 // same fd and one of them will fail
71 m_socket->assign(::dup(fd));
72
Davide Pesavento44deacc2014-02-19 10:48:07 +010073 m_interfaceMtu = getInterfaceMtu();
Davide Pesaventob60cc122014-03-19 19:26:02 +010074 NFD_LOG_DEBUG("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +010075 << "] Interface MTU is: " << m_interfaceMtu);
76
77 char filter[100];
78 ::snprintf(filter, sizeof(filter),
79 "(ether proto 0x%x) && (ether dst %s) && (not ether src %s)",
Junxiao Shi3ffe66d2014-11-06 15:37:59 -070080 ethernet::ETHERTYPE_NDN,
Davide Pesaventoedae3532014-04-09 03:07:11 +020081 m_destAddress.toString().c_str(),
82 m_srcAddress.toString().c_str());
Davide Pesavento44deacc2014-02-19 10:48:07 +010083 setPacketFilter(filter);
84
85 m_socket->async_read_some(boost::asio::null_buffers(),
86 bind(&EthernetFace::handleRead, this,
87 boost::asio::placeholders::error,
88 boost::asio::placeholders::bytes_transferred));
89}
90
91EthernetFace::~EthernetFace()
92{
Alexander Afanasyev251f3c12014-06-02 18:39:58 +030093 onFail.clear(); // no reason to call onFail anymore
Davide Pesavento44deacc2014-02-19 10:48:07 +010094 close();
95}
96
97void
98EthernetFace::sendInterest(const Interest& interest)
99{
Alexander Afanasyev7e698e62014-03-07 16:48:35 +0000100 onSendInterest(interest);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100101 sendPacket(interest.wireEncode());
102}
103
104void
105EthernetFace::sendData(const Data& data)
106{
Alexander Afanasyev7e698e62014-03-07 16:48:35 +0000107 onSendData(data);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100108 sendPacket(data.wireEncode());
109}
110
111void
112EthernetFace::close()
113{
114 if (m_pcap)
115 {
116 boost::system::error_code error;
117 m_socket->close(error); // ignore errors
118 pcap_close(m_pcap);
119 m_pcap = 0;
Alexander Afanasyev251f3c12014-06-02 18:39:58 +0300120
Junxiao Shi08d07a72014-06-09 23:17:57 -0700121 fail("Face closed");
Davide Pesavento44deacc2014-02-19 10:48:07 +0100122 }
123}
124
125void
126EthernetFace::pcapInit()
127{
Davide Pesavento44deacc2014-02-19 10:48:07 +0100128 char errbuf[PCAP_ERRBUF_SIZE];
129 errbuf[0] = '\0';
Davide Pesaventob60cc122014-03-19 19:26:02 +0100130 m_pcap = pcap_create(m_interfaceName.c_str(), errbuf);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100131 if (!m_pcap)
132 throw Error("pcap_create(): " + std::string(errbuf));
133
Davide Pesaventof0ae4422014-05-05 16:32:12 +0200134#ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
135 // Enable "immediate mode", effectively disabling any read buffering in the kernel.
136 // This corresponds to the BIOCIMMEDIATE ioctl on BSD-like systems (including OS X)
137 // where libpcap uses a BPF device. On Linux this forces libpcap not to use TPACKET_V3,
138 // even if the kernel supports it, thus preventing bug #1511.
139 pcap_set_immediate_mode(m_pcap, 1);
140#endif
141
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100142 /// \todo Do not rely on promisc mode, see task #1278
143 if (!m_destAddress.isBroadcast())
144 pcap_set_promisc(m_pcap, 1);
145
Davide Pesavento44deacc2014-02-19 10:48:07 +0100146 if (pcap_activate(m_pcap) < 0)
147 throw Error("pcap_activate() failed");
148
Davide Pesavento44deacc2014-02-19 10:48:07 +0100149 if (pcap_set_datalink(m_pcap, DLT_EN10MB) < 0)
150 throw Error("pcap_set_datalink(): " + std::string(pcap_geterr(m_pcap)));
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100151
152 if (pcap_setdirection(m_pcap, PCAP_D_IN) < 0)
153 // no need to throw on failure, BPF will filter unwanted packets anyway
154 NFD_LOG_WARN("pcap_setdirection(): " << pcap_geterr(m_pcap));
Davide Pesavento44deacc2014-02-19 10:48:07 +0100155}
156
157void
158EthernetFace::setPacketFilter(const char* filterString)
159{
160 bpf_program filter;
161 if (pcap_compile(m_pcap, &filter, filterString, 1, PCAP_NETMASK_UNKNOWN) < 0)
162 throw Error("pcap_compile(): " + std::string(pcap_geterr(m_pcap)));
163
164 int ret = pcap_setfilter(m_pcap, &filter);
165 pcap_freecode(&filter);
166 if (ret < 0)
167 throw Error("pcap_setfilter(): " + std::string(pcap_geterr(m_pcap)));
168}
169
170void
171EthernetFace::sendPacket(const ndn::Block& block)
172{
173 if (!m_pcap)
174 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100175 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +0100176 << "] Trying to send on closed face");
Junxiao Shi08d07a72014-06-09 23:17:57 -0700177 fail("Face closed");
Davide Pesavento44deacc2014-02-19 10:48:07 +0100178 return;
179 }
180
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100181 /// \todo Fragmentation
Davide Pesavento44deacc2014-02-19 10:48:07 +0100182 if (block.size() > m_interfaceMtu)
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100183 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100184 NFD_LOG_ERROR("[id:" << getId() << ",endpoint:" << m_interfaceName
185 << "] Fragmentation not implemented: dropping packet larger than MTU");
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100186 return;
187 }
Davide Pesavento44deacc2014-02-19 10:48:07 +0100188
189 /// \todo Right now there is no reserve when packet is received, but
190 /// we should reserve some space at the beginning and at the end
191 ndn::EncodingBuffer buffer(block);
192
Davide Pesaventoe4631002014-03-21 20:55:36 +0100193 // pad with zeroes if the payload is too short
Davide Pesavento44deacc2014-02-19 10:48:07 +0100194 if (block.size() < ethernet::MIN_DATA_LEN)
195 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100196 static const uint8_t padding[ethernet::MIN_DATA_LEN] = {0};
197 buffer.appendByteArray(padding, ethernet::MIN_DATA_LEN - block.size());
Davide Pesavento44deacc2014-02-19 10:48:07 +0100198 }
199
200 // construct and prepend the ethernet header
Junxiao Shi3ffe66d2014-11-06 15:37:59 -0700201 static uint16_t ethertype = htons(ethernet::ETHERTYPE_NDN);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100202 buffer.prependByteArray(reinterpret_cast<const uint8_t*>(&ethertype), ethernet::TYPE_LEN);
Davide Pesaventob60cc122014-03-19 19:26:02 +0100203 buffer.prependByteArray(m_srcAddress.data(), m_srcAddress.size());
Davide Pesavento44deacc2014-02-19 10:48:07 +0100204 buffer.prependByteArray(m_destAddress.data(), m_destAddress.size());
205
206 // send the packet
207 int sent = pcap_inject(m_pcap, buffer.buf(), buffer.size());
208 if (sent < 0)
209 {
210 throw Error("pcap_inject(): " + std::string(pcap_geterr(m_pcap)));
211 }
212 else if (static_cast<size_t>(sent) < buffer.size())
213 {
214 throw Error("Failed to send packet");
215 }
216
Davide Pesaventob60cc122014-03-19 19:26:02 +0100217 NFD_LOG_TRACE("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento4c1a0782014-08-14 16:13:20 +0200218 << "] Successfully sent: " << block.size() << " bytes");
219 this->getMutableCounters().getNOutBytes() += block.size();
Davide Pesavento44deacc2014-02-19 10:48:07 +0100220}
221
222void
223EthernetFace::handleRead(const boost::system::error_code& error, size_t)
224{
225 if (error)
226 return processErrorCode(error);
227
228 pcap_pkthdr* pktHeader;
229 const uint8_t* packet;
230 int ret = pcap_next_ex(m_pcap, &pktHeader, &packet);
231 if (ret < 0)
232 {
233 throw Error("pcap_next_ex(): " + std::string(pcap_geterr(m_pcap)));
234 }
235 else if (ret == 0)
236 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100237 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +0100238 << "] pcap_next_ex() timed out");
239 }
240 else
241 {
242 size_t length = pktHeader->caplen;
243 if (length < ethernet::HDR_LEN + ethernet::MIN_DATA_LEN)
244 throw Error("Received packet is too short");
245
246 const ether_header* eh = reinterpret_cast<const ether_header*>(packet);
Junxiao Shi3ffe66d2014-11-06 15:37:59 -0700247 if (ntohs(eh->ether_type) != ethernet::ETHERTYPE_NDN)
Davide Pesavento44deacc2014-02-19 10:48:07 +0100248 throw Error("Unrecognized ethertype");
249
250 packet += ethernet::HDR_LEN;
251 length -= ethernet::HDR_LEN;
Davide Pesavento44deacc2014-02-19 10:48:07 +0100252
Alexander Afanasyev5a8d8d82014-03-21 14:08:41 -0700253 /// \todo Reserve space in front and at the back
254 /// of the underlying buffer
255 Block element;
256 bool isOk = Block::fromBuffer(packet, length, element);
257 if (isOk)
258 {
Davide Pesavento4c1a0782014-08-14 16:13:20 +0200259 NFD_LOG_TRACE("[id:" << getId() << ",endpoint:" << m_interfaceName
260 << "] Received: " << element.size() << " bytes");
261 this->getMutableCounters().getNInBytes() += element.size();
262
Alexander Afanasyev5a8d8d82014-03-21 14:08:41 -0700263 if (!decodeAndDispatchInput(element))
264 {
265 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
266 << "] Received unrecognized block of type " << element.type());
267 // ignore unknown packet
268 }
269 }
270 else
271 {
272 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
273 << "] Received block is invalid or too large to process");
274 }
Davide Pesavento44deacc2014-02-19 10:48:07 +0100275 }
276
277 m_socket->async_read_some(boost::asio::null_buffers(),
278 bind(&EthernetFace::handleRead, this,
279 boost::asio::placeholders::error,
280 boost::asio::placeholders::bytes_transferred));
281}
282
283void
284EthernetFace::processErrorCode(const boost::system::error_code& error)
285{
286 if (error == boost::system::errc::operation_canceled)
287 // when socket is closed by someone
288 return;
289
290 if (!m_pcap)
291 {
Junxiao Shi08d07a72014-06-09 23:17:57 -0700292 fail("Face closed");
Davide Pesavento44deacc2014-02-19 10:48:07 +0100293 return;
294 }
295
296 std::string msg;
297 if (error == boost::asio::error::eof)
298 {
299 msg = "Face closed";
Davide Pesaventob60cc122014-03-19 19:26:02 +0100300 NFD_LOG_INFO("[id:" << getId() << ",endpoint:" << m_interfaceName << "] " << msg);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100301 }
302 else
303 {
Davide Pesavento4c1a0782014-08-14 16:13:20 +0200304 msg = "Receive operation failed, closing face: " + error.message();
Davide Pesaventob60cc122014-03-19 19:26:02 +0100305 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName << "] " << msg);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100306 }
307
308 close();
Junxiao Shi08d07a72014-06-09 23:17:57 -0700309 fail(msg);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100310}
311
Davide Pesavento44deacc2014-02-19 10:48:07 +0100312size_t
313EthernetFace::getInterfaceMtu() const
314{
315 size_t mtu = ethernet::MAX_DATA_LEN;
316
317#ifdef SIOCGIFMTU
Alexander Afanasyevf4e89b42014-05-31 15:54:18 +0300318 ifreq ifr = boost::initialized_value;
Davide Pesaventob60cc122014-03-19 19:26:02 +0100319 std::strncpy(ifr.ifr_name, m_interfaceName.c_str(), sizeof(ifr.ifr_name) - 1);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100320
321 if (::ioctl(m_socket->native_handle(), SIOCGIFMTU, &ifr) < 0)
322 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100323 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +0100324 << "] Failed to get interface MTU, assuming " << mtu);
325 }
326 else
327 {
328 mtu = std::min(mtu, static_cast<size_t>(ifr.ifr_mtu));
329 }
330#endif
331
332 return mtu;
333}
334
335} // namespace nfd