generic-link-service.cpp
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright (c) 2014-2020, Regents of the University of California,
4  * Arizona Board of Regents,
5  * Colorado State University,
6  * University Pierre & Marie Curie, Sorbonne University,
7  * Washington University in St. Louis,
8  * Beijing Institute of Technology,
9  * The University of Memphis.
10  *
11  * This file is part of NFD (Named Data Networking Forwarding Daemon).
12  * See AUTHORS.md for complete list of NFD authors and contributors.
13  *
14  * NFD is free software: you can redistribute it and/or modify it under the terms
15  * of the GNU General Public License as published by the Free Software Foundation,
16  * either version 3 of the License, or (at your option) any later version.
17  *
18  * NFD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
19  * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
20  * PURPOSE. See the GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License along with
23  * NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
24  */
25 
26 #include "generic-link-service.hpp"
27 
28 #include <ndn-cxx/lp/pit-token.hpp>
29 #include <ndn-cxx/lp/tags.hpp>
30 
31 #include <cmath>
32 
33 namespace nfd {
34 namespace face {
35 
36 NFD_LOG_INIT(GenericLinkService);
37 
38 constexpr size_t CONGESTION_MARK_SIZE = tlv::sizeOfVarNumber(lp::tlv::CongestionMark) + // type
39  tlv::sizeOfVarNumber(sizeof(uint64_t)) + // length
40  tlv::sizeOfNonNegativeInteger(UINT64_MAX); // value
41 
43  : m_options(options)
44  , m_fragmenter(m_options.fragmenterOptions, this)
45  , m_reassembler(m_options.reassemblerOptions, this)
46  , m_reliability(m_options.reliabilityOptions, this)
47  , m_lastSeqNo(-2)
48  , m_nextMarkTime(time::steady_clock::TimePoint::max())
49  , m_nMarkedSinceInMarkingState(0)
50 {
51  m_reassembler.beforeTimeout.connect([this] (auto...) { ++this->nReassemblyTimeouts; });
52  m_reliability.onDroppedInterest.connect([this] (const auto& i) { this->notifyDroppedInterest(i); });
53  nReassembling.observe(&m_reassembler);
54 }
55 
56 void
58 {
59  m_options = options;
60  m_fragmenter.setOptions(m_options.fragmenterOptions);
61  m_reassembler.setOptions(m_options.reassemblerOptions);
62  m_reliability.setOptions(m_options.reliabilityOptions);
63 }
64 
65 ssize_t
67 {
68  // Since MTU_UNLIMITED is negative, it will implicitly override any finite override MTU
69  return std::min(m_options.overrideMtu, getTransport()->getMtu());
70 }
71 
72 bool
74 {
75  // Not allowed to override unlimited transport MTU
76  if (getTransport()->getMtu() == MTU_UNLIMITED) {
77  return false;
78  }
79 
80  // Override MTU must be at least MIN_MTU (also implicitly forbids MTU_UNLIMITED and MTU_INVALID)
81  return mtu >= MIN_MTU;
82 }
83 
84 void
85 GenericLinkService::requestIdlePacket()
86 {
87  // No need to request Acks to attach to this packet from LpReliability, as they are already
88  // attached in sendLpPacket
89  NFD_LOG_FACE_TRACE("IDLE packet requested");
90  this->sendLpPacket({});
91 }
92 
93 void
94 GenericLinkService::sendLpPacket(lp::Packet&& pkt)
95 {
96  const ssize_t mtu = getEffectiveMtu();
97 
98  if (m_options.reliabilityOptions.isEnabled) {
99  m_reliability.piggyback(pkt, mtu);
100  }
101 
102  if (m_options.allowCongestionMarking) {
103  checkCongestionLevel(pkt);
104  }
105 
106  auto block = pkt.wireEncode();
107  if (mtu != MTU_UNLIMITED && block.size() > static_cast<size_t>(mtu)) {
108  ++this->nOutOverMtu;
109  NFD_LOG_FACE_WARN("attempted to send packet over MTU limit");
110  return;
111  }
112  this->sendPacket(block);
113 }
114 
115 void
116 GenericLinkService::doSendInterest(const Interest& interest)
117 {
118  lp::Packet lpPacket(interest.wireEncode());
119 
120  encodeLpFields(interest, lpPacket);
121 
122  this->sendNetPacket(std::move(lpPacket), true);
123 }
124 
125 void
126 GenericLinkService::doSendData(const Data& data)
127 {
128  lp::Packet lpPacket(data.wireEncode());
129 
130  encodeLpFields(data, lpPacket);
131 
132  this->sendNetPacket(std::move(lpPacket), false);
133 }
134 
135 void
136 GenericLinkService::doSendNack(const lp::Nack& nack)
137 {
138  lp::Packet lpPacket(nack.getInterest().wireEncode());
139  lpPacket.add<lp::NackField>(nack.getHeader());
140 
141  encodeLpFields(nack, lpPacket);
142 
143  this->sendNetPacket(std::move(lpPacket), false);
144 }
145 
146 void
147 GenericLinkService::assignSequences(std::vector<lp::Packet>& pkts)
148 {
149  std::for_each(pkts.begin(), pkts.end(), [this] (lp::Packet& pkt) {
150  pkt.set<lp::SequenceField>(++m_lastSeqNo);
151  });
152 }
153 
154 void
155 GenericLinkService::encodeLpFields(const ndn::PacketBase& netPkt, lp::Packet& lpPacket)
156 {
157  if (m_options.allowLocalFields) {
158  auto incomingFaceIdTag = netPkt.getTag<lp::IncomingFaceIdTag>();
159  if (incomingFaceIdTag != nullptr) {
160  lpPacket.add<lp::IncomingFaceIdField>(*incomingFaceIdTag);
161  }
162  }
163 
164  auto congestionMarkTag = netPkt.getTag<lp::CongestionMarkTag>();
165  if (congestionMarkTag != nullptr) {
166  lpPacket.add<lp::CongestionMarkField>(*congestionMarkTag);
167  }
168 
169  if (m_options.allowSelfLearning) {
170  auto nonDiscoveryTag = netPkt.getTag<lp::NonDiscoveryTag>();
171  if (nonDiscoveryTag != nullptr) {
172  lpPacket.add<lp::NonDiscoveryField>(*nonDiscoveryTag);
173  }
174 
175  auto prefixAnnouncementTag = netPkt.getTag<lp::PrefixAnnouncementTag>();
176  if (prefixAnnouncementTag != nullptr) {
177  lpPacket.add<lp::PrefixAnnouncementField>(*prefixAnnouncementTag);
178  }
179  }
180 
181  auto pitToken = netPkt.getTag<lp::PitToken>();
182  if (pitToken != nullptr) {
183  lpPacket.add<lp::PitTokenField>(*pitToken);
184  }
185 }
186 
187 void
188 GenericLinkService::sendNetPacket(lp::Packet&& pkt, bool isInterest)
189 {
190  std::vector<lp::Packet> frags;
191  ssize_t mtu = getEffectiveMtu();
192 
193  // Make space for feature fields in fragments
194  if (m_options.reliabilityOptions.isEnabled && mtu != MTU_UNLIMITED) {
196  }
197 
198  if (m_options.allowCongestionMarking && mtu != MTU_UNLIMITED) {
199  mtu -= CONGESTION_MARK_SIZE;
200  }
201 
202  // An MTU of 0 is allowed but will cause all packets to be dropped before transmission
203  BOOST_ASSERT(mtu == MTU_UNLIMITED || mtu >= 0);
204 
205  if (m_options.allowFragmentation && mtu != MTU_UNLIMITED) {
206  bool isOk = false;
207  std::tie(isOk, frags) = m_fragmenter.fragmentPacket(pkt, mtu);
208  if (!isOk) {
209  // fragmentation failed (warning is logged by LpFragmenter)
210  ++this->nFragmentationErrors;
211  return;
212  }
213  }
214  else {
215  if (m_options.reliabilityOptions.isEnabled) {
216  frags.push_back(pkt);
217  }
218  else {
219  frags.push_back(std::move(pkt));
220  }
221  }
222 
223  if (frags.size() == 1) {
224  // even if indexed fragmentation is enabled, the fragmenter should not
225  // fragment the packet if it can fit in MTU
226  BOOST_ASSERT(!frags.front().has<lp::FragIndexField>());
227  BOOST_ASSERT(!frags.front().has<lp::FragCountField>());
228  }
229 
230  // Only assign sequences to fragments if reliability enabled or if packet contains >1 fragment
231  if (m_options.reliabilityOptions.isEnabled || frags.size() > 1) {
232  // Assign sequences to all fragments
233  this->assignSequences(frags);
234  }
235 
236  if (m_options.reliabilityOptions.isEnabled && frags.front().has<lp::FragmentField>()) {
237  m_reliability.handleOutgoing(frags, std::move(pkt), isInterest);
238  }
239 
240  for (lp::Packet& frag : frags) {
241  this->sendLpPacket(std::move(frag));
242  }
243 }
244 
245 void
246 GenericLinkService::checkCongestionLevel(lp::Packet& pkt)
247 {
248  ssize_t sendQueueLength = getTransport()->getSendQueueLength();
249  // The transport must support retrieving the current send queue length
250  if (sendQueueLength < 0) {
251  return;
252  }
253 
254  if (sendQueueLength > 0) {
255  NFD_LOG_FACE_TRACE("txqlen=" << sendQueueLength << " threshold=" <<
256  m_options.defaultCongestionThreshold << " capacity=" <<
257  getTransport()->getSendQueueCapacity());
258  }
259 
260  // sendQueue is above target
261  if (static_cast<size_t>(sendQueueLength) > m_options.defaultCongestionThreshold) {
262  const auto now = time::steady_clock::now();
263 
264  if (m_nextMarkTime == time::steady_clock::TimePoint::max()) {
265  m_nextMarkTime = now + m_options.baseCongestionMarkingInterval;
266  }
267  // Mark packet if sendQueue stays above target for one interval
268  else if (now >= m_nextMarkTime) {
269  pkt.set<lp::CongestionMarkField>(1);
271  NFD_LOG_FACE_DEBUG("LpPacket was marked as congested");
272 
273  ++m_nMarkedSinceInMarkingState;
274  // Decrease the marking interval by the inverse of the square root of the number of packets
275  // marked in this incident of congestion
276  time::nanoseconds interval(static_cast<time::nanoseconds::rep>(
277  m_options.baseCongestionMarkingInterval.count() /
278  std::sqrt(m_nMarkedSinceInMarkingState + 1)));
279  m_nextMarkTime += interval;
280  }
281  }
282  else if (m_nextMarkTime != time::steady_clock::TimePoint::max()) {
283  // Congestion incident has ended, so reset
284  NFD_LOG_FACE_DEBUG("Send queue length dropped below congestion threshold");
285  m_nextMarkTime = time::steady_clock::TimePoint::max();
286  m_nMarkedSinceInMarkingState = 0;
287  }
288 }
289 
290 void
291 GenericLinkService::doReceivePacket(const Block& packet, const EndpointId& endpoint)
292 {
293  try {
294  lp::Packet pkt(packet);
295 
296  if (m_options.reliabilityOptions.isEnabled) {
297  if (!m_reliability.processIncomingPacket(pkt)) {
298  NFD_LOG_FACE_TRACE("received duplicate fragment: DROP");
299  ++this->nDuplicateSequence;
300  return;
301  }
302  }
303 
304  if (!pkt.has<lp::FragmentField>()) {
305  NFD_LOG_FACE_TRACE("received IDLE packet: DROP");
306  return;
307  }
308 
309  if ((pkt.has<lp::FragIndexField>() || pkt.has<lp::FragCountField>()) &&
310  !m_options.allowReassembly) {
311  NFD_LOG_FACE_WARN("received fragment, but reassembly disabled: DROP");
312  return;
313  }
314 
315  bool isReassembled = false;
316  Block netPkt;
317  lp::Packet firstPkt;
318  std::tie(isReassembled, netPkt, firstPkt) = m_reassembler.receiveFragment(endpoint, pkt);
319  if (isReassembled) {
320  this->decodeNetPacket(netPkt, firstPkt, endpoint);
321  }
322  }
323  catch (const tlv::Error& e) {
324  ++this->nInLpInvalid;
325  NFD_LOG_FACE_WARN("packet parse error (" << e.what() << "): DROP");
326  }
327 }
328 
329 void
330 GenericLinkService::decodeNetPacket(const Block& netPkt, const lp::Packet& firstPkt,
331  const EndpointId& endpointId)
332 {
333  try {
334  switch (netPkt.type()) {
335  case tlv::Interest:
336  if (firstPkt.has<lp::NackField>()) {
337  this->decodeNack(netPkt, firstPkt, endpointId);
338  }
339  else {
340  this->decodeInterest(netPkt, firstPkt, endpointId);
341  }
342  break;
343  case tlv::Data:
344  this->decodeData(netPkt, firstPkt, endpointId);
345  break;
346  default:
347  ++this->nInNetInvalid;
348  NFD_LOG_FACE_WARN("unrecognized network-layer packet TLV-TYPE " << netPkt.type() << ": DROP");
349  return;
350  }
351  }
352  catch (const tlv::Error& e) {
353  ++this->nInNetInvalid;
354  NFD_LOG_FACE_WARN("packet parse error (" << e.what() << "): DROP");
355  }
356 }
357 
358 void
359 GenericLinkService::decodeInterest(const Block& netPkt, const lp::Packet& firstPkt,
360  const EndpointId& endpointId)
361 {
362  BOOST_ASSERT(netPkt.type() == tlv::Interest);
363  BOOST_ASSERT(!firstPkt.has<lp::NackField>());
364 
365  // forwarding expects Interest to be created with make_shared
366  auto interest = make_shared<Interest>(netPkt);
367 
368  if (firstPkt.has<lp::NextHopFaceIdField>()) {
369  if (m_options.allowLocalFields) {
370  interest->setTag(make_shared<lp::NextHopFaceIdTag>(firstPkt.get<lp::NextHopFaceIdField>()));
371  }
372  else {
373  NFD_LOG_FACE_WARN("received NextHopFaceId, but local fields disabled: DROP");
374  return;
375  }
376  }
377 
378  if (firstPkt.has<lp::CachePolicyField>()) {
379  ++this->nInNetInvalid;
380  NFD_LOG_FACE_WARN("received CachePolicy with Interest: DROP");
381  return;
382  }
383 
384  if (firstPkt.has<lp::IncomingFaceIdField>()) {
385  NFD_LOG_FACE_WARN("received IncomingFaceId: IGNORE");
386  }
387 
388  if (firstPkt.has<lp::CongestionMarkField>()) {
389  interest->setTag(make_shared<lp::CongestionMarkTag>(firstPkt.get<lp::CongestionMarkField>()));
390  }
391 
392  if (firstPkt.has<lp::NonDiscoveryField>()) {
393  if (m_options.allowSelfLearning) {
394  interest->setTag(make_shared<lp::NonDiscoveryTag>(firstPkt.get<lp::NonDiscoveryField>()));
395  }
396  else {
397  NFD_LOG_FACE_WARN("received NonDiscovery, but self-learning disabled: IGNORE");
398  }
399  }
400 
401  if (firstPkt.has<lp::PrefixAnnouncementField>()) {
402  ++this->nInNetInvalid;
403  NFD_LOG_FACE_WARN("received PrefixAnnouncement with Interest: DROP");
404  return;
405  }
406 
407  if (firstPkt.has<lp::PitTokenField>()) {
408  interest->setTag(make_shared<lp::PitToken>(firstPkt.get<lp::PitTokenField>()));
409  }
410 
411  this->receiveInterest(*interest, endpointId);
412 }
413 
414 void
415 GenericLinkService::decodeData(const Block& netPkt, const lp::Packet& firstPkt,
416  const EndpointId& endpointId)
417 {
418  BOOST_ASSERT(netPkt.type() == tlv::Data);
419 
420  // forwarding expects Data to be created with make_shared
421  auto data = make_shared<Data>(netPkt);
422 
423  if (firstPkt.has<lp::NackField>()) {
424  ++this->nInNetInvalid;
425  NFD_LOG_FACE_WARN("received Nack with Data: DROP");
426  return;
427  }
428 
429  if (firstPkt.has<lp::NextHopFaceIdField>()) {
430  ++this->nInNetInvalid;
431  NFD_LOG_FACE_WARN("received NextHopFaceId with Data: DROP");
432  return;
433  }
434 
435  if (firstPkt.has<lp::CachePolicyField>()) {
436  // CachePolicy is unprivileged and does not require allowLocalFields option.
437  // In case of an invalid CachePolicyType, get<lp::CachePolicyField> will throw,
438  // so it's unnecessary to check here.
439  data->setTag(make_shared<lp::CachePolicyTag>(firstPkt.get<lp::CachePolicyField>()));
440  }
441 
442  if (firstPkt.has<lp::IncomingFaceIdField>()) {
443  NFD_LOG_FACE_WARN("received IncomingFaceId: IGNORE");
444  }
445 
446  if (firstPkt.has<lp::CongestionMarkField>()) {
447  data->setTag(make_shared<lp::CongestionMarkTag>(firstPkt.get<lp::CongestionMarkField>()));
448  }
449 
450  if (firstPkt.has<lp::NonDiscoveryField>()) {
451  ++this->nInNetInvalid;
452  NFD_LOG_FACE_WARN("received NonDiscovery with Data: DROP");
453  return;
454  }
455 
456  if (firstPkt.has<lp::PrefixAnnouncementField>()) {
457  if (m_options.allowSelfLearning) {
458  data->setTag(make_shared<lp::PrefixAnnouncementTag>(firstPkt.get<lp::PrefixAnnouncementField>()));
459  }
460  else {
461  NFD_LOG_FACE_WARN("received PrefixAnnouncement, but self-learning disabled: IGNORE");
462  }
463  }
464 
465  this->receiveData(*data, endpointId);
466 }
467 
468 void
469 GenericLinkService::decodeNack(const Block& netPkt, const lp::Packet& firstPkt,
470  const EndpointId& endpointId)
471 {
472  BOOST_ASSERT(netPkt.type() == tlv::Interest);
473  BOOST_ASSERT(firstPkt.has<lp::NackField>());
474 
475  lp::Nack nack((Interest(netPkt)));
476  nack.setHeader(firstPkt.get<lp::NackField>());
477 
478  if (firstPkt.has<lp::NextHopFaceIdField>()) {
479  ++this->nInNetInvalid;
480  NFD_LOG_FACE_WARN("received NextHopFaceId with Nack: DROP");
481  return;
482  }
483 
484  if (firstPkt.has<lp::CachePolicyField>()) {
485  ++this->nInNetInvalid;
486  NFD_LOG_FACE_WARN("received CachePolicy with Nack: DROP");
487  return;
488  }
489 
490  if (firstPkt.has<lp::IncomingFaceIdField>()) {
491  NFD_LOG_FACE_WARN("received IncomingFaceId: IGNORE");
492  }
493 
494  if (firstPkt.has<lp::CongestionMarkField>()) {
495  nack.setTag(make_shared<lp::CongestionMarkTag>(firstPkt.get<lp::CongestionMarkField>()));
496  }
497 
498  if (firstPkt.has<lp::NonDiscoveryField>()) {
499  ++this->nInNetInvalid;
500  NFD_LOG_FACE_WARN("received NonDiscovery with Nack: DROP");
501  return;
502  }
503 
504  if (firstPkt.has<lp::PrefixAnnouncementField>()) {
505  ++this->nInNetInvalid;
506  NFD_LOG_FACE_WARN("received PrefixAnnouncement with Nack: DROP");
507  return;
508  }
509 
510  this->receiveNack(nack, endpointId);
511 }
512 
513 } // namespace face
514 } // namespace nfd
#define NFD_LOG_FACE_TRACE(msg)
Log a message at TRACE level.
virtual ssize_t getSendQueueLength()
Definition: transport.hpp:256
const ssize_t MTU_UNLIMITED
indicates the transport has no limit on payload size
Definition: transport.hpp:91
#define NFD_LOG_FACE_DEBUG(msg)
Log a message at DEBUG level.
void piggyback(lp::Packet &pkt, ssize_t mtu)
called by GenericLinkService to attach Acks onto an outgoing LpPacket
std::tuple< bool, Block, lp::Packet > receiveFragment(EndpointId remoteEndpoint, const lp::Packet &packet)
adds received fragment to the buffer
bool isEnabled
enables link-layer reliability
uint64_t EndpointId
Identifies a remote endpoint on the link.
Definition: face-common.hpp:71
void setOptions(const Options &options)
set options for fragmenter
#define NFD_LOG_FACE_WARN(msg)
Log a message at WARN level.
static constexpr size_t RESERVED_HEADER_SPACE
TxSequence TLV-TYPE (3 octets) + TLV-LENGTH (1 octet) + lp::Sequence (8 octets)
Copyright (c) 2014-2015, Regents of the University of California, Arizona Board of Regents...
Definition: algorithm.hpp:32
signal::Signal< LpReassembler, EndpointId, size_t > beforeTimeout
signals before a partial packet is dropped due to timeout
std::tuple< bool, std::vector< lp::Packet > > fragmentPacket(const lp::Packet &packet, size_t mtu)
fragments a network-layer packet into link-layer packets
void handleOutgoing(std::vector< lp::Packet > &frags, lp::Packet &&pkt, bool isInterest)
observe outgoing fragment(s) of a network packet and store for potential retransmission ...
void setOptions(const Options &options)
set options for reliability
#define NFD_LOG_INIT(name)
Definition: logger.hpp:31
signal::Signal< LpReliability, Interest > onDroppedInterest
signals on Interest dropped by reliability system for exceeding allowed number of retx ...
bool processIncomingPacket(const lp::Packet &pkt)
extract and parse all Acks and add Ack for contained Fragment (if any) to AckQueue ...
const ssize_t MIN_MTU
Minimum MTU that may be set.
Definition: face-common.hpp:61
constexpr size_t CONGESTION_MARK_SIZE
void setOptions(const Options &options)
set options for reassembler