blob: 7d87c0f6b9931d88fa724c4224d9b22eb9a81ec2 [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"
Davide Pesaventob60cc122014-03-19 19:26:02 +01008#include "core/network-interface.hpp"
Davide Pesavento44deacc2014-02-19 10:48:07 +01009
10#include <pcap/pcap.h>
11
Davide Pesaventob60cc122014-03-19 19:26:02 +010012#include <cstring> // for std::strncpy()
Davide Pesavento44deacc2014-02-19 10:48:07 +010013#include <arpa/inet.h> // for htons() and ntohs()
14#include <net/ethernet.h> // for struct ether_header
15#include <net/if.h> // for struct ifreq
16#include <stdio.h> // for snprintf()
17#include <sys/ioctl.h> // for ioctl()
18#include <unistd.h> // for dup()
19
Davide Pesavento44deacc2014-02-19 10:48:07 +010020namespace nfd {
21
22NFD_LOG_INIT("EthernetFace")
23
Davide Pesavento44deacc2014-02-19 10:48:07 +010024EthernetFace::EthernetFace(const shared_ptr<boost::asio::posix::stream_descriptor>& socket,
Davide Pesaventob60cc122014-03-19 19:26:02 +010025 const shared_ptr<NetworkInterfaceInfo>& interface,
Davide Pesavento44deacc2014-02-19 10:48:07 +010026 const ethernet::Address& address)
Davide Pesaventob60cc122014-03-19 19:26:02 +010027 : Face(FaceUri("ether://" + interface->name + "/" + address.toString(':')))
Alexander Afanasyeva39b90b2014-03-05 15:31:00 +000028 , m_socket(socket)
Davide Pesaventob60cc122014-03-19 19:26:02 +010029 , m_interfaceName(interface->name)
30 , m_srcAddress(interface->etherAddress)
Davide Pesavento44deacc2014-02-19 10:48:07 +010031 , m_destAddress(address)
32{
Davide Pesaventob60cc122014-03-19 19:26:02 +010033 NFD_LOG_INFO("Creating ethernet face on " << m_interfaceName << ": "
34 << m_srcAddress << " <--> " << m_destAddress);
Davide Pesavento44deacc2014-02-19 10:48:07 +010035 pcapInit();
36
37 int fd = pcap_get_selectable_fd(m_pcap);
38 if (fd < 0)
39 throw Error("pcap_get_selectable_fd() failed");
40
41 // need to duplicate the fd, otherwise both pcap_close()
42 // and stream_descriptor::close() will try to close the
43 // same fd and one of them will fail
44 m_socket->assign(::dup(fd));
45
Davide Pesavento44deacc2014-02-19 10:48:07 +010046 m_interfaceMtu = getInterfaceMtu();
Davide Pesaventob60cc122014-03-19 19:26:02 +010047 NFD_LOG_DEBUG("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +010048 << "] Interface MTU is: " << m_interfaceMtu);
49
50 char filter[100];
51 ::snprintf(filter, sizeof(filter),
52 "(ether proto 0x%x) && (ether dst %s) && (not ether src %s)",
53 ETHERTYPE_NDN,
54 m_destAddress.toString(':').c_str(),
Davide Pesaventob60cc122014-03-19 19:26:02 +010055 m_srcAddress.toString(':').c_str());
Davide Pesavento44deacc2014-02-19 10:48:07 +010056 setPacketFilter(filter);
57
58 m_socket->async_read_some(boost::asio::null_buffers(),
59 bind(&EthernetFace::handleRead, this,
60 boost::asio::placeholders::error,
61 boost::asio::placeholders::bytes_transferred));
62}
63
64EthernetFace::~EthernetFace()
65{
66 close();
67}
68
69void
70EthernetFace::sendInterest(const Interest& interest)
71{
Alexander Afanasyev7e698e62014-03-07 16:48:35 +000072 onSendInterest(interest);
Davide Pesavento44deacc2014-02-19 10:48:07 +010073 sendPacket(interest.wireEncode());
74}
75
76void
77EthernetFace::sendData(const Data& data)
78{
Alexander Afanasyev7e698e62014-03-07 16:48:35 +000079 onSendData(data);
Davide Pesavento44deacc2014-02-19 10:48:07 +010080 sendPacket(data.wireEncode());
81}
82
83void
84EthernetFace::close()
85{
86 if (m_pcap)
87 {
88 boost::system::error_code error;
89 m_socket->close(error); // ignore errors
90 pcap_close(m_pcap);
91 m_pcap = 0;
92 }
93}
94
95void
96EthernetFace::pcapInit()
97{
Davide Pesavento44deacc2014-02-19 10:48:07 +010098 char errbuf[PCAP_ERRBUF_SIZE];
99 errbuf[0] = '\0';
Davide Pesaventob60cc122014-03-19 19:26:02 +0100100 m_pcap = pcap_create(m_interfaceName.c_str(), errbuf);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100101 if (!m_pcap)
102 throw Error("pcap_create(): " + std::string(errbuf));
103
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100104 /// \todo Do not rely on promisc mode, see task #1278
105 if (!m_destAddress.isBroadcast())
106 pcap_set_promisc(m_pcap, 1);
107
Davide Pesavento44deacc2014-02-19 10:48:07 +0100108 if (pcap_activate(m_pcap) < 0)
109 throw Error("pcap_activate() failed");
110
Davide Pesavento44deacc2014-02-19 10:48:07 +0100111 if (pcap_set_datalink(m_pcap, DLT_EN10MB) < 0)
112 throw Error("pcap_set_datalink(): " + std::string(pcap_geterr(m_pcap)));
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100113
114 if (pcap_setdirection(m_pcap, PCAP_D_IN) < 0)
115 // no need to throw on failure, BPF will filter unwanted packets anyway
116 NFD_LOG_WARN("pcap_setdirection(): " << pcap_geterr(m_pcap));
Davide Pesavento44deacc2014-02-19 10:48:07 +0100117}
118
119void
120EthernetFace::setPacketFilter(const char* filterString)
121{
122 bpf_program filter;
123 if (pcap_compile(m_pcap, &filter, filterString, 1, PCAP_NETMASK_UNKNOWN) < 0)
124 throw Error("pcap_compile(): " + std::string(pcap_geterr(m_pcap)));
125
126 int ret = pcap_setfilter(m_pcap, &filter);
127 pcap_freecode(&filter);
128 if (ret < 0)
129 throw Error("pcap_setfilter(): " + std::string(pcap_geterr(m_pcap)));
130}
131
132void
133EthernetFace::sendPacket(const ndn::Block& block)
134{
135 if (!m_pcap)
136 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100137 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +0100138 << "] Trying to send on closed face");
139 onFail("Face closed");
140 return;
141 }
142
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100143 /// \todo Fragmentation
Davide Pesavento44deacc2014-02-19 10:48:07 +0100144 if (block.size() > m_interfaceMtu)
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100145 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100146 NFD_LOG_ERROR("[id:" << getId() << ",endpoint:" << m_interfaceName
147 << "] Fragmentation not implemented: dropping packet larger than MTU");
Davide Pesavento9eaeac72014-03-15 05:03:42 +0100148 return;
149 }
Davide Pesavento44deacc2014-02-19 10:48:07 +0100150
151 /// \todo Right now there is no reserve when packet is received, but
152 /// we should reserve some space at the beginning and at the end
153 ndn::EncodingBuffer buffer(block);
154
Davide Pesaventoe4631002014-03-21 20:55:36 +0100155 // pad with zeroes if the payload is too short
Davide Pesavento44deacc2014-02-19 10:48:07 +0100156 if (block.size() < ethernet::MIN_DATA_LEN)
157 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100158 static const uint8_t padding[ethernet::MIN_DATA_LEN] = {0};
159 buffer.appendByteArray(padding, ethernet::MIN_DATA_LEN - block.size());
Davide Pesavento44deacc2014-02-19 10:48:07 +0100160 }
161
162 // construct and prepend the ethernet header
163 static uint16_t ethertype = htons(ETHERTYPE_NDN);
164 buffer.prependByteArray(reinterpret_cast<const uint8_t*>(&ethertype), ethernet::TYPE_LEN);
Davide Pesaventob60cc122014-03-19 19:26:02 +0100165 buffer.prependByteArray(m_srcAddress.data(), m_srcAddress.size());
Davide Pesavento44deacc2014-02-19 10:48:07 +0100166 buffer.prependByteArray(m_destAddress.data(), m_destAddress.size());
167
168 // send the packet
169 int sent = pcap_inject(m_pcap, buffer.buf(), buffer.size());
170 if (sent < 0)
171 {
172 throw Error("pcap_inject(): " + std::string(pcap_geterr(m_pcap)));
173 }
174 else if (static_cast<size_t>(sent) < buffer.size())
175 {
176 throw Error("Failed to send packet");
177 }
178
Davide Pesaventob60cc122014-03-19 19:26:02 +0100179 NFD_LOG_TRACE("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +0100180 << "] Successfully sent: " << buffer.size() << " bytes");
181}
182
183void
184EthernetFace::handleRead(const boost::system::error_code& error, size_t)
185{
186 if (error)
187 return processErrorCode(error);
188
189 pcap_pkthdr* pktHeader;
190 const uint8_t* packet;
191 int ret = pcap_next_ex(m_pcap, &pktHeader, &packet);
192 if (ret < 0)
193 {
194 throw Error("pcap_next_ex(): " + std::string(pcap_geterr(m_pcap)));
195 }
196 else if (ret == 0)
197 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100198 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +0100199 << "] pcap_next_ex() timed out");
200 }
201 else
202 {
203 size_t length = pktHeader->caplen;
204 if (length < ethernet::HDR_LEN + ethernet::MIN_DATA_LEN)
205 throw Error("Received packet is too short");
206
207 const ether_header* eh = reinterpret_cast<const ether_header*>(packet);
208 if (ntohs(eh->ether_type) != ETHERTYPE_NDN)
209 throw Error("Unrecognized ethertype");
210
211 packet += ethernet::HDR_LEN;
212 length -= ethernet::HDR_LEN;
Davide Pesaventob60cc122014-03-19 19:26:02 +0100213 NFD_LOG_TRACE("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +0100214 << "] Received: " << length << " bytes");
215
216 /// \todo Eliminate reliance on exceptions in this path
217 try {
218 /// \todo Reserve space in front and at the back
219 /// of the underlying buffer
220 ndn::Block element(packet, length);
221 if (!decodeAndDispatchInput(element))
222 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100223 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
224 << "] Received unrecognized block of type " << element.type());
Davide Pesavento44deacc2014-02-19 10:48:07 +0100225 // ignore unknown packet
226 }
Davide Pesaventob60cc122014-03-19 19:26:02 +0100227 }
228 catch (const tlv::Error&) {
229 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
230 << "] Received block is invalid or too large to process");
Davide Pesavento44deacc2014-02-19 10:48:07 +0100231 }
232 }
233
234 m_socket->async_read_some(boost::asio::null_buffers(),
235 bind(&EthernetFace::handleRead, this,
236 boost::asio::placeholders::error,
237 boost::asio::placeholders::bytes_transferred));
238}
239
240void
241EthernetFace::processErrorCode(const boost::system::error_code& error)
242{
243 if (error == boost::system::errc::operation_canceled)
244 // when socket is closed by someone
245 return;
246
247 if (!m_pcap)
248 {
249 onFail("Face closed");
250 return;
251 }
252
253 std::string msg;
254 if (error == boost::asio::error::eof)
255 {
256 msg = "Face closed";
Davide Pesaventob60cc122014-03-19 19:26:02 +0100257 NFD_LOG_INFO("[id:" << getId() << ",endpoint:" << m_interfaceName << "] " << msg);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100258 }
259 else
260 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100261 msg = "Receive operation failed, closing face: " + error.category().message(error.value());
262 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName << "] " << msg);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100263 }
264
265 close();
266 onFail(msg);
267}
268
Davide Pesavento44deacc2014-02-19 10:48:07 +0100269size_t
270EthernetFace::getInterfaceMtu() const
271{
272 size_t mtu = ethernet::MAX_DATA_LEN;
273
274#ifdef SIOCGIFMTU
Davide Pesaventoe4631002014-03-21 20:55:36 +0100275 ifreq ifr = {};
Davide Pesaventob60cc122014-03-19 19:26:02 +0100276 std::strncpy(ifr.ifr_name, m_interfaceName.c_str(), sizeof(ifr.ifr_name) - 1);
Davide Pesavento44deacc2014-02-19 10:48:07 +0100277
278 if (::ioctl(m_socket->native_handle(), SIOCGIFMTU, &ifr) < 0)
279 {
Davide Pesaventob60cc122014-03-19 19:26:02 +0100280 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interfaceName
Davide Pesavento44deacc2014-02-19 10:48:07 +0100281 << "] Failed to get interface MTU, assuming " << mtu);
282 }
283 else
284 {
285 mtu = std::min(mtu, static_cast<size_t>(ifr.ifr_mtu));
286 }
287#endif
288
289 return mtu;
290}
291
292} // namespace nfd