blob: f51a8ae2ee6e13ca6ab673381a82d3c9490df269 [file] [log] [blame]
Davide Pesavento44deacc2014-02-19 10:48:07 +01001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2/**
Alexander Afanasyev9bcbc7c2014-04-06 19:37:37 -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 *
10 * This file is part of NFD (Named Data Networking Forwarding Daemon).
11 * See AUTHORS.md for complete list of NFD authors and contributors.
12 *
13 * NFD is free software: you can redistribute it and/or modify it under the terms
14 * of the GNU General Public License as published by the Free Software Foundation,
15 * either version 3 of the License, or (at your option) any later version.
16 *
17 * NFD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
18 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
19 * PURPOSE. See the GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License along with
22 * NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
23 **/
Davide Pesavento44deacc2014-02-19 10:48:07 +010024
25#include "ethernet-face.hpp"
Steve DiBenedettobf6a93d2014-03-21 14:03:02 -060026#include "core/logger.hpp"
Davide Pesaventob60cc122014-03-19 19:26:02 +010027#include "core/network-interface.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
Davide Pesavento44deacc2014-02-19 10:48:07 +010039namespace nfd {
40
Davide Pesavento1bdef282014-04-08 20:59:50 +020041NFD_LOG_INIT("EthernetFace");
Davide Pesavento44deacc2014-02-19 10:48:07 +010042
Davide Pesavento44deacc2014-02-19 10:48:07 +010043EthernetFace::EthernetFace(const shared_ptr<boost::asio::posix::stream_descriptor>& socket,
Davide Pesaventob60cc122014-03-19 19:26:02 +010044 const shared_ptr<NetworkInterfaceInfo>& interface,
Davide Pesavento44deacc2014-02-19 10:48:07 +010045 const ethernet::Address& address)
Junxiao Shi79494162014-04-02 18:25:11 -070046 : Face(FaceUri(address), FaceUri::fromDev(interface->name))
Alexander Afanasyeva39b90b2014-03-05 15:31:00 +000047 , m_socket(socket)
Davide Pesaventob60cc122014-03-19 19:26:02 +010048 , m_interfaceName(interface->name)
49 , m_srcAddress(interface->etherAddress)
Davide Pesavento44deacc2014-02-19 10:48:07 +010050 , m_destAddress(address)
51{
Davide Pesaventob60cc122014-03-19 19:26:02 +010052 NFD_LOG_INFO("Creating ethernet face on " << m_interfaceName << ": "
53 << m_srcAddress << " <--> " << m_destAddress);
Davide Pesavento44deacc2014-02-19 10:48:07 +010054 pcapInit();
55
56 int fd = pcap_get_selectable_fd(m_pcap);
57 if (fd < 0)
58 throw Error("pcap_get_selectable_fd() failed");
59
60 // need to duplicate the fd, otherwise both pcap_close()
61 // and stream_descriptor::close() will try to close the
62 // same fd and one of them will fail
63 m_socket->assign(::dup(fd));
64
Davide Pesavento44deacc2014-02-19 10:48:07 +010065 m_interfaceMtu = getInterfaceMtu();
Davide Pesaventob60cc122014-03-19 19:26:02 +010066 NFD_LOG_DEBUG("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +010067 << "] Interface MTU is: " << m_interfaceMtu);
68
69 char filter[100];
70 ::snprintf(filter, sizeof(filter),
71 "(ether proto 0x%x) && (ether dst %s) && (not ether src %s)",
72 ETHERTYPE_NDN,
Davide Pesaventoedae3532014-04-09 03:07:11 +020073 m_destAddress.toString().c_str(),
74 m_srcAddress.toString().c_str());
Davide Pesavento44deacc2014-02-19 10:48:07 +010075 setPacketFilter(filter);
76
77 m_socket->async_read_some(boost::asio::null_buffers(),
78 bind(&EthernetFace::handleRead, this,
79 boost::asio::placeholders::error,
80 boost::asio::placeholders::bytes_transferred));
81}
82
83EthernetFace::~EthernetFace()
84{
85 close();
86}
87
88void
89EthernetFace::sendInterest(const Interest& interest)
90{
Alexander Afanasyev7e698e62014-03-07 16:48:35 +000091 onSendInterest(interest);
Davide Pesavento44deacc2014-02-19 10:48:07 +010092 sendPacket(interest.wireEncode());
93}
94
95void
96EthernetFace::sendData(const Data& data)
97{
Alexander Afanasyev7e698e62014-03-07 16:48:35 +000098 onSendData(data);
Davide Pesavento44deacc2014-02-19 10:48:07 +010099 sendPacket(data.wireEncode());
100}
101
102void
103EthernetFace::close()
104{
105 if (m_pcap)
106 {
107 boost::system::error_code error;
108 m_socket->close(error); // ignore errors
109 pcap_close(m_pcap);
110 m_pcap = 0;
111 }
112}
113
114void
115EthernetFace::pcapInit()
116{
Davide Pesavento44deacc2014-02-19 10:48:07 +0100117 char errbuf[PCAP_ERRBUF_SIZE];
118 errbuf[0] = '\0';
Davide Pesaventob60cc122014-03-19 19:26:02 +0100119 m_pcap = pcap_create(m_interfaceName.c_str(), errbuf);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100120 if (!m_pcap)
121 throw Error("pcap_create(): " + std::string(errbuf));
122
Davide Pesaventof0ae4422014-05-05 16:32:12 +0200123#ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
124 // Enable "immediate mode", effectively disabling any read buffering in the kernel.
125 // This corresponds to the BIOCIMMEDIATE ioctl on BSD-like systems (including OS X)
126 // where libpcap uses a BPF device. On Linux this forces libpcap not to use TPACKET_V3,
127 // even if the kernel supports it, thus preventing bug #1511.
128 pcap_set_immediate_mode(m_pcap, 1);
129#endif
130
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100131 /// \todo Do not rely on promisc mode, see task #1278
132 if (!m_destAddress.isBroadcast())
133 pcap_set_promisc(m_pcap, 1);
134
Davide Pesavento44deacc2014-02-19 10:48:07 +0100135 if (pcap_activate(m_pcap) < 0)
136 throw Error("pcap_activate() failed");
137
Davide Pesavento44deacc2014-02-19 10:48:07 +0100138 if (pcap_set_datalink(m_pcap, DLT_EN10MB) < 0)
139 throw Error("pcap_set_datalink(): " + std::string(pcap_geterr(m_pcap)));
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100140
141 if (pcap_setdirection(m_pcap, PCAP_D_IN) < 0)
142 // no need to throw on failure, BPF will filter unwanted packets anyway
143 NFD_LOG_WARN("pcap_setdirection(): " << pcap_geterr(m_pcap));
Davide Pesavento44deacc2014-02-19 10:48:07 +0100144}
145
146void
147EthernetFace::setPacketFilter(const char* filterString)
148{
149 bpf_program filter;
150 if (pcap_compile(m_pcap, &filter, filterString, 1, PCAP_NETMASK_UNKNOWN) < 0)
151 throw Error("pcap_compile(): " + std::string(pcap_geterr(m_pcap)));
152
153 int ret = pcap_setfilter(m_pcap, &filter);
154 pcap_freecode(&filter);
155 if (ret < 0)
156 throw Error("pcap_setfilter(): " + std::string(pcap_geterr(m_pcap)));
157}
158
159void
160EthernetFace::sendPacket(const ndn::Block& block)
161{
162 if (!m_pcap)
163 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100164 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +0100165 << "] Trying to send on closed face");
166 onFail("Face closed");
167 return;
168 }
169
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100170 /// \todo Fragmentation
Davide Pesavento44deacc2014-02-19 10:48:07 +0100171 if (block.size() > m_interfaceMtu)
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100172 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100173 NFD_LOG_ERROR("[id:" << getId() << ",endpoint:" << m_interfaceName
174 << "] Fragmentation not implemented: dropping packet larger than MTU");
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100175 return;
176 }
Davide Pesavento44deacc2014-02-19 10:48:07 +0100177
178 /// \todo Right now there is no reserve when packet is received, but
179 /// we should reserve some space at the beginning and at the end
180 ndn::EncodingBuffer buffer(block);
181
Davide Pesaventoe4631002014-03-21 20:55:36 +0100182 // pad with zeroes if the payload is too short
Davide Pesavento44deacc2014-02-19 10:48:07 +0100183 if (block.size() < ethernet::MIN_DATA_LEN)
184 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100185 static const uint8_t padding[ethernet::MIN_DATA_LEN] = {0};
186 buffer.appendByteArray(padding, ethernet::MIN_DATA_LEN - block.size());
Davide Pesavento44deacc2014-02-19 10:48:07 +0100187 }
188
189 // construct and prepend the ethernet header
190 static uint16_t ethertype = htons(ETHERTYPE_NDN);
191 buffer.prependByteArray(reinterpret_cast<const uint8_t*>(&ethertype), ethernet::TYPE_LEN);
Davide Pesaventob60cc122014-03-19 19:26:02 +0100192 buffer.prependByteArray(m_srcAddress.data(), m_srcAddress.size());
Davide Pesavento44deacc2014-02-19 10:48:07 +0100193 buffer.prependByteArray(m_destAddress.data(), m_destAddress.size());
194
195 // send the packet
196 int sent = pcap_inject(m_pcap, buffer.buf(), buffer.size());
197 if (sent < 0)
198 {
199 throw Error("pcap_inject(): " + std::string(pcap_geterr(m_pcap)));
200 }
201 else if (static_cast<size_t>(sent) < buffer.size())
202 {
203 throw Error("Failed to send packet");
204 }
205
Davide Pesaventob60cc122014-03-19 19:26:02 +0100206 NFD_LOG_TRACE("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +0100207 << "] Successfully sent: " << buffer.size() << " bytes");
208}
209
210void
211EthernetFace::handleRead(const boost::system::error_code& error, size_t)
212{
213 if (error)
214 return processErrorCode(error);
215
216 pcap_pkthdr* pktHeader;
217 const uint8_t* packet;
218 int ret = pcap_next_ex(m_pcap, &pktHeader, &packet);
219 if (ret < 0)
220 {
221 throw Error("pcap_next_ex(): " + std::string(pcap_geterr(m_pcap)));
222 }
223 else if (ret == 0)
224 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100225 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +0100226 << "] pcap_next_ex() timed out");
227 }
228 else
229 {
230 size_t length = pktHeader->caplen;
231 if (length < ethernet::HDR_LEN + ethernet::MIN_DATA_LEN)
232 throw Error("Received packet is too short");
233
234 const ether_header* eh = reinterpret_cast<const ether_header*>(packet);
235 if (ntohs(eh->ether_type) != ETHERTYPE_NDN)
236 throw Error("Unrecognized ethertype");
237
238 packet += ethernet::HDR_LEN;
239 length -= ethernet::HDR_LEN;
Davide Pesaventob60cc122014-03-19 19:26:02 +0100240 NFD_LOG_TRACE("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +0100241 << "] Received: " << length << " bytes");
242
Alexander Afanasyev5a8d8d82014-03-21 14:08:41 -0700243 /// \todo Reserve space in front and at the back
244 /// of the underlying buffer
245 Block element;
246 bool isOk = Block::fromBuffer(packet, length, element);
247 if (isOk)
248 {
249 if (!decodeAndDispatchInput(element))
250 {
251 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
252 << "] Received unrecognized block of type " << element.type());
253 // ignore unknown packet
254 }
255 }
256 else
257 {
258 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
259 << "] Received block is invalid or too large to process");
260 }
Davide Pesavento44deacc2014-02-19 10:48:07 +0100261 }
262
263 m_socket->async_read_some(boost::asio::null_buffers(),
264 bind(&EthernetFace::handleRead, this,
265 boost::asio::placeholders::error,
266 boost::asio::placeholders::bytes_transferred));
267}
268
269void
270EthernetFace::processErrorCode(const boost::system::error_code& error)
271{
272 if (error == boost::system::errc::operation_canceled)
273 // when socket is closed by someone
274 return;
275
276 if (!m_pcap)
277 {
278 onFail("Face closed");
279 return;
280 }
281
282 std::string msg;
283 if (error == boost::asio::error::eof)
284 {
285 msg = "Face closed";
Davide Pesaventob60cc122014-03-19 19:26:02 +0100286 NFD_LOG_INFO("[id:" << getId() << ",endpoint:" << m_interfaceName << "] " << msg);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100287 }
288 else
289 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100290 msg = "Receive operation failed, closing face: " + error.category().message(error.value());
291 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName << "] " << msg);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100292 }
293
294 close();
295 onFail(msg);
296}
297
Davide Pesavento44deacc2014-02-19 10:48:07 +0100298size_t
299EthernetFace::getInterfaceMtu() const
300{
301 size_t mtu = ethernet::MAX_DATA_LEN;
302
303#ifdef SIOCGIFMTU
Davide Pesaventoe4631002014-03-21 20:55:36 +0100304 ifreq ifr = {};
Davide Pesaventob60cc122014-03-19 19:26:02 +0100305 std::strncpy(ifr.ifr_name, m_interfaceName.c_str(), sizeof(ifr.ifr_name) - 1);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100306
307 if (::ioctl(m_socket->native_handle(), SIOCGIFMTU, &ifr) < 0)
308 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100309 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +0100310 << "] Failed to get interface MTU, assuming " << mtu);
311 }
312 else
313 {
314 mtu = std::min(mtu, static_cast<size_t>(ifr.ifr_mtu));
315 }
316#endif
317
318 return mtu;
319}
320
321} // namespace nfd