dispatcher.cpp
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright (c) 2013-2018 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 "dispatcher.hpp"
23 #include "../lp/tags.hpp"
24 #include "../util/logger.hpp"
25 
27 
28 namespace ndn {
29 namespace mgmt {
30 
31 const time::milliseconds DEFAULT_FRESHNESS_PERIOD = 1_s;
32 
35 {
36  return [] (const Name& prefix,
37  const Interest& interest,
38  const ControlParameters* params,
39  const AcceptContinuation& accept,
40  const RejectContinuation& reject) {
41  accept("");
42  };
43 }
44 
45 Dispatcher::Dispatcher(Face& face, KeyChain& keyChain,
46  const security::SigningInfo& signingInfo,
47  size_t imsCapacity)
48  : m_face(face)
49  , m_keyChain(keyChain)
50  , m_signingInfo(signingInfo)
51  , m_storage(m_face.getIoService(), imsCapacity)
52 {
53 }
54 
56 {
57  std::vector<Name> topPrefixNames;
58  std::transform(m_topLevelPrefixes.begin(), m_topLevelPrefixes.end(), std::back_inserter(topPrefixNames),
59  [] (const auto& entry) { return entry.second.topPrefix; });
60 
61  for (const auto& name : topPrefixNames) {
62  removeTopPrefix(name);
63  }
64 }
65 
66 void
67 Dispatcher::addTopPrefix(const Name& prefix, bool wantRegister,
68  const security::SigningInfo& signingInfo)
69 {
70  bool hasOverlap = std::any_of(m_topLevelPrefixes.begin(), m_topLevelPrefixes.end(),
71  [&prefix] (const auto& x) {
72  return x.first.isPrefixOf(prefix) || prefix.isPrefixOf(x.first);
73  });
74  if (hasOverlap) {
75  BOOST_THROW_EXCEPTION(std::out_of_range("top-level prefix overlaps"));
76  }
77 
78  TopPrefixEntry& topPrefixEntry = m_topLevelPrefixes[prefix];
79  topPrefixEntry.topPrefix = prefix;
80 
81  if (wantRegister) {
82  topPrefixEntry.registeredPrefixId = m_face.registerPrefix(prefix,
83  nullptr,
84  [] (const Name&, const std::string& reason) {
85  BOOST_THROW_EXCEPTION(std::runtime_error("prefix registration failed: " + reason));
86  },
87  signingInfo);
88  }
89 
90  for (const auto& entry : m_handlers) {
91  Name fullPrefix = Name(prefix).append(entry.first);
92  const auto* filterId = m_face.setInterestFilter(fullPrefix, bind(entry.second, prefix, _2));
93  topPrefixEntry.interestFilters.push_back(filterId);
94  }
95 }
96 
97 void
99 {
100  auto it = m_topLevelPrefixes.find(prefix);
101  if (it == m_topLevelPrefixes.end()) {
102  return;
103  }
104 
105  const TopPrefixEntry& topPrefixEntry = it->second;
106  if (topPrefixEntry.registeredPrefixId) {
107  m_face.unregisterPrefix(*topPrefixEntry.registeredPrefixId, nullptr, nullptr);
108  }
109  for (const auto& filter : topPrefixEntry.interestFilters) {
110  m_face.unsetInterestFilter(filter);
111  }
112 
113  m_topLevelPrefixes.erase(it);
114 }
115 
116 bool
117 Dispatcher::isOverlappedWithOthers(const PartialName& relPrefix) const
118 {
119  bool hasOverlapWithHandlers =
120  std::any_of(m_handlers.begin(), m_handlers.end(),
121  [&] (const auto& entry) {
122  return entry.first.isPrefixOf(relPrefix) || relPrefix.isPrefixOf(entry.first);
123  });
124  bool hasOverlapWithStreams =
125  std::any_of(m_streams.begin(), m_streams.end(),
126  [&] (const auto& entry) {
127  return entry.first.isPrefixOf(relPrefix) || relPrefix.isPrefixOf(entry.first);
128  });
129 
130  return hasOverlapWithHandlers || hasOverlapWithStreams;
131 }
132 
133 void
134 Dispatcher::afterAuthorizationRejected(RejectReply act, const Interest& interest)
135 {
136  if (act == RejectReply::STATUS403) {
137  sendControlResponse(ControlResponse(403, "authorization rejected"), interest);
138  }
139 }
140 
141 void
142 Dispatcher::queryStorage(const Name& prefix, const Interest& interest,
143  const InterestHandler& missContinuation)
144 {
145  auto data = m_storage.find(interest);
146  if (data == nullptr) {
147  // invoke missContinuation to process this Interest if the query fails.
148  if (missContinuation)
149  missContinuation(prefix, interest);
150  }
151  else {
152  // send the fetched data through face if query succeeds.
153  sendOnFace(*data);
154  }
155 }
156 
157 void
158 Dispatcher::sendData(const Name& dataName, const Block& content, const MetaInfo& metaInfo,
159  SendDestination option, time::milliseconds imsFresh)
160 {
161  auto data = make_shared<Data>(dataName);
162  data->setContent(content).setMetaInfo(metaInfo).setFreshnessPeriod(DEFAULT_FRESHNESS_PERIOD);
163 
164  m_keyChain.sign(*data, m_signingInfo);
165 
166  if (option == SendDestination::IMS || option == SendDestination::FACE_AND_IMS) {
167  lp::CachePolicy policy;
169  data->setTag(make_shared<lp::CachePolicyTag>(policy));
170  m_storage.insert(*data, imsFresh);
171  }
172 
173  if (option == SendDestination::FACE || option == SendDestination::FACE_AND_IMS) {
174  sendOnFace(*data);
175  }
176 }
177 
178 void
179 Dispatcher::sendOnFace(const Data& data)
180 {
181  try {
182  m_face.put(data);
183  }
184  catch (const Face::Error& e) {
185  NDN_LOG_ERROR("sendOnFace: " << e.what());
186  }
187 }
188 
189 void
190 Dispatcher::processControlCommandInterest(const Name& prefix,
191  const Name& relPrefix,
192  const Interest& interest,
193  const ControlParametersParser& parser,
194  const Authorization& authorization,
195  const AuthorizationAcceptedCallback& accepted,
196  const AuthorizationRejectedCallback& rejected)
197 {
198  // /<prefix>/<relPrefix>/<parameters>
199  size_t parametersLoc = prefix.size() + relPrefix.size();
200  const name::Component& pc = interest.getName().get(parametersLoc);
201 
202  shared_ptr<ControlParameters> parameters;
203  try {
204  parameters = parser(pc);
205  }
206  catch (const tlv::Error&) {
207  return;
208  }
209 
210  AcceptContinuation accept = [=] (const auto& req) { accepted(req, prefix, interest, parameters); };
211  RejectContinuation reject = [=] (RejectReply reply) { rejected(reply, interest); };
212  authorization(prefix, interest, parameters.get(), accept, reject);
213 }
214 
215 void
216 Dispatcher::processAuthorizedControlCommandInterest(const std::string& requester,
217  const Name& prefix,
218  const Interest& interest,
219  const shared_ptr<ControlParameters>& parameters,
220  const ValidateParameters& validateParams,
221  const ControlCommandHandler& handler)
222 {
223  if (validateParams(*parameters)) {
224  handler(prefix, interest, *parameters,
225  [=] (const auto& resp) { this->sendControlResponse(resp, interest); });
226  }
227  else {
228  sendControlResponse(ControlResponse(400, "failed in validating parameters"), interest);
229  }
230 }
231 
232 void
233 Dispatcher::sendControlResponse(const ControlResponse& resp, const Interest& interest, bool isNack)
234 {
235  MetaInfo metaInfo;
236  if (isNack) {
237  metaInfo.setType(tlv::ContentType_Nack);
238  }
239 
240  // control response is always sent out through the face
241  sendData(interest.getName(), resp.wireEncode(), metaInfo,
242  SendDestination::FACE, DEFAULT_FRESHNESS_PERIOD);
243 }
244 
245 void
247  Authorization authorize,
248  StatusDatasetHandler handle)
249 {
250  if (!m_topLevelPrefixes.empty()) {
251  BOOST_THROW_EXCEPTION(std::domain_error("one or more top-level prefix has been added"));
252  }
253 
254  if (isOverlappedWithOthers(relPrefix)) {
255  BOOST_THROW_EXCEPTION(std::out_of_range("status dataset name overlaps"));
256  }
257 
258  AuthorizationAcceptedCallback accepted =
259  bind(&Dispatcher::processAuthorizedStatusDatasetInterest, this, _1, _2, _3, std::move(handle));
260  AuthorizationRejectedCallback rejected =
261  bind(&Dispatcher::afterAuthorizationRejected, this, _1, _2);
262 
263  // follow the general path if storage is a miss
264  InterestHandler missContinuation = bind(&Dispatcher::processStatusDatasetInterest, this, _1, _2,
265  std::move(authorize), std::move(accepted), std::move(rejected));
266 
267  m_handlers[relPrefix] = [this, miss = std::move(missContinuation)] (auto&&... args) {
268  this->queryStorage(std::forward<decltype(args)>(args)..., miss);
269  };
270 }
271 
272 void
273 Dispatcher::processStatusDatasetInterest(const Name& prefix,
274  const Interest& interest,
275  const Authorization& authorization,
276  const AuthorizationAcceptedCallback& accepted,
277  const AuthorizationRejectedCallback& rejected)
278 {
279  const Name& interestName = interest.getName();
280  bool endsWithVersionOrSegment = interestName.size() >= 1 &&
281  (interestName[-1].isVersion() || interestName[-1].isSegment());
282  if (endsWithVersionOrSegment) {
283  return;
284  }
285 
286  AcceptContinuation accept = [=] (const auto& req) { accepted(req, prefix, interest, nullptr); };
287  RejectContinuation reject = [=] (RejectReply reply) { rejected(reply, interest); };
288  authorization(prefix, interest, nullptr, accept, reject);
289 }
290 
291 void
292 Dispatcher::processAuthorizedStatusDatasetInterest(const std::string& requester,
293  const Name& prefix,
294  const Interest& interest,
295  const StatusDatasetHandler& handler)
296 {
297  StatusDatasetContext context(interest,
298  bind(&Dispatcher::sendStatusDatasetSegment, this, _1, _2, _3, _4),
299  bind(&Dispatcher::sendControlResponse, this, _1, interest, true));
300  handler(prefix, interest, context);
301 }
302 
303 void
304 Dispatcher::sendStatusDatasetSegment(const Name& dataName, const Block& content,
305  time::milliseconds imsFresh, bool isFinalBlock)
306 {
307  // the first segment will be sent to both places (the face and the in-memory storage)
308  // other segments will be inserted to the in-memory storage only
309  auto destination = SendDestination::IMS;
310  if (dataName[-1].toSegment() == 0) {
311  destination = SendDestination::FACE_AND_IMS;
312  }
313 
314  MetaInfo metaInfo;
315  if (isFinalBlock) {
316  metaInfo.setFinalBlock(dataName[-1]);
317  }
318 
319  sendData(dataName, content, metaInfo, destination, imsFresh);
320 }
321 
324 {
325  if (!m_topLevelPrefixes.empty()) {
326  BOOST_THROW_EXCEPTION(std::domain_error("one or more top-level prefix has been added"));
327  }
328 
329  if (isOverlappedWithOthers(relPrefix)) {
330  BOOST_THROW_EXCEPTION(std::out_of_range("notification stream name overlaps"));
331  }
332 
333  // register a handler for the subscriber of this notification stream
334  // keep silent if Interest does not match a stored notification
335  m_handlers[relPrefix] = [this] (auto&&... args) {
336  this->queryStorage(std::forward<decltype(args)>(args)..., nullptr);
337  };
338  m_streams[relPrefix] = 0;
339 
340  return [=] (const Block& b) { postNotification(b, relPrefix); };
341 }
342 
343 void
344 Dispatcher::postNotification(const Block& notification, const PartialName& relPrefix)
345 {
346  if (m_topLevelPrefixes.empty() || m_topLevelPrefixes.size() > 1) {
347  NDN_LOG_WARN("postNotification: no top-level prefix or too many top-level prefixes");
348  return;
349  }
350 
351  Name streamName(m_topLevelPrefixes.begin()->second.topPrefix);
352  streamName.append(relPrefix);
353  streamName.appendSequenceNumber(m_streams[streamName]++);
354 
355  // notification is sent out via the face after inserting into the in-memory storage,
356  // because a request may be pending in the PIT
357  sendData(streamName, notification, {}, SendDestination::FACE_AND_IMS, DEFAULT_FRESHNESS_PERIOD);
358 }
359 
360 } // namespace mgmt
361 } // namespace ndn
represents a CachePolicy header field
const Name & getName() const
Definition: interest.hpp:133
Copyright (c) 2013-2017 Regents of the University of California.
Definition: common.hpp:65
std::function< void(const Block &notification)> PostNotification
a function to post a notification
Definition: dispatcher.hpp:124
represents a dispatcher on server side of NFD Management protocol
Definition: dispatcher.hpp:130
RejectReply
indicate how to reply in case authorization is rejected
Definition: dispatcher.hpp:49
MetaInfo & setFinalBlock(optional< name::Component > finalBlockId)
set FinalBlockId
Definition: meta-info.cpp:66
const RegisteredPrefixId * setInterestFilter(const InterestFilter &interestFilter, 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:232
reply with a ControlResponse where StatusCode is 403
CachePolicy & setPolicy(CachePolicyType policy)
set policy type code
Represents a TLV element of NDN packet format.
Definition: block.hpp:42
Represents an Interest packet.
Definition: interest.hpp:43
std::function< void(const std::string &requester)> AcceptContinuation
a function to be called if authorization is successful
Definition: dispatcher.hpp:45
Dispatcher(Face &face, KeyChain &keyChain, const security::SigningInfo &signingInfo=security::SigningInfo(), size_t imsCapacity=256)
constructor
Definition: dispatcher.cpp:45
const Block & wireEncode() const
#define NDN_LOG_INIT(name)
Define a non-member log module.
Definition: logger.hpp:163
Authorization makeAcceptAllAuthorization()
return an Authorization that accepts all Interests, with empty string as requester ...
Definition: dispatcher.cpp:34
Name & append(const Component &component)
Append a component.
Definition: name.hpp:248
Signing parameters passed to KeyChain.
void unregisterPrefix(const RegisteredPrefixId *registeredPrefixId, const UnregisterPrefixSuccessCallback &onSuccess, const UnregisterPrefixFailureCallback &onFailure)
Unregister prefix from RIB.
Definition: face.cpp:301
shared_ptr< const Data > find(const Interest &interest)
Finds the best match Data for an Interest.
MetaInfo & setType(uint32_t type)
set ContentType
Definition: meta-info.cpp:47
mgmt::ControlResponse ControlResponse
std::function< void(RejectReply reply)> RejectContinuation
a function to be called if authorization is rejected
Definition: dispatcher.hpp:60
Provide a communication channel with local or remote NDN forwarder.
Definition: face.hpp:90
void addTopPrefix(const Name &prefix, bool wantRegister=true, const security::SigningInfo &signingInfo=security::SigningInfo())
add a top-level prefix
Definition: dispatcher.cpp:67
A MetaInfo holds the meta info which is signed inside the data packet.
Definition: meta-info.hpp:58
size_t size() const
Get number of components.
Definition: name.hpp:146
Name & appendSequenceNumber(uint64_t seqNo)
Append a sequence number component.
Definition: name.hpp:418
Represents an absolute name.
Definition: name.hpp:42
bool isPrefixOf(const Name &other) const
Check if this name is a prefix of another name.
Definition: name.cpp:252
const time::milliseconds DEFAULT_FRESHNESS_PERIOD
Definition: dispatcher.cpp:31
void unsetInterestFilter(const RegisteredPrefixId *registeredPrefixId)
Remove the registered prefix entry with the registeredPrefixId.
Definition: face.cpp:285
base class for a struct that contains ControlCommand parameters
#define NDN_LOG_WARN(expression)
Log at WARN level.
Definition: logger.hpp:272
Represents a name component.
std::function< void(const Name &prefix, const Interest &interest, const ControlParameters &params, const CommandContinuation &done)> ControlCommandHandler
a function to handle an authorized ControlCommand
Definition: dispatcher.hpp:106
application-level nack
std::function< bool(const ControlParameters &params)> ValidateParameters
a function to validate input ControlParameters
Definition: dispatcher.hpp:90
void insert(const Data &data, const time::milliseconds &mustBeFreshProcessingWindow=INFINITE_WINDOW)
Inserts a Data packet.
void put(Data data)
Publish data packet.
Definition: face.cpp:216
void removeTopPrefix(const Name &prefix)
remove a top-level prefix
Definition: dispatcher.cpp:98
ControlCommand response.
void addStatusDataset(const PartialName &relPrefix, Authorization authorize, StatusDatasetHandler handle)
register a StatusDataset or a prefix under which StatusDatasets can be requested
Definition: dispatcher.cpp:246
provides a context for generating response to a StatusDataset request
Represents a Data packet.
Definition: data.hpp:35
std::function< void(const Name &prefix, const Interest &interest, const ControlParameters *params, const AcceptContinuation &accept, const RejectContinuation &reject)> Authorization
a function that performs authorization
Definition: dispatcher.hpp:77
#define NDN_LOG_ERROR(expression)
Log at ERROR level.
Definition: logger.hpp:277
const Component & get(ssize_t i) const
Get the component at the given index.
Definition: name.hpp:156
const RegisteredPrefixId * 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:272
represents an error in TLV encoding or decoding
PostNotification addNotificationStream(const PartialName &relPrefix)
register a NotificationStream
Definition: dispatcher.cpp:323
std::function< void(const Name &prefix, const Interest &interest, StatusDatasetContext &context)> StatusDatasetHandler
a function to handle a StatusDataset request
Definition: dispatcher.hpp:118