blob: f279a8f79324ee1e4bbc39fc3e5976442a8bb89b [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"
8
9#include <pcap/pcap.h>
10
11#include <arpa/inet.h> // for htons() and ntohs()
12#include <net/ethernet.h> // for struct ether_header
13#include <net/if.h> // for struct ifreq
14#include <stdio.h> // for snprintf()
15#include <sys/ioctl.h> // for ioctl()
16#include <unistd.h> // for dup()
17
18#ifndef SIOCGIFHWADDR
19#include <net/if_dl.h> // for struct sockaddr_dl
20// must be included *after* <net/if.h>
21#include <ifaddrs.h> // for getifaddrs()
22#endif
23
24namespace nfd {
25
26NFD_LOG_INIT("EthernetFace")
27
28static const uint8_t MAX_PADDING[ethernet::MIN_DATA_LEN] = {
29 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
30 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
31};
32
33
34EthernetFace::EthernetFace(const shared_ptr<boost::asio::posix::stream_descriptor>& socket,
35 const ethernet::Endpoint& interface,
36 const ethernet::Address& address)
Alexander Afanasyeva39b90b2014-03-05 15:31:00 +000037 : Face(FaceUri("ether://" + interface + "/" + address.toString(':')))
38 , m_socket(socket)
Davide Pesavento44deacc2014-02-19 10:48:07 +010039 , m_interface(interface)
40 , m_destAddress(address)
41{
Davide Pesavento44deacc2014-02-19 10:48:07 +010042 pcapInit();
43
44 int fd = pcap_get_selectable_fd(m_pcap);
45 if (fd < 0)
46 throw Error("pcap_get_selectable_fd() failed");
47
48 // need to duplicate the fd, otherwise both pcap_close()
49 // and stream_descriptor::close() will try to close the
50 // same fd and one of them will fail
51 m_socket->assign(::dup(fd));
52
53 m_sourceAddress = getInterfaceAddress();
54 NFD_LOG_DEBUG("[id:" << getId() << ",endpoint:" << m_interface
55 << "] Local MAC address is: " << m_sourceAddress);
56 m_interfaceMtu = getInterfaceMtu();
57 NFD_LOG_DEBUG("[id:" << getId() << ",endpoint:" << m_interface
58 << "] Interface MTU is: " << m_interfaceMtu);
59
60 char filter[100];
61 ::snprintf(filter, sizeof(filter),
62 "(ether proto 0x%x) && (ether dst %s) && (not ether src %s)",
63 ETHERTYPE_NDN,
64 m_destAddress.toString(':').c_str(),
65 m_sourceAddress.toString(':').c_str());
66 setPacketFilter(filter);
67
68 m_socket->async_read_some(boost::asio::null_buffers(),
69 bind(&EthernetFace::handleRead, this,
70 boost::asio::placeholders::error,
71 boost::asio::placeholders::bytes_transferred));
72}
73
74EthernetFace::~EthernetFace()
75{
76 close();
77}
78
79void
80EthernetFace::sendInterest(const Interest& interest)
81{
Alexander Afanasyev7e698e62014-03-07 16:48:35 +000082 onSendInterest(interest);
Davide Pesavento44deacc2014-02-19 10:48:07 +010083 sendPacket(interest.wireEncode());
84}
85
86void
87EthernetFace::sendData(const Data& data)
88{
Alexander Afanasyev7e698e62014-03-07 16:48:35 +000089 onSendData(data);
Davide Pesavento44deacc2014-02-19 10:48:07 +010090 sendPacket(data.wireEncode());
91}
92
93void
94EthernetFace::close()
95{
96 if (m_pcap)
97 {
98 boost::system::error_code error;
99 m_socket->close(error); // ignore errors
100 pcap_close(m_pcap);
101 m_pcap = 0;
102 }
103}
104
105void
106EthernetFace::pcapInit()
107{
108 NFD_LOG_TRACE("[id:" << getId() << ",endpoint:" << m_interface
109 << "] Initializing pcap");
110
111 char errbuf[PCAP_ERRBUF_SIZE];
112 errbuf[0] = '\0';
113 m_pcap = pcap_create(m_interface.c_str(), errbuf);
114 if (!m_pcap)
115 throw Error("pcap_create(): " + std::string(errbuf));
116
117 if (pcap_activate(m_pcap) < 0)
118 throw Error("pcap_activate() failed");
119
120 errbuf[0] = '\0';
121 if (pcap_setnonblock(m_pcap, 1, errbuf) < 0)
122 throw Error("pcap_setnonblock(): " + std::string(errbuf));
123
124 if (pcap_setdirection(m_pcap, PCAP_D_IN) < 0)
125 throw Error("pcap_setdirection(): " + std::string(pcap_geterr(m_pcap)));
126
127 if (pcap_set_datalink(m_pcap, DLT_EN10MB) < 0)
128 throw Error("pcap_set_datalink(): " + std::string(pcap_geterr(m_pcap)));
129}
130
131void
132EthernetFace::setPacketFilter(const char* filterString)
133{
134 bpf_program filter;
135 if (pcap_compile(m_pcap, &filter, filterString, 1, PCAP_NETMASK_UNKNOWN) < 0)
136 throw Error("pcap_compile(): " + std::string(pcap_geterr(m_pcap)));
137
138 int ret = pcap_setfilter(m_pcap, &filter);
139 pcap_freecode(&filter);
140 if (ret < 0)
141 throw Error("pcap_setfilter(): " + std::string(pcap_geterr(m_pcap)));
142}
143
144void
145EthernetFace::sendPacket(const ndn::Block& block)
146{
147 if (!m_pcap)
148 {
149 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interface
150 << "] Trying to send on closed face");
151 onFail("Face closed");
152 return;
153 }
154
155 /// @todo Fragmentation
156 if (block.size() > m_interfaceMtu)
157 throw Error("Fragmentation not implemented");
158
159 /// \todo Right now there is no reserve when packet is received, but
160 /// we should reserve some space at the beginning and at the end
161 ndn::EncodingBuffer buffer(block);
162
163 if (block.size() < ethernet::MIN_DATA_LEN)
164 {
165 buffer.appendByteArray(MAX_PADDING, ethernet::MIN_DATA_LEN - block.size());
166 }
167
168 // construct and prepend the ethernet header
169 static uint16_t ethertype = htons(ETHERTYPE_NDN);
170 buffer.prependByteArray(reinterpret_cast<const uint8_t*>(&ethertype), ethernet::TYPE_LEN);
171 buffer.prependByteArray(m_sourceAddress.data(), m_sourceAddress.size());
172 buffer.prependByteArray(m_destAddress.data(), m_destAddress.size());
173
174 // send the packet
175 int sent = pcap_inject(m_pcap, buffer.buf(), buffer.size());
176 if (sent < 0)
177 {
178 throw Error("pcap_inject(): " + std::string(pcap_geterr(m_pcap)));
179 }
180 else if (static_cast<size_t>(sent) < buffer.size())
181 {
182 throw Error("Failed to send packet");
183 }
184
185 NFD_LOG_TRACE("[id:" << getId() << ",endpoint:" << m_interface
186 << "] Successfully sent: " << buffer.size() << " bytes");
187}
188
189void
190EthernetFace::handleRead(const boost::system::error_code& error, size_t)
191{
192 if (error)
193 return processErrorCode(error);
194
195 pcap_pkthdr* pktHeader;
196 const uint8_t* packet;
197 int ret = pcap_next_ex(m_pcap, &pktHeader, &packet);
198 if (ret < 0)
199 {
200 throw Error("pcap_next_ex(): " + std::string(pcap_geterr(m_pcap)));
201 }
202 else if (ret == 0)
203 {
204 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interface
205 << "] pcap_next_ex() timed out");
206 }
207 else
208 {
209 size_t length = pktHeader->caplen;
210 if (length < ethernet::HDR_LEN + ethernet::MIN_DATA_LEN)
211 throw Error("Received packet is too short");
212
213 const ether_header* eh = reinterpret_cast<const ether_header*>(packet);
214 if (ntohs(eh->ether_type) != ETHERTYPE_NDN)
215 throw Error("Unrecognized ethertype");
216
217 packet += ethernet::HDR_LEN;
218 length -= ethernet::HDR_LEN;
219 NFD_LOG_TRACE("[id:" << getId() << ",endpoint:" << m_interface
220 << "] Received: " << length << " bytes");
221
222 /// \todo Eliminate reliance on exceptions in this path
223 try {
224 /// \todo Reserve space in front and at the back
225 /// of the underlying buffer
226 ndn::Block element(packet, length);
227 if (!decodeAndDispatchInput(element))
228 {
229 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interface
230 << "] Received unrecognized block of type ["
231 << element.type() << "]");
232 // ignore unknown packet
233 }
234 } catch (const tlv::Error&) {
235 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interface
236 << "] Received input is invalid or too large to process");
237 }
238 }
239
240 m_socket->async_read_some(boost::asio::null_buffers(),
241 bind(&EthernetFace::handleRead, this,
242 boost::asio::placeholders::error,
243 boost::asio::placeholders::bytes_transferred));
244}
245
246void
247EthernetFace::processErrorCode(const boost::system::error_code& error)
248{
249 if (error == boost::system::errc::operation_canceled)
250 // when socket is closed by someone
251 return;
252
253 if (!m_pcap)
254 {
255 onFail("Face closed");
256 return;
257 }
258
259 std::string msg;
260 if (error == boost::asio::error::eof)
261 {
262 msg = "Face closed";
263 NFD_LOG_INFO("[id:" << getId() << ",endpoint:" << m_interface << "] " << msg);
264 }
265 else
266 {
267 msg = "Send or receive operation failed, closing face: "
268 + error.category().message(error.value());
269 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interface << "] " << msg);
270 }
271
272 close();
273 onFail(msg);
274}
275
276ethernet::Address
277EthernetFace::getInterfaceAddress() const
278{
279#ifdef SIOCGIFHWADDR
280 ifreq ifr = {};
281 ::strncpy(ifr.ifr_name, m_interface.c_str(), sizeof(ifr.ifr_name));
282
283 if (::ioctl(m_socket->native_handle(), SIOCGIFHWADDR, &ifr) < 0)
284 throw Error("ioctl(SIOCGIFHWADDR) failed");
285
286 uint8_t* hwaddr = reinterpret_cast<uint8_t*>(ifr.ifr_hwaddr.sa_data);
287 return ethernet::Address(hwaddr);
288#else
289 ifaddrs* addrlist;
290 if (::getifaddrs(&addrlist) < 0)
291 throw Error("getifaddrs() failed");
292
293 ethernet::Address address;
294 for (ifaddrs* ifa = addrlist; ifa != 0; ifa = ifa->ifa_next)
295 {
296 if (std::string(ifa->ifa_name) == m_interface
297 && ifa->ifa_addr != 0
298 && ifa->ifa_addr->sa_family == AF_LINK)
299 {
300 sockaddr_dl* sa = reinterpret_cast<sockaddr_dl*>(ifa->ifa_addr);
301 address = ethernet::Address(reinterpret_cast<uint8_t*>(LLADDR(sa)));
302 break;
303 }
304 }
305
306 ::freeifaddrs(addrlist);
307 return address;
308#endif
309}
310
311size_t
312EthernetFace::getInterfaceMtu() const
313{
314 size_t mtu = ethernet::MAX_DATA_LEN;
315
316#ifdef SIOCGIFMTU
317 ifreq ifr = {};
318 ::strncpy(ifr.ifr_name, m_interface.c_str(), sizeof(ifr.ifr_name));
319
320 if (::ioctl(m_socket->native_handle(), SIOCGIFMTU, &ifr) < 0)
321 {
322 NFD_LOG_WARN("[id:" << getId() << ",endpoint:" << m_interface
323 << "] Failed to get interface MTU, assuming " << mtu);
324 }
325 else
326 {
327 mtu = std::min(mtu, static_cast<size_t>(ifr.ifr_mtu));
328 }
329#endif
330
331 return mtu;
332}
333
334} // namespace nfd