face.cpp
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright (c) 2013-2022 Regents of the University of California.
4  *
5  * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
6  *
7  * ndn-cxx library is free software: you can redistribute it and/or modify it under the
8  * terms of the GNU Lesser General Public License as published by the Free Software
9  * Foundation, either version 3 of the License, or (at your option) any later version.
10  *
11  * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
12  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
13  * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
14  *
15  * You should have received copies of the GNU General Public License and GNU Lesser
16  * General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see
17  * <http://www.gnu.org/licenses/>.
18  *
19  * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
20  */
21 
22 #include "ndn-cxx/face.hpp"
23 #include "ndn-cxx/encoding/tlv.hpp"
24 #include "ndn-cxx/impl/face-impl.hpp"
25 #include "ndn-cxx/net/face-uri.hpp"
28 #include "ndn-cxx/util/scope.hpp"
29 #include "ndn-cxx/util/time.hpp"
30 
31 // NDN_LOG_INIT(ndn.Face) is declared in face-impl.hpp
32 
33 // A callback scheduled through io.post and io.dispatch may be invoked after the face is destructed.
34 // To prevent this situation, use these macros to capture Face::m_impl as weak_ptr and skip callback
35 // execution if the face has been destructed.
36 #define IO_CAPTURE_WEAK_IMPL(OP) \
37  { \
38  weak_ptr<Impl> implWeak(m_impl); \
39  m_ioService.OP([=] { \
40  auto impl = implWeak.lock(); \
41  if (impl != nullptr) {
42 #define IO_CAPTURE_WEAK_IMPL_END \
43  } \
44  }); \
45  }
46 
47 namespace ndn {
48 
49 Face::OversizedPacketError::OversizedPacketError(char pktType, const Name& name, size_t wireSize)
50  : Error((pktType == 'I' ? "Interest " : pktType == 'D' ? "Data " : "Nack ") +
51  name.toUri() + " encodes into " + to_string(wireSize) + " octets, "
52  "exceeding the implementation limit of " + to_string(MAX_NDN_PACKET_SIZE) + " octets")
53  , pktType(pktType)
54  , name(name)
55  , wireSize(wireSize)
56 {
57 }
58 
59 Face::Face(shared_ptr<Transport> transport)
60  : m_internalIoService(make_unique<boost::asio::io_service>())
61  , m_ioService(*m_internalIoService)
62  , m_internalKeyChain(make_unique<KeyChain>())
63 {
64  construct(std::move(transport), *m_internalKeyChain);
65 }
66 
67 Face::Face(boost::asio::io_service& ioService)
68  : m_ioService(ioService)
69  , m_internalKeyChain(make_unique<KeyChain>())
70 {
71  construct(nullptr, *m_internalKeyChain);
72 }
73 
74 Face::Face(const std::string& host, const std::string& port)
75  : m_internalIoService(make_unique<boost::asio::io_service>())
76  , m_ioService(*m_internalIoService)
77  , m_internalKeyChain(make_unique<KeyChain>())
78 {
79  construct(make_shared<TcpTransport>(host, port), *m_internalKeyChain);
80 }
81 
82 Face::Face(shared_ptr<Transport> transport, KeyChain& keyChain)
83  : m_internalIoService(make_unique<boost::asio::io_service>())
84  , m_ioService(*m_internalIoService)
85 {
86  construct(std::move(transport), keyChain);
87 }
88 
89 Face::Face(shared_ptr<Transport> transport, boost::asio::io_service& ioService)
90  : m_ioService(ioService)
91  , m_internalKeyChain(make_unique<KeyChain>())
92 {
93  construct(std::move(transport), *m_internalKeyChain);
94 }
95 
96 Face::Face(shared_ptr<Transport> transport, boost::asio::io_service& ioService, KeyChain& keyChain)
97  : m_ioService(ioService)
98 {
99  construct(std::move(transport), keyChain);
100 }
101 
102 shared_ptr<Transport>
103 Face::makeDefaultTransport()
104 {
105  std::string transportUri;
106 
107  const char* transportEnviron = getenv("NDN_CLIENT_TRANSPORT");
108  if (transportEnviron != nullptr) {
109  transportUri = transportEnviron;
110  }
111  else {
112  ConfigFile config;
113  transportUri = config.getParsedConfiguration().get<std::string>("transport", "");
114  }
115 
116  if (transportUri.empty()) {
117  // transport not specified, use default Unix transport.
118  return UnixTransport::create("");
119  }
120 
121  std::string protocol;
122  try {
123  FaceUri uri(transportUri);
124  protocol = uri.getScheme();
125 
126  if (protocol == "unix") {
127  return UnixTransport::create(transportUri);
128  }
129  else if (protocol == "tcp" || protocol == "tcp4" || protocol == "tcp6") {
130  return TcpTransport::create(transportUri);
131  }
132  else {
133  NDN_THROW(ConfigFile::Error("Unsupported transport protocol \"" + protocol + "\""));
134  }
135  }
136  catch (const Transport::Error&) {
137  NDN_THROW_NESTED(ConfigFile::Error("Failed to create transport"));
138  }
139  catch (const FaceUri::Error&) {
140  NDN_THROW_NESTED(ConfigFile::Error("Failed to create transport"));
141  }
142 }
143 
144 void
145 Face::construct(shared_ptr<Transport> transport, KeyChain& keyChain)
146 {
147  BOOST_ASSERT(m_impl == nullptr);
148  m_impl = make_shared<Impl>(*this, keyChain);
149 
150  if (transport == nullptr) {
151  transport = makeDefaultTransport();
152  BOOST_ASSERT(transport != nullptr);
153  }
154  m_transport = std::move(transport);
155 
156  IO_CAPTURE_WEAK_IMPL(post) {
157  impl->ensureConnected(false);
159 }
160 
161 Face::~Face() = default;
162 
163 PendingInterestHandle
165  const DataCallback& afterSatisfied,
166  const NackCallback& afterNacked,
167  const TimeoutCallback& afterTimeout)
168 {
169  auto id = m_impl->m_pendingInterestTable.allocateId();
170 
171  auto interest2 = make_shared<Interest>(interest);
172  interest2->getNonce();
173 
174  IO_CAPTURE_WEAK_IMPL(post) {
175  impl->expressInterest(id, interest2, afterSatisfied, afterNacked, afterTimeout);
177 
178  return PendingInterestHandle(m_impl, id);
179 }
180 
181 void
183 {
184  IO_CAPTURE_WEAK_IMPL(post) {
185  impl->removeAllPendingInterests();
187 }
188 
189 size_t
191 {
192  return m_impl->m_pendingInterestTable.size();
193 }
194 
195 void
197 {
198  IO_CAPTURE_WEAK_IMPL(post) {
199  impl->putData(data);
201 }
202 
203 void
205 {
206  IO_CAPTURE_WEAK_IMPL(post) {
207  impl->putNack(nack);
209 }
210 
212 Face::setInterestFilter(const InterestFilter& filter, const InterestCallback& onInterest,
213  const RegisterPrefixFailureCallback& onFailure,
214  const security::SigningInfo& signingInfo, uint64_t flags)
215 {
216  return setInterestFilter(filter, onInterest, nullptr, onFailure, signingInfo, flags);
217 }
218 
220 Face::setInterestFilter(const InterestFilter& filter, const InterestCallback& onInterest,
221  const RegisterPrefixSuccessCallback& onSuccess,
222  const RegisterPrefixFailureCallback& onFailure,
223  const security::SigningInfo& signingInfo, uint64_t flags)
224 {
225  nfd::CommandOptions options;
226  options.setSigningInfo(signingInfo);
227 
228  auto id = m_impl->registerPrefix(filter.getPrefix(), onSuccess, onFailure, flags, options,
229  filter, onInterest);
230  return RegisteredPrefixHandle(m_impl, id);
231 }
232 
234 Face::setInterestFilter(const InterestFilter& filter, const InterestCallback& onInterest)
235 {
236  auto id = m_impl->m_interestFilterTable.allocateId();
237 
238  IO_CAPTURE_WEAK_IMPL(post) {
239  impl->setInterestFilter(id, filter, onInterest);
241 
242  return InterestFilterHandle(m_impl, id);
243 }
244 
247  const RegisterPrefixSuccessCallback& onSuccess,
248  const RegisterPrefixFailureCallback& onFailure,
249  const security::SigningInfo& signingInfo,
250  uint64_t flags)
251 {
252  nfd::CommandOptions options;
253  options.setSigningInfo(signingInfo);
254 
255  auto id = m_impl->registerPrefix(prefix, onSuccess, onFailure, flags, options, nullopt, nullptr);
256  return RegisteredPrefixHandle(m_impl, id);
257 }
258 
259 void
260 Face::doProcessEvents(time::milliseconds timeout, bool keepThread)
261 {
262  if (m_ioService.stopped()) {
263  m_ioService.reset(); // ensure that run()/poll() will do some work
264  }
265 
266  auto onThrow = make_scope_fail([this] { m_impl->shutdown(); });
267 
268  if (timeout < 0_ms) {
269  // do not block if timeout is negative, but process pending events
270  m_ioService.poll();
271  return;
272  }
273 
274  if (timeout > 0_ms) {
275  m_impl->m_processEventsTimeoutEvent = m_impl->m_scheduler.schedule(timeout,
276  [&io = m_ioService, &work = m_impl->m_ioServiceWork] {
277  io.stop();
278  work.reset();
279  });
280  }
281 
282  if (keepThread) {
283  // work will ensure that m_ioService is running until work object exists
284  m_impl->m_ioServiceWork = make_unique<boost::asio::io_service::work>(m_ioService);
285  }
286 
287  m_ioService.run();
288 }
289 
290 void
292 {
293  IO_CAPTURE_WEAK_IMPL(post) {
294  impl->shutdown();
295  if (m_transport->getState() != Transport::State::CLOSED)
296  m_transport->close();
298 }
299 
303 template<typename NetPkt>
304 static void
305 extractLpLocalFields(NetPkt& netPacket, const lp::Packet& lpPacket)
306 {
307  addTagFromField<lp::IncomingFaceIdTag, lp::IncomingFaceIdField>(netPacket, lpPacket);
308  addTagFromField<lp::CongestionMarkTag, lp::CongestionMarkField>(netPacket, lpPacket);
309 }
310 
311 void
312 Face::onReceiveElement(const Block& blockFromDaemon)
313 {
314  lp::Packet lpPacket(blockFromDaemon); // bare Interest/Data is a valid lp::Packet,
315  // no need to distinguish
316 
317  auto frag = lpPacket.get<lp::FragmentField>();
318  Block netPacket({frag.first, frag.second});
319  switch (netPacket.type()) {
320  case tlv::Interest: {
321  auto interest = make_shared<Interest>(netPacket);
322  if (lpPacket.has<lp::NackField>()) {
323  auto nack = make_shared<lp::Nack>(std::move(*interest));
324  nack->setHeader(lpPacket.get<lp::NackField>());
325  extractLpLocalFields(*nack, lpPacket);
326  NDN_LOG_DEBUG(">N " << nack->getInterest() << '~' << nack->getHeader().getReason());
327  m_impl->nackPendingInterests(*nack);
328  }
329  else {
330  extractLpLocalFields(*interest, lpPacket);
331  NDN_LOG_DEBUG(">I " << *interest);
332  m_impl->processIncomingInterest(std::move(interest));
333  }
334  break;
335  }
336  case tlv::Data: {
337  auto data = make_shared<Data>(netPacket);
338  extractLpLocalFields(*data, lpPacket);
339  NDN_LOG_DEBUG(">D " << data->getName());
340  m_impl->satisfyPendingInterests(*data);
341  break;
342  }
343  }
344 }
345 
346 PendingInterestHandle::PendingInterestHandle(weak_ptr<Face::Impl> weakImpl, detail::RecordId id)
347  : CancelHandle([w = std::move(weakImpl), id] {
348  auto impl = w.lock();
349  if (impl != nullptr) {
350  impl->asyncRemovePendingInterest(id);
351  }
352  })
353 {
354 }
355 
356 RegisteredPrefixHandle::RegisteredPrefixHandle(weak_ptr<Face::Impl> weakImpl, detail::RecordId id)
357  : CancelHandle([=] { unregister(weakImpl, id, nullptr, nullptr); })
358  , m_weakImpl(std::move(weakImpl))
359  , m_id(id)
360 {
361  // The lambda passed to CancelHandle constructor cannot call the non-static unregister(),
362  // because the base class destructor cannot access the member fields of this subclass.
363 }
364 
365 void
367  const UnregisterPrefixFailureCallback& onFailure)
368 {
369  if (m_id == 0) {
370  if (onFailure) {
371  onFailure("RegisteredPrefixHandle is empty");
372  }
373  return;
374  }
375 
376  unregister(m_weakImpl, m_id, onSuccess, onFailure);
377  *this = {};
378 }
379 
380 void
381 RegisteredPrefixHandle::unregister(const weak_ptr<Face::Impl>& weakImpl, detail::RecordId id,
382  const UnregisterPrefixSuccessCallback& onSuccess,
383  const UnregisterPrefixFailureCallback& onFailure)
384 {
385  auto impl = weakImpl.lock();
386  if (impl != nullptr) {
387  impl->asyncUnregisterPrefix(id, onSuccess, onFailure);
388  }
389  else if (onFailure) {
390  onFailure("Face already closed");
391  }
392 }
393 
394 InterestFilterHandle::InterestFilterHandle(weak_ptr<Face::Impl> weakImpl, detail::RecordId id)
395  : CancelHandle([w = std::move(weakImpl), id] {
396  auto impl = w.lock();
397  if (impl != nullptr) {
398  impl->asyncUnsetInterestFilter(id);
399  }
400  })
401 {
402 }
403 
404 } // namespace ndn
Represents a Data packet.
Definition: data.hpp:39
OversizedPacketError(char pktType, const Name &name, size_t wireSize)
Constructor.
Definition: face.cpp:49
virtual void doProcessEvents(time::milliseconds timeout, bool keepThread)
Definition: face.cpp:260
RegisteredPrefixHandle registerPrefix(const Name &prefix, const RegisterPrefixSuccessCallback &onSuccess, const RegisterPrefixFailureCallback &onFailure, const security::SigningInfo &signingInfo=security::SigningInfo(), uint64_t flags=nfd::ROUTE_FLAG_CHILD_INHERIT)
Register prefix with the connected NDN forwarder.
Definition: face.cpp:246
virtual ~Face()
RegisteredPrefixHandle setInterestFilter(const InterestFilter &filter, const InterestCallback &onInterest, const RegisterPrefixFailureCallback &onFailure, const security::SigningInfo &signingInfo=security::SigningInfo(), uint64_t flags=nfd::ROUTE_FLAG_CHILD_INHERIT)
Set InterestFilter to dispatch incoming matching interest to onInterest callback and register the fil...
Definition: face.cpp:212
void removeAllPendingInterests()
Cancel all previously expressed Interests.
Definition: face.cpp:182
Face(shared_ptr< Transport > transport=nullptr)
Create Face using given transport (or default transport if omitted)
Definition: face.cpp:59
PendingInterestHandle expressInterest(const Interest &interest, const DataCallback &afterSatisfied, const NackCallback &afterNacked, const TimeoutCallback &afterTimeout)
Express an Interest.
Definition: face.cpp:164
void shutdown()
Shutdown face operations.
Definition: face.cpp:291
void put(Data data)
Publish a Data packet.
Definition: face.cpp:196
size_t getNPendingInterests() const
Get number of pending Interests.
Definition: face.cpp:190
Handle for a registered Interest filter.
Definition: face.hpp:566
InterestFilterHandle() noexcept=default
Declares the set of Interests a producer can serve.
const Name & getPrefix() const
Represents an Interest packet.
Definition: interest.hpp:50
Represents an absolute name.
Definition: name.hpp:44
Handle for a pending Interest.
Definition: face.hpp:491
PendingInterestHandle() noexcept=default
Handle for a registered prefix.
Definition: face.hpp:518
void unregister(const UnregisterPrefixSuccessCallback &onSuccess=nullptr, const UnregisterPrefixFailureCallback &onFailure=nullptr)
Unregister the prefix.
Definition: face.cpp:366
RegisteredPrefixHandle() noexcept=default
static shared_ptr< TcpTransport > create(const std::string &uri)
Create transport with parameters defined in URI.
static shared_ptr< UnixTransport > create(const std::string &uri)
Create transport with parameters defined in URI.
Represents a Network Nack.
Definition: nack.hpp:40
Contains options for ControlCommand execution.
CommandOptions & setSigningInfo(const security::SigningInfo &signingInfo)
Sets the signing parameters.
Signing parameters passed to KeyChain.
#define NDN_THROW_NESTED(e)
Definition: exception.hpp:71
#define NDN_THROW(e)
Definition: exception.hpp:61
#define IO_CAPTURE_WEAK_IMPL_END
Definition: face.cpp:42
#define IO_CAPTURE_WEAK_IMPL(OP)
Definition: face.cpp:36
#define NDN_LOG_DEBUG(expression)
Log at DEBUG level.
Definition: logger.hpp:254
uint64_t RecordId
Definition: face.hpp:44
std::string to_string(const errinfo_stacktrace &x)
Definition: exception.cpp:31
FieldDecl< field_location_tags::Fragment, std::pair< Buffer::const_iterator, Buffer::const_iterator >, tlv::Fragment > FragmentField
Declare the Fragment field.
Definition: fields.hpp:115
FieldDecl< field_location_tags::Header, NackHeader, tlv::Nack > NackField
Definition: fields.hpp:60
boost::chrono::milliseconds milliseconds
Definition: time.hpp:48
@ Data
Definition: tlv.hpp:69
@ Interest
Definition: tlv.hpp:68
Definition: data.cpp:25
function< void(const std::string &)> UnregisterPrefixFailureCallback
Callback invoked when unregistering a prefix fails.
Definition: face.hpp:85
function< void(const InterestFilter &, const Interest &)> InterestCallback
Callback invoked when an incoming Interest matches the specified InterestFilter.
Definition: face.hpp:65
function< void(const Interest &, const lp::Nack &)> NackCallback
Callback invoked when a Nack is received in response to an expressed Interest.
Definition: face.hpp:55
function< void()> UnregisterPrefixSuccessCallback
Callback invoked when unregistering a prefix succeeds.
Definition: face.hpp:80
function< void(const Interest &)> TimeoutCallback
Callback invoked when an expressed Interest times out.
Definition: face.hpp:60
function< void(const Name &, const std::string &)> RegisterPrefixFailureCallback
Callback invoked when registerPrefix or setInterestFilter command fails.
Definition: face.hpp:75
function< void(const Name &)> RegisterPrefixSuccessCallback
Callback invoked when registerPrefix or setInterestFilter command succeeds.
Definition: face.hpp:70
const size_t MAX_NDN_PACKET_SIZE
Practical size limit of a network-layer packet.
Definition: tlv.hpp:41
function< void(const Interest &, const Data &)> DataCallback
Callback invoked when an expressed Interest is satisfied by a Data packet.
Definition: face.hpp:50