blob: 66dcf08d3257c16ee8d8f23b5046b4dfaaa4e9a4 [file] [log] [blame]
Davide Pesavento44deacc2014-02-19 10:48:07 +01001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2/**
3 * Copyright (C) 2014 Named Data Networking Project
4 * See COPYING for copyright and distribution information.
5 */
6
7#include "ethernet-face.hpp"
Steve DiBenedettobf6a93d2014-03-21 14:03:02 -06008#include "core/logger.hpp"
Davide Pesaventob60cc122014-03-19 19:26:02 +01009#include "core/network-interface.hpp"
Davide Pesavento44deacc2014-02-19 10:48:07 +010010
11#include <pcap/pcap.h>
12
Davide Pesaventob60cc122014-03-19 19:26:02 +010013#include <cstring> // for std::strncpy()
Davide Pesavento44deacc2014-02-19 10:48:07 +010014#include <arpa/inet.h> // for htons() and ntohs()
15#include <net/ethernet.h> // for struct ether_header
16#include <net/if.h> // for struct ifreq
17#include <stdio.h> // for snprintf()
18#include <sys/ioctl.h> // for ioctl()
19#include <unistd.h> // for dup()
20
Davide Pesavento44deacc2014-02-19 10:48:07 +010021namespace nfd {
22
23NFD_LOG_INIT("EthernetFace")
24
Davide Pesavento44deacc2014-02-19 10:48:07 +010025EthernetFace::EthernetFace(const shared_ptr<boost::asio::posix::stream_descriptor>& socket,
Davide Pesaventob60cc122014-03-19 19:26:02 +010026 const shared_ptr<NetworkInterfaceInfo>& interface,
Davide Pesavento44deacc2014-02-19 10:48:07 +010027 const ethernet::Address& address)
Davide Pesaventob60cc122014-03-19 19:26:02 +010028 : Face(FaceUri("ether://" + interface->name + "/" + address.toString(':')))
Alexander Afanasyeva39b90b2014-03-05 15:31:00 +000029 , m_socket(socket)
Davide Pesaventob60cc122014-03-19 19:26:02 +010030 , m_interfaceName(interface->name)
31 , m_srcAddress(interface->etherAddress)
Davide Pesavento44deacc2014-02-19 10:48:07 +010032 , m_destAddress(address)
33{
Davide Pesaventob60cc122014-03-19 19:26:02 +010034 NFD_LOG_INFO("Creating ethernet face on " << m_interfaceName << ": "
35 << m_srcAddress << " <--> " << m_destAddress);
Davide Pesavento44deacc2014-02-19 10:48:07 +010036 pcapInit();
37
38 int fd = pcap_get_selectable_fd(m_pcap);
39 if (fd < 0)
40 throw Error("pcap_get_selectable_fd() failed");
41
42 // need to duplicate the fd, otherwise both pcap_close()
43 // and stream_descriptor::close() will try to close the
44 // same fd and one of them will fail
45 m_socket->assign(::dup(fd));
46
Davide Pesavento44deacc2014-02-19 10:48:07 +010047 m_interfaceMtu = getInterfaceMtu();
Davide Pesaventob60cc122014-03-19 19:26:02 +010048 NFD_LOG_DEBUG("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +010049 << "] Interface MTU is: " << m_interfaceMtu);
50
51 char filter[100];
52 ::snprintf(filter, sizeof(filter),
53 "(ether proto 0x%x) && (ether dst %s) && (not ether src %s)",
54 ETHERTYPE_NDN,
55 m_destAddress.toString(':').c_str(),
Davide Pesaventob60cc122014-03-19 19:26:02 +010056 m_srcAddress.toString(':').c_str());
Davide Pesavento44deacc2014-02-19 10:48:07 +010057 setPacketFilter(filter);
58
59 m_socket->async_read_some(boost::asio::null_buffers(),
60 bind(&EthernetFace::handleRead, this,
61 boost::asio::placeholders::error,
62 boost::asio::placeholders::bytes_transferred));
63}
64
65EthernetFace::~EthernetFace()
66{
67 close();
68}
69
70void
71EthernetFace::sendInterest(const Interest& interest)
72{
Alexander Afanasyev7e698e62014-03-07 16:48:35 +000073 onSendInterest(interest);
Davide Pesavento44deacc2014-02-19 10:48:07 +010074 sendPacket(interest.wireEncode());
75}
76
77void
78EthernetFace::sendData(const Data& data)
79{
Alexander Afanasyev7e698e62014-03-07 16:48:35 +000080 onSendData(data);
Davide Pesavento44deacc2014-02-19 10:48:07 +010081 sendPacket(data.wireEncode());
82}
83
84void
85EthernetFace::close()
86{
87 if (m_pcap)
88 {
89 boost::system::error_code error;
90 m_socket->close(error); // ignore errors
91 pcap_close(m_pcap);
92 m_pcap = 0;
93 }
94}
95
96void
97EthernetFace::pcapInit()
98{
Davide Pesavento44deacc2014-02-19 10:48:07 +010099 char errbuf[PCAP_ERRBUF_SIZE];
100 errbuf[0] = '\0';
Davide Pesaventob60cc122014-03-19 19:26:02 +0100101 m_pcap = pcap_create(m_interfaceName.c_str(), errbuf);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100102 if (!m_pcap)
103 throw Error("pcap_create(): " + std::string(errbuf));
104
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100105 /// \todo Do not rely on promisc mode, see task #1278
106 if (!m_destAddress.isBroadcast())
107 pcap_set_promisc(m_pcap, 1);
108
Davide Pesavento44deacc2014-02-19 10:48:07 +0100109 if (pcap_activate(m_pcap) < 0)
110 throw Error("pcap_activate() failed");
111
Davide Pesavento44deacc2014-02-19 10:48:07 +0100112 if (pcap_set_datalink(m_pcap, DLT_EN10MB) < 0)
113 throw Error("pcap_set_datalink(): " + std::string(pcap_geterr(m_pcap)));
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100114
115 if (pcap_setdirection(m_pcap, PCAP_D_IN) < 0)
116 // no need to throw on failure, BPF will filter unwanted packets anyway
117 NFD_LOG_WARN("pcap_setdirection(): " << pcap_geterr(m_pcap));
Davide Pesavento44deacc2014-02-19 10:48:07 +0100118}
119
120void
121EthernetFace::setPacketFilter(const char* filterString)
122{
123 bpf_program filter;
124 if (pcap_compile(m_pcap, &filter, filterString, 1, PCAP_NETMASK_UNKNOWN) < 0)
125 throw Error("pcap_compile(): " + std::string(pcap_geterr(m_pcap)));
126
127 int ret = pcap_setfilter(m_pcap, &filter);
128 pcap_freecode(&filter);
129 if (ret < 0)
130 throw Error("pcap_setfilter(): " + std::string(pcap_geterr(m_pcap)));
131}
132
133void
134EthernetFace::sendPacket(const ndn::Block& block)
135{
136 if (!m_pcap)
137 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100138 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +0100139 << "] Trying to send on closed face");
140 onFail("Face closed");
141 return;
142 }
143
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100144 /// \todo Fragmentation
Davide Pesavento44deacc2014-02-19 10:48:07 +0100145 if (block.size() > m_interfaceMtu)
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100146 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100147 NFD_LOG_ERROR("[id:" << getId() << ",endpoint:" << m_interfaceName
148 << "] Fragmentation not implemented: dropping packet larger than MTU");
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100149 return;
150 }
Davide Pesavento44deacc2014-02-19 10:48:07 +0100151
152 /// \todo Right now there is no reserve when packet is received, but
153 /// we should reserve some space at the beginning and at the end
154 ndn::EncodingBuffer buffer(block);
155
Davide Pesaventoe4631002014-03-21 20:55:36 +0100156 // pad with zeroes if the payload is too short
Davide Pesavento44deacc2014-02-19 10:48:07 +0100157 if (block.size() < ethernet::MIN_DATA_LEN)
158 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100159 static const uint8_t padding[ethernet::MIN_DATA_LEN] = {0};
160 buffer.appendByteArray(padding, ethernet::MIN_DATA_LEN - block.size());
Davide Pesavento44deacc2014-02-19 10:48:07 +0100161 }
162
163 // construct and prepend the ethernet header
164 static uint16_t ethertype = htons(ETHERTYPE_NDN);
165 buffer.prependByteArray(reinterpret_cast<const uint8_t*>(&ethertype), ethernet::TYPE_LEN);
Davide Pesaventob60cc122014-03-19 19:26:02 +0100166 buffer.prependByteArray(m_srcAddress.data(), m_srcAddress.size());
Davide Pesavento44deacc2014-02-19 10:48:07 +0100167 buffer.prependByteArray(m_destAddress.data(), m_destAddress.size());
168
169 // send the packet
170 int sent = pcap_inject(m_pcap, buffer.buf(), buffer.size());
171 if (sent < 0)
172 {
173 throw Error("pcap_inject(): " + std::string(pcap_geterr(m_pcap)));
174 }
175 else if (static_cast<size_t>(sent) < buffer.size())
176 {
177 throw Error("Failed to send packet");
178 }
179
Davide Pesaventob60cc122014-03-19 19:26:02 +0100180 NFD_LOG_TRACE("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +0100181 << "] Successfully sent: " << buffer.size() << " bytes");
182}
183
184void
185EthernetFace::handleRead(const boost::system::error_code& error, size_t)
186{
187 if (error)
188 return processErrorCode(error);
189
190 pcap_pkthdr* pktHeader;
191 const uint8_t* packet;
192 int ret = pcap_next_ex(m_pcap, &pktHeader, &packet);
193 if (ret < 0)
194 {
195 throw Error("pcap_next_ex(): " + std::string(pcap_geterr(m_pcap)));
196 }
197 else if (ret == 0)
198 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100199 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +0100200 << "] pcap_next_ex() timed out");
201 }
202 else
203 {
204 size_t length = pktHeader->caplen;
205 if (length < ethernet::HDR_LEN + ethernet::MIN_DATA_LEN)
206 throw Error("Received packet is too short");
207
208 const ether_header* eh = reinterpret_cast<const ether_header*>(packet);
209 if (ntohs(eh->ether_type) != ETHERTYPE_NDN)
210 throw Error("Unrecognized ethertype");
211
212 packet += ethernet::HDR_LEN;
213 length -= ethernet::HDR_LEN;
Davide Pesaventob60cc122014-03-19 19:26:02 +0100214 NFD_LOG_TRACE("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +0100215 << "] Received: " << length << " bytes");
216
Alexander Afanasyev5a8d8d82014-03-21 14:08:41 -0700217 /// \todo Reserve space in front and at the back
218 /// of the underlying buffer
219 Block element;
220 bool isOk = Block::fromBuffer(packet, length, element);
221 if (isOk)
222 {
223 if (!decodeAndDispatchInput(element))
224 {
225 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
226 << "] Received unrecognized block of type " << element.type());
227 // ignore unknown packet
228 }
229 }
230 else
231 {
232 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
233 << "] Received block is invalid or too large to process");
234 }
Davide Pesavento44deacc2014-02-19 10:48:07 +0100235 }
236
237 m_socket->async_read_some(boost::asio::null_buffers(),
238 bind(&EthernetFace::handleRead, this,
239 boost::asio::placeholders::error,
240 boost::asio::placeholders::bytes_transferred));
241}
242
243void
244EthernetFace::processErrorCode(const boost::system::error_code& error)
245{
246 if (error == boost::system::errc::operation_canceled)
247 // when socket is closed by someone
248 return;
249
250 if (!m_pcap)
251 {
252 onFail("Face closed");
253 return;
254 }
255
256 std::string msg;
257 if (error == boost::asio::error::eof)
258 {
259 msg = "Face closed";
Davide Pesaventob60cc122014-03-19 19:26:02 +0100260 NFD_LOG_INFO("[id:" << getId() << ",endpoint:" << m_interfaceName << "] " << msg);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100261 }
262 else
263 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100264 msg = "Receive operation failed, closing face: " + error.category().message(error.value());
265 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName << "] " << msg);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100266 }
267
268 close();
269 onFail(msg);
270}
271
Davide Pesavento44deacc2014-02-19 10:48:07 +0100272size_t
273EthernetFace::getInterfaceMtu() const
274{
275 size_t mtu = ethernet::MAX_DATA_LEN;
276
277#ifdef SIOCGIFMTU
Davide Pesaventoe4631002014-03-21 20:55:36 +0100278 ifreq ifr = {};
Davide Pesaventob60cc122014-03-19 19:26:02 +0100279 std::strncpy(ifr.ifr_name, m_interfaceName.c_str(), sizeof(ifr.ifr_name) - 1);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100280
281 if (::ioctl(m_socket->native_handle(), SIOCGIFMTU, &ifr) < 0)
282 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100283 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +0100284 << "] Failed to get interface MTU, assuming " << mtu);
285 }
286 else
287 {
288 mtu = std::min(mtu, static_cast<size_t>(ifr.ifr_mtu));
289 }
290#endif
291
292 return mtu;
293}
294
295} // namespace nfd