shared_ptr<const Data> InMemoryStorage::find(const Interest& interest) { // if the interest contains implicit digest, it is possible to directly locate a packet. auto it = m_cache.get<byFullName>().find(interest.getName()); // if a packet is located by its full name, it must be the packet to return. if (it != m_cache.get<byFullName>().end()) { return ((*it)->getData()).shared_from_this(); } // if the packet is not discovered by last step, either the packet is not in the storage or // the interest doesn't contains implicit digest. it = m_cache.get<byFullName>().lower_bound(interest.getName()); if (it == m_cache.get<byFullName>().end()) { return nullptr; } // to locate the element that has a just smaller name than the interest's if (it != m_cache.get<byFullName>().begin()) { it--; } InMemoryStorageEntry* ret = selectChild(interest, it); if (ret == nullptr) { return nullptr; } // let derived class do something with the entry afterAccess(ret); return ret->getData().shared_from_this(); }
bool FaceManager::extractLocalControlParameters(const Interest& request, ControlParameters& parameters, ControlCommand& command, shared_ptr<LocalFace>& outFace, LocalControlFeature& outFeature) { if (!validateParameters(command, parameters)) { sendResponse(request.getName(), 400, "Malformed command"); return false; } shared_ptr<Face> face = m_faceTable.get(request.getIncomingFaceId()); if (!static_cast<bool>(face)) { NFD_LOG_DEBUG("command result: faceid " << request.getIncomingFaceId() << " not found"); sendResponse(request.getName(), 410, "Face not found"); return false; } else if (!face->isLocal()) { NFD_LOG_DEBUG("command result: cannot enable local control on non-local faceid " << face->getId()); sendResponse(request.getName(), 412, "Face is non-local"); return false; } outFace = dynamic_pointer_cast<LocalFace>(face); outFeature = static_cast<LocalControlFeature>(parameters.getLocalControlFeature()); return true; }
void WeightedLoadBalancerStrategy::afterReceiveInterest(const Face& inFace, const Interest& interest, shared_ptr<fib::Entry> fibEntry, shared_ptr<pit::Entry> pitEntry) { NFD_LOG_TRACE("Received Interest: " << interest.getName()); // not a new Interest, don't forward if (pitEntry->hasUnexpiredOutRecords()) { NFD_LOG_TRACE("Not a new Interest, " << interest.getName() << ", refusing to forward"); return; } // create timer information and attach to PIT entry pitEntry->setStrategyInfo<MyPitInfo>(make_shared<MyPitInfo>()); shared_ptr<MyMeasurementInfo> measurementsEntryInfo = myGetOrCreateMyMeasurementInfo(fibEntry); // reconcile differences between incoming nexthops and those stored // on our custom measurement entry info measurementsEntryInfo->updateStoredNextHops(fibEntry->getNextHops()); if (!this->mySendInterest(interest, measurementsEntryInfo, pitEntry)) { this->rejectPendingInterest(pitEntry); BOOST_ASSERT(false); } }
void Producer::onInterest(const Interest& interest) { BOOST_ASSERT(m_store.size() > 0); if (m_isVerbose) std::cerr << "Interest: " << interest << std::endl; const Name& name = interest.getName(); shared_ptr<Data> data; // is this a discovery Interest or a sequence retrieval? if (name.size() == m_versionedPrefix.size() + 1 && m_versionedPrefix.isPrefixOf(name) && name[-1].isSegment()) { const auto segmentNo = static_cast<size_t>(interest.getName()[-1].toSegment()); // specific segment retrieval if (segmentNo < m_store.size()) { data = m_store[segmentNo]; } } else if (interest.matchesData(*m_store[0])) { // Interest has version and is looking for the first segment or has no version data = m_store[0]; } if (data != nullptr) { if (m_isVerbose) std::cerr << "Data: " << *data << std::endl; m_face.put(*data); } }
void CommandInterestGenerator::generate (Interest& interest, KeyChain& keyChain, const Name& certificateName, WireFormat& wireFormat) { MillisecondsSince1970 timestamp = ::round(ndn_getNowMilliseconds()); while (timestamp <= lastTimestamp_) timestamp += 1.0; // The timestamp is encoded as a TLV nonNegativeInteger. TlvEncoder encoder(8); encoder.writeNonNegativeInteger((uint64_t)timestamp); interest.getName().append(Blob(encoder.finish())); // The random value is a TLV nonNegativeInteger too, but we know it is 8 bytes, // so we don't need to call the nonNegativeInteger encoder. uint8_t randomBuffer[8]; ndn_Error error; if ((error = CryptoLite::generateRandomBytes(randomBuffer, sizeof(randomBuffer)))) throw runtime_error(ndn_getErrorString(error)); interest.getName().append(randomBuffer, sizeof(randomBuffer)); keyChain.sign(interest, certificateName, wireFormat); if (interest.getInterestLifetimeMilliseconds() < 0) // The caller has not set the interest lifetime, so set it here. interest.setInterestLifetimeMilliseconds(1000.0); // We successfully signed the interest, so update the timestamp. lastTimestamp_ = timestamp; }
void PipelineInterests::handleNack(const Interest& interest, const lp::Nack& nack) { if (m_options.isVerbose) std::cerr << "Received Nack with reason " << nack.getReason() << " for Interest " << interest << std::endl; switch (nack.getReason()) { case lp::NackReason::DUPLICATE: { break; // ignore duplicates } case lp::NackReason::CONGESTION: { // treated the same as timeout for now uint64_t segno = interest.getName()[-1].toSegment(); m_segmentInfoMap[segno]->state = inRetxQueue; // update state handleTimeout(1); break; } default: { m_hasError = true; fail("Could not retrieve data for " + interest.getName().toUri() + ", reason: " + boost::lexical_cast<std::string>(nack.getReason())); break; } } }
virtual uint64_t expressInterest (const Interest& interest, const OnData& onData, const OnTimeout& onTimeout, const OnNetworkNack& onNetworkNack, WireFormat& wireFormat = *WireFormat::getDefaultWireFormat()) { if (expectedInterest_ != interest.getName()) throw runtime_error("TestFace::expressInterest: Not the expectedInterest_"); bool gotInterestName = false; Name interestName; for (size_t i = 0; i < 3; ++i) { interestName = Name(interest.getName()); if (i == 0) interestName.append(timeMarkerFirstHop_); else if (i == 1) interestName.append(timeMarkerSecondHop_); else if (i == 2) interestName.append(timeMarkerThirdHop_); // matchesName will check the Exclude. if (interest.matchesName(interestName)) { gotInterestName = true; ++(*requestCount_); break; } } if (gotInterestName) onData(ptr_lib::make_shared<Interest>(interest), parent_->encryptionKeys[interestName]); return 0; }
/** @brief determines if entry can satisfy interest * @param hash SHA256 hash of PublisherPublicKeyLocator if exists in interest, otherwise ignored */ static bool matchesSimpleSelectors(const Interest& interest, ndn::ConstBufferPtr& hash, const Index::Entry& entry) { const Name& fullName = entry.getName(); if (!interest.getName().isPrefixOf(fullName)) return false; size_t nSuffixComponents = fullName.size() - interest.getName().size(); if (interest.getMinSuffixComponents() >= 0 && nSuffixComponents < static_cast<size_t>(interest.getMinSuffixComponents())) return false; if (interest.getMaxSuffixComponents() >= 0 && nSuffixComponents > static_cast<size_t>(interest.getMaxSuffixComponents())) return false; if (!interest.getExclude().empty() && entry.getName().size() > interest.getName().size() && interest.getExclude().isExcluded(entry.getName()[interest.getName().size()])) { return false; } if (!interest.getPublisherPublicKeyLocator().empty()) { if (*entry.getKeyLocatorHash() != *hash) return false; } return true; }
void Forwarder::onIncomingInterest(Face& inFace, const Interest& interest) { // receive Interest NFD_LOG_DEBUG("onIncomingInterest face=" << inFace.getId() << " interest=" << interest.getName()); const_cast<Interest&>(interest).setIncomingFaceId(inFace.getId()); ++m_counters.getNInInterests(); // /localhost scope control bool isViolatingLocalhost = !inFace.isLocal() && LOCALHOST_NAME.isPrefixOf(interest.getName()); if (isViolatingLocalhost) { NFD_LOG_DEBUG("onIncomingInterest face=" << inFace.getId() << " interest=" << interest.getName() << " violates /localhost"); // (drop) return; } // PIT insert shared_ptr<pit::Entry> pitEntry = m_pit.insert(interest).first; // detect duplicate Nonce int dnw = pitEntry->findNonce(interest.getNonce(), inFace); bool hasDuplicateNonce = (dnw != pit::DUPLICATE_NONCE_NONE) || m_deadNonceList.has(interest.getName(), interest.getNonce()); if (hasDuplicateNonce) { // goto Interest loop pipeline this->onInterestLoop(inFace, interest, pitEntry); return; } // cancel unsatisfy & straggler timer this->cancelUnsatisfyAndStragglerTimer(pitEntry); // is pending? const pit::InRecordCollection& inRecords = pitEntry->getInRecords(); bool isPending = inRecords.begin() != inRecords.end(); if (!isPending) { if (m_csFromNdnSim == nullptr) { m_cs.find(interest, bind(&Forwarder::onContentStoreHit, this, ref(inFace), pitEntry, _1, _2), bind(&Forwarder::onContentStoreMiss, this, ref(inFace), pitEntry, _1)); } else { shared_ptr<Data> match = m_csFromNdnSim->Lookup(interest.shared_from_this()); if (match != nullptr) { this->onContentStoreHit(inFace, pitEntry, interest, *match); } else { this->onContentStoreMiss(inFace, pitEntry, interest); } } } else { this->onContentStoreMiss(inFace, pitEntry, interest); } }
virtual bool match(const Interest& interest) { if (interest.getName().size() < 2) return false; Name signedName = interest.getName().getPrefix(-2); return match(signedName); }
bool match(const Interest& interest) { if (interest.getName().size() < signed_interest::MIN_LENGTH) return false; Name unsignedName = interest.getName().getPrefix(-signed_interest::MIN_LENGTH); return matchName(unsignedName); }
bool Entry::canMatch(const Interest& interest, size_t nEqualNameComps) const { BOOST_ASSERT(m_interest->getName().compare(0, nEqualNameComps, interest.getName(), 0, nEqualNameComps) == 0); return m_interest->getName().compare(nEqualNameComps, Name::npos, interest.getName(), nEqualNameComps) == 0 && m_interest->getSelectors() == interest.getSelectors(); /// \todo #3162 match Link field }
void onInterest(const Interest& interest) { Name interestName = interest.getName(); //interestName.append(".txt"); // std::cout << "Interest Received = "<< interestName << std::endl; size_t segnum = static_cast<size_t>(interest.getName().rbegin()->toSegment()); if(segnum<m_store.size()){ m_face.put(*m_store[segnum]); } }
/** @brief Verify the interest against the SHA256 signature. * * (Note the signature covers the first n-2 name components). */ static bool verifySignature(const Interest& interest, const DigestSha256& sig) { if (interest.getName().size() < 2) return false; const Name& name = interest.getName(); return verifySignature(name.wireEncode().value(), name.wireEncode().value_size() - name[-1].size(), sig); }
bool check(const Interest& interest, const KeyLocator& keyLocator, std::string& failInfo) { if (interest.getName().size() < signed_interest::MIN_LENGTH) { failInfo = "No Signature"; return false; } Name signedName = interest.getName().getPrefix(-signed_interest::MIN_LENGTH); return check(signedName, keyLocator, failInfo); }
/** @brief Verify the interest using the publicKey against the SHA256-RSA signature. * * (Note the signature covers the first n-2 name components). */ static bool verifySignature(const Interest& interest, const Signature& sig, const v1::PublicKey& publicKey) { if (interest.getName().size() < 2) return false; const Name& name = interest.getName(); return verifySignature(name.wireEncode().value(), name.wireEncode().value_size() - name[-1].size(), sig, publicKey); }
shared_ptr<Data> StorageEngineImpl::read(const Interest &interest) { shared_ptr<Data> data; #if HAVE_PERSISTENT_STORAGE bool canBePrefix = interest.getCanBePrefix(); if (canBePrefix) { // extract by prefix match Name prefix = interest.getName(), keyName; auto it = db_->NewIterator(db_namespace::ReadOptions()); std::string key = ""; bool checkMaxSuffixComponents = interest.getMaxSuffixComponents() != -1; bool checkMinSuffixComponents = interest.getMinSuffixComponents() != -1; for (it->Seek(prefix.toUri()); it->Valid() && it->key().starts_with(prefix.toUri()); it->Next()) { if (checkMaxSuffixComponents || checkMinSuffixComponents) { keyName = Name(it->key().ToString()); int nSuffixComponents = keyName.size() - prefix.size(); bool passCheck = false; if (checkMaxSuffixComponents && nSuffixComponents <= interest.getMaxSuffixComponents()) passCheck = true; if (checkMinSuffixComponents && nSuffixComponents >= interest.getMinSuffixComponents()) passCheck = true; if (passCheck) key = it->key().ToString(); } else key = it->key().ToString(); } if (key != "") data = get(Name(key)); delete it; } else data = get(interest.getName()); #endif return data; }
void FaceManager::listQueriedFaces(const Interest& request) { NFD_LOG_DEBUG("in listQueriedFaces"); const Name& query = request.getName(); const size_t queryNComps = query.size(); if (queryNComps < FACES_QUERY_DATASET_NCOMPS || !FACES_QUERY_DATASET_PREFIX.isPrefixOf(query)) { NFD_LOG_DEBUG("query result: malformed"); sendNack(query); return; } ndn::nfd::FaceQueryFilter faceFilter; try { faceFilter.wireDecode(query[-1].blockFromValue()); } catch (tlv::Error&) { NFD_LOG_DEBUG("query result: malformed filter"); sendNack(query); return; } FaceQueryStatusPublisher faceQueryStatusPublisher(m_faceTable, *m_face, query, faceFilter, m_keyChain); faceQueryStatusPublisher.publish(); }
void onFileInterest(const InterestFilter& filter, const Interest& interest){ int currentPacketID = interest.getName().get(-1).toSegmentOffset(); m_face.put(*m_store[currentPacketID]); std::cout <<"RECEVE INTerest, send data id:\t" << currentPacketID << std::endl; }
iterator Cs::findRightmost(const Interest& interest, iterator first, iterator last) const { // Each loop visits a sub-namespace under a prefix one component longer than Interest Name. // If there is a match in that sub-namespace, the leftmost match is returned; // otherwise, loop continues. size_t interestNameLength = interest.getName().size(); for (iterator right = last; right != first;) { iterator prev = std::prev(right); // special case: [first,prev] have exact Names if (prev->getName().size() == interestNameLength) { NFD_LOG_TRACE(" find-among-exact " << prev->getName()); iterator matchExact = this->findRightmostAmongExact(interest, first, right); return matchExact == right ? last : matchExact; } Name prefix = prev->getName().getPrefix(interestNameLength + 1); iterator left = m_table.lower_bound(prefix); // normal case: [left,right) are under one-component-longer prefix NFD_LOG_TRACE(" find-under-prefix " << prefix); iterator match = this->findLeftmost(interest, left, right); if (match != right) { return match; } right = left; } return last; }
void MadmStrategy::probeInterests(const shared_ptr<Face> outFace, const Interest& interest, StrategyRequirements &requirements, const fib::NextHopList& nexthops, shared_ptr<pit::Entry> pitEntry) { for (auto n : nexthops) { const shared_ptr<Face>& thisFace = n.getFace(); bool costTooHigh = false; if (requirements.getLimits(RequirementType::COST).second != -1) { costTooHigh = costMap[thisFace->getId()].getCost() > (requirements.getLimits(RequirementType::COST)).second; if (costTooHigh) { NFD_LOG_DEBUG( "Cost too high: " << costMap[thisFace->getId()].getCost() << " > " << (requirements.getLimits(RequirementType::COST)).second); } } if (thisFace != outFace && !costTooHigh) { NFD_LOG_TRACE("Probing face: " << thisFace->getId()); faceInfoTable[thisFace->getId()].addSentInterest(interest.getName().toUri()); this->sendInterest(pitEntry, thisFace, true); } } }
bool Interest::matchesInterest(const Interest& other) const { /// @todo #3162 match ForwardingHint field return (this->getName() == other.getName() && this->getSelectors() == other.getSelectors()); }
bool Interest::matchesInterest(const Interest& other) const { return getName() == other.getName() && getCanBePrefix() == other.getCanBePrefix() && getMustBeFresh() == other.getMustBeFresh(); }
void MulticastStrategy::afterReceiveInterest(const Face& inFace, const Interest& interest, shared_ptr<fib::Entry> fibEntry, shared_ptr<pit::Entry> pitEntry) { std::string interest_name = interest.getName().toUri(); if (my_panini_fib::has_prefix(interest_name, "/nac")) { return; } else if (my_panini_fib::has_prefix(interest_name, "/nam_msg")) { return; } else if (my_panini_fib::has_prefix(interest_name, "/panini")) { m_my_logger.log("panini", "afterRecvInterest", interest_name, 0); } const fib::NextHopList& nexthops = fibEntry->getNextHops(); for (fib::NextHopList::const_iterator it = nexthops.begin(); it != nexthops.end(); ++it) { shared_ptr<Face> outFace = it->getFace(); if (pitEntry->canForwardTo(*outFace)) { this->sendInterest(pitEntry, outFace); m_my_logger.log("panini", "afterSendBroadcastInterest", interest_name); } } if (!pitEntry->hasUnexpiredOutRecords()) { this->rejectPendingInterest(pitEntry); } }
void FibManager::onFibRequest(const Interest& request) { const Name& command = request.getName(); const size_t commandNComps = command.size(); const Name::Component& verb = command.get(COMMAND_PREFIX.size()); UnsignedVerbDispatchTable::const_iterator unsignedVerbProcessor = m_unsignedVerbDispatch.find(verb); if (unsignedVerbProcessor != m_unsignedVerbDispatch.end()) { NFD_LOG_DEBUG("command result: processing verb: " << verb); (unsignedVerbProcessor->second)(this, request); } else if (COMMAND_UNSIGNED_NCOMPS <= commandNComps && commandNComps < COMMAND_SIGNED_NCOMPS) { NFD_LOG_DEBUG("command result: unsigned verb: " << command); sendResponse(command, 401, "Signature required"); } else if (commandNComps < COMMAND_SIGNED_NCOMPS || !COMMAND_PREFIX.isPrefixOf(command)) { NFD_LOG_DEBUG("command result: malformed"); sendResponse(command, 400, "Malformed command"); } else { validate(request, bind(&FibManager::onValidatedFibRequest, this, _1), bind(&ManagerBase::onCommandValidationFailed, this, _1, _2)); } }
void StrategyChoiceManager::onStrategyChoiceRequest(const Interest& request) { const Name& command = request.getName(); const size_t commandNComps = command.size(); if (command == LIST_DATASET_PREFIX) { listStrategies(request); return; } if (COMMAND_UNSIGNED_NCOMPS <= commandNComps && commandNComps < COMMAND_SIGNED_NCOMPS) { NFD_LOG_DEBUG("command result: unsigned verb: " << command); sendResponse(command, 401, "Signature required"); return; } else if (commandNComps < COMMAND_SIGNED_NCOMPS || !COMMAND_PREFIX.isPrefixOf(command)) { NFD_LOG_DEBUG("command result: malformed"); sendResponse(command, 400, "Malformed command"); return; } validate(request, bind(&StrategyChoiceManager::onValidatedStrategyChoiceRequest, this, _1), bind(&ManagerBase::onCommandValidationFailed, this, _1, _2)); }
bool Validator::verifySignature(const Interest& interest, const v1::PublicKey& key) { const Name& name = interest.getName(); if (name.size() < signed_interest::MIN_LENGTH_SIG_ONLY) return false; Signature sig; try { sig.setInfo(name[signed_interest::POS_SIG_INFO].blockFromValue()); sig.setValue(name[signed_interest::POS_SIG_VALUE].blockFromValue()); } catch (const tlv::Error&) { return false; } if (!sig.hasKeyLocator()) return false; const Block& nameWire = name.wireEncode(); return verifySignature(nameWire.value(), nameWire.value_size() - name[signed_interest::POS_SIG_VALUE].size(), sig, key); }
void onInterest(const Name& name, const Interest& interest) { std::cout << "<< I: " << interest << std::endl; // Create new name, based on Interest's name Name dataName(interest.getName()); dataName .append("testApp") // add "testApp" component to Interest name .appendVersion(); // add "version" component (current UNIX timestamp in milliseconds) static const std::string content = "HELLO KITTY"; // Create Data packet Data data; data.setName(dataName); data.setFreshnessPeriod(time::seconds(10)); data.setContent(reinterpret_cast<const uint8_t*>(content.c_str()), content.size()); // Sign Data packet with default identity m_keyChain.sign(data); // m_keyChain.sign(data, <identityName>); // m_keyChain.sign(data, <certificate>); // Return Data packet to the requester std::cout << ">> D: " << data << std::endl; m_face.put(data); }
std::pair<bool, Name> CommandAuthenticator::extractKeyName(const Interest& interest) { const Name& name = interest.getName(); if (name.size() < ndn::signed_interest::MIN_LENGTH) { return {false, Name()}; } ndn::SignatureInfo sig; try { sig.wireDecode(name[ndn::signed_interest::POS_SIG_INFO].blockFromValue()); } catch (const tlv::Error&) { return {false, Name()}; } if (!sig.hasKeyLocator()) { return {false, Name()}; } const ndn::KeyLocator& keyLocator = sig.getKeyLocator(); if (keyLocator.getType() != ndn::KeyLocator::KeyLocator_Name) { return {false, Name()}; } try { return {true, ndn::IdentityCertificate::certificateNameToPublicKeyName(keyLocator.getName())}; } catch (const ndn::IdentityCertificate::Error&) { return {false, Name()}; } }
void Cs::find(const Interest& interest, const HitCallback& hitCallback, const MissCallback& missCallback) const { BOOST_ASSERT(static_cast<bool>(hitCallback)); BOOST_ASSERT(static_cast<bool>(missCallback)); const Name& prefix = interest.getName(); bool isRightmost = interest.getChildSelector() == 1; NFD_LOG_DEBUG("find " << prefix << (isRightmost ? " R" : " L")); iterator first = m_table.lower_bound(prefix); iterator last = m_table.end(); if (prefix.size() > 0) { last = m_table.lower_bound(prefix.getSuccessor()); } iterator match = last; if (isRightmost) { match = this->findRightmost(interest, first, last); } else { match = this->findLeftmost(interest, first, last); } if (match == last) { NFD_LOG_DEBUG(" no-match"); missCallback(interest); return; } NFD_LOG_DEBUG(" matching " << match->getName()); m_policy->beforeUse(match); hitCallback(interest, match->getData()); }