def _expressCustomInterest(self, interestName): #TODO: make this a form, add timeout field try: handled = False (returnCode, returnStr) = self.ui.prompt('Send interest', interestName, preExtra=[ '--extra-button', '--extra-label', 'Signed', '--ok-label', 'Unsigned' ]) if returnCode == Dialog.DIALOG_ESC or returnCode == Dialog.DIALOG_CANCEL: self.loop.call_soon(self.expressInterest) else: interestName = Name(returnStr) doSigned = (returnCode == Dialog.DIALOG_EXTRA) interest = Interest(interestName) interest.setInterestLifetimeMilliseconds(5000) interest.setChildSelector(1) interest.setMustBeFresh(True) if (doSigned): self.face.makeCommandInterest(interest) self.ui.alert( 'Waiting for response to {}'.format(interestName.toUri()), False) self.face.expressInterest(interest, self.onDataReceived, self.onInterestTimeout) except: self.loop.call_soon(self.expressInterest)
def reissueInterest(self): BACKOFF_THRESHOLD = 10 if self.backoffCounter > BACKOFF_THRESHOLD: self.TIMEOUT += 50 self.backoffCounter = 0 self.logger.debug('Backing off interval to ' + str(self.TIMEOUT)) if self.backoffCounter < -BACKOFF_THRESHOLD: self.TIMEOUT -= 50 self.backoffCounter = 0 self.logger.debug('Reducing backoff interval to ' + str(self.TIMEOUT)) if self.nextIssue is not None: now = time.clock() if self.nextIssue > now: pass # time.sleep(self.nextIssue-now) interest = Interest(Name(self.prefix)) interest.setInterestLifetimeMilliseconds(self.interestLifetime) interest.setMustBeFresh(False) if self.lastVersion is not None: e = Exclude() e.appendAny() e.appendComponent(self.lastVersion) interest.setExclude(e) interest.setChildSelector(1) #rightmost == freshest self.face.expressInterest(interest, self.onData, self.onTimeout) self.nextIssue = time.clock()+self.TIMEOUT/2000
def onDataNotFound(self, prefix, interest, face, interestFilterId, filter): print "Data not found for interest: " + interest.getName().toUri() if interest.getName().get( -3).toEscapedString() == "bout" or interest.getName().get( -3).toEscapedString() == "genericfunctions": if interest.getName().toUri() in self.remainingTasks: # We are already trying to process this task, so we don't add it to the list of tasks pass else: self.remainingTasks[interest.getName().toUri()] = "in-progress" else: print "Got unexpected interest: " + interest.getName().toUri() # .../SAMPLE/<timestamp> timestamp = interest.getName().get(-1) catalogInterest = Interest(self.catalogPrefix) # Traverse catalogs in range from leftmost child catalogInterest.setChildSelector(0) catalogInterest.setMustBeFresh(True) catalogInterest.setInterestLifetimeMilliseconds(4000) exclude = Exclude() exclude.appendAny() exclude.appendComponent(timestamp) catalogInterest.setExclude(catalogInterest) self.face.expressInterest(catalogInterest, self.onCatalogData, self.onCatalogTimeout) print "Expressed catalog interest " + catalogInterest.getName().toUri() return
def main(): interest = Interest() interest.wireDecode(TlvInterest) dump("Interest:") dumpInterest(interest) encoding = interest.wireEncode() dump("") dump("Re-encoded interest", encoding.toHex()) reDecodedInterest = Interest() reDecodedInterest.wireDecode(encoding) dump("Re-decoded Interest:") dumpInterest(reDecodedInterest) freshInterest = Interest(Name("/ndn/abc")) freshInterest.setMustBeFresh(False) dump(freshInterest.toUri()) freshInterest.setMinSuffixComponents(4) freshInterest.setMaxSuffixComponents(6) freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST) freshInterest.getKeyLocator().setKeyData(bytearray( [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F])) freshInterest.getExclude().appendComponent(Name("abc")[0]).appendAny() freshInterest.setInterestLifetimeMilliseconds(30000) freshInterest.setChildSelector(1) freshInterest.setMustBeFresh(True); freshInterest.setScope(2) reDecodedFreshInterest = Interest() reDecodedFreshInterest.wireDecode(freshInterest.wireEncode()) dump("") dump("Re-decoded fresh Interest:") dumpInterest(reDecodedFreshInterest)
def main(): # The default Face will connect using a Unix socket, or to "localhost". face = Face() keyChain = KeyChain() face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) dataPrefix = "/home/test1/data" repoDataPrefix = "/home/test1/data" # Set up repo-ng, register prefix for repo-ng's fetch prefix # Per configuration file in /usr/local/etc/ndn/repo-ng.conf # memCache is not used for now; repo is hoping that the piece of data in question is still being held at nfd #memCache = MemoryContentCache(face, 100000) #memCache.registerPrefix(Name(repoDataPrefix), onRegisterFailed, onDataNotFound) counter = Counter(face, repoDataPrefix) interest = Interest(Name(dataPrefix)) interest.setChildSelector(1) interest.setInterestLifetimeMilliseconds(defaultInterestLifetime) face.expressInterest(interest, counter.onData, counter.onTimeout) while True: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(1) face.shutdown()
def startTrustSchemaUpdate(self, appPrefix, onUpdateSuccess = None, onUpdateFailed = None): """ Starts trust schema update for under an application prefix: initial interest asks for the rightMostChild, and later interests are sent with previous version excluded. Each verified trust schema will trigger onUpdateSuccess and update the ConfigPolicyManager for the keyChain in this instance, and unverified ones will trigger onUpdateFailed. The keyChain and trust anchor should be set up using setupDefaultIdentityAndRoot before calling this method. :param appPrefix: the prefix to ask trust schema for. (interest name: /<prefix>/_schema) :type appPrefix: Name :param onUpdateSuccess: (optional) onUpdateSuccess(trustSchemaStr, isInitial) is called when update succeeds :type onUpdateSuccess: function object :param onUpdateFailed: (optional) onUpdateFailed(msg) is called when update fails :type onUpdateFailed: function object """ namespace = appPrefix.toUri() if namespace in self._trustSchemas: if self._trustSchemas[namespace]["following"] == True: print "Already following trust schema under this namespace!" return self._trustSchemas[namespace]["following"] = True else: self._trustSchemas[namespace] = {"following": True, "version": 0, "is-initial": True} initialInterest = Interest(Name(namespace).append("_schema")) initialInterest.setChildSelector(1) self._face.expressInterest(initialInterest, lambda interest, data: self.onTrustSchemaData(interest, data, onUpdateSuccess, onUpdateFailed), lambda interest: self.onTrustSchemaTimeout(interest, onUpdateSuccess, onUpdateFailed)) return
def startPublishingAggregation(self, params, childrenList, dataType, aggregationType): if __debug__: print('Start publishing for ' + dataType + '-' + aggregationType) # aggregation calculating and publishing mechanism publishingPrefix = Name(self._identityName).append(DATA_COMPONENT).append(dataType).append(AGGREGATION_COMPONENT).append(aggregationType) self._dataQueue[dataType + aggregationType] = DataQueue(params, childrenList, publishingPrefix) if len(childrenList.keys()) == 0: # TODO: make start_time optional for leaf nodes self._loop.call_later(int(params['producer_interval']), self.calculateAggregation, dataType, aggregationType, childrenList, int(params['start_time']), int(params['producer_interval']), publishingPrefix, True) else: # express interest for children who produce the same data and aggregation type for childName in childrenList.keys(): name = Name(self._identityName).append(childName).append(DATA_COMPONENT).append(dataType).append(AGGREGATION_COMPONENT).append(aggregationType) interest = Interest(name) # if start_time is specified, we ask for data starting at start_time; # if not, we ask for the right most child and go from there if ('start_time' in childrenList[childName]): endTime = int(childrenList[childName]['start_time']) + int(childrenList[childName]['producer_interval']) interest.getName().append(str(childrenList[childName]['start_time'])).append(str(endTime)) else: # TODO: For now we are playing with historical data, for each run we don't want to miss any data, thus we start with leftMost interest.setChildSelector(0) interest.setMustBeFresh(True) interest.setInterestLifetimeMilliseconds(DEFAULT_INTEREST_LIFETIME) if __debug__: print(' Issue interest: ' + interest.getName().toUri()) self._face.expressInterest(interest, self.onData, self.onTimeout) return
def onCatalogData(self, interest, data): # Find the next catalog print "Received catalog data " + data.getName().toUri() catalogTimestamp = data.getName().get(-2) exclude = Exclude() exclude.appendAny() exclude.appendComponent(catalogTimestamp) nextCatalogInterest = Interest(interest.getName()) nextCatalogInterest.setExclude(exclude) nextCatalogInterest.setChildSelector(0) nextCatalogInterest.setMustBeFresh(True) nextCatalogInterest.setInterestLifetimeMilliseconds(2000) self.face.expressInterest(nextCatalogInterest, self.onCatalogData, self.onCatalogTimeout) print "Expressed catalog interest " + nextCatalogInterest.getName( ).toUri() # We ignore the version in the catalog if self.encrypted: self.consumer.consume(contentName, self.onCatalogConsumeComplete, self.onConsumeFailed) else: self.onCatalogConsumeComplete(data, data.getContent())
def main(): interest = Interest() interest.wireDecode(TlvInterest) dump("Interest:") dumpInterest(interest) # Set the name again to clear the cached encoding so we encode again. interest.setName(interest.getName()) encoding = interest.wireEncode() dump("") dump("Re-encoded interest", encoding.toHex()) reDecodedInterest = Interest() reDecodedInterest.wireDecode(encoding) dump("Re-decoded Interest:") dumpInterest(reDecodedInterest) freshInterest = Interest(Name("/ndn/abc")) freshInterest.setMustBeFresh(False) dump(freshInterest.toUri()) freshInterest.setMinSuffixComponents(4) freshInterest.setMaxSuffixComponents(6) freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST) freshInterest.getKeyLocator().setKeyData(bytearray( [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F])) freshInterest.getExclude().appendComponent(Name("abc")[0]).appendAny() freshInterest.setInterestLifetimeMilliseconds(30000) freshInterest.setChildSelector(1) freshInterest.setMustBeFresh(True); freshInterest.setScope(2) identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage), SelfVerifyPolicyManager(identityStorage)) # Initialize the storage. keyName = Name("/testname/DSK-123") certificateName = keyName.getSubName(0, keyName.size() - 1).append( "KEY").append(keyName[-1]).append("ID-CERT").append("0") identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER)) privateKeyStorage.setKeyPairForKeyName( keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER) # Make a Face just so that we can sign the interest. face = Face("localhost") face.setCommandSigningInfo(keyChain, certificateName) face.makeCommandInterest(freshInterest) reDecodedFreshInterest = Interest() reDecodedFreshInterest.wireDecode(freshInterest.wireEncode()) dump("") dump("Re-decoded fresh Interest:") dumpInterest(reDecodedFreshInterest) keyChain.verifyInterest( reDecodedFreshInterest, makeOnVerified("Freshly-signed Interest"), makeOnVerifyFailed("Freshly-signed Interest"))
def test_set_removes_nonce(self): # ensure that setting a value on an interest clears the nonce self.assertFalse(self.referenceInterest.getNonce().isNull()) interest = Interest(self.referenceInterest) interest.setChildSelector(0) self.assertTrue( interest.getNonce().isNull(), 'Interest should not have a nonce after changing fields')
def onData(self, interest, data): self._keyChain.verifyData(data, self.onVerified, self.onVerifyFailed) dataName = data.getName() dataQueue = None if __debug__: print("Got data: " + dataName.toUri() + "; " + data.getContent().toRawStr()) for i in range(0, len(dataName)): if dataName.get(i).toEscapedString() == AGGREGATION_COMPONENT: dataType = dataName.get(i - 1).toEscapedString() aggregationType = dataName.get(i + 1).toEscapedString() startTime = int(dataName.get(i + 2).toEscapedString()) endTime = int(dataName.get(i + 3).toEscapedString()) childName = dataName.get(i - 3).toEscapedString() dataAndAggregationType = dataType + aggregationType dataDictKey = self.getDataDictKey(startTime, endTime, childName) dataQueue = self._dataQueue[dataAndAggregationType] dataQueue._dataDict[dataDictKey] = data break # TODO: check what if interval/starttime is misconfigured if dataQueue: self.calculateAggregation(dataType, aggregationType, dataQueue._childrenList, startTime, endTime - startTime, dataQueue._publishingPrefix) # Always ask for the next piece of data when we receive this one; assumes interval does not change; this also assumes there are no more components after endTime #newInterestName = dataName.getPrefix(i + 2).append(str(endTime)).append(str(endTime + (endTime - startTime))) # We don't expect aggregated data name to be continuous within our given time window, so we ask with exclusion instead newInterestName = dataName.getPrefix(i + 2) newInterest = Interest(interest) newInterest.setName(newInterestName) newInterest.setChildSelector(0) exclude = Exclude() exclude.appendAny() exclude.appendComponent(dataName.get(i + 2)) newInterest.setExclude(exclude) self._face.expressInterest(newInterest, self.onData, self.onTimeout) if __debug__: print(" issue interest: " + interest.getName().toUri()) return
def createFreshInterest(): freshInterest = Interest(Name("/ndn/abc")) freshInterest.setMustBeFresh(False) freshInterest.setMinSuffixComponents(4) freshInterest.setMaxSuffixComponents(6) freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST) freshInterest.getKeyLocator().setKeyData(bytearray( [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F])) freshInterest.getExclude().appendComponent(Name("abc")[0]).appendAny() freshInterest.setInterestLifetimeMilliseconds(30000) freshInterest.setChildSelector(1) freshInterest.setMustBeFresh(True); freshInterest.setScope(2) return freshInterest
def startPublishingAggregation(self, params, childrenList, dataType, aggregationType): if __debug__: print('Start publishing for ' + dataType + '-' + aggregationType) # aggregation calculating and publishing mechanism publishingPrefix = Name( self._identityName).append(DATA_COMPONENT).append(dataType).append( AGGREGATION_COMPONENT).append(aggregationType) self._dataQueue[dataType + aggregationType] = DataQueue( params, childrenList, publishingPrefix) if len(childrenList.keys()) == 0: # TODO: make start_time optional for leaf nodes self._loop.call_later(int(params['producer_interval']), self.calculateAggregation, dataType, aggregationType, childrenList, int(params['start_time']), int(params['producer_interval']), publishingPrefix, True) else: # express interest for children who produce the same data and aggregation type for childName in childrenList.keys(): name = Name(self._identityName).append(childName).append( DATA_COMPONENT).append(dataType).append( AGGREGATION_COMPONENT).append(aggregationType) interest = Interest(name) # if start_time is specified, we ask for data starting at start_time; # if not, we ask for the right most child and go from there if ('start_time' in childrenList[childName]): endTime = int(childrenList[childName]['start_time']) + int( childrenList[childName]['producer_interval']) interest.getName().append( str(childrenList[childName]['start_time'])).append( str(endTime)) else: # TODO: For now we are playing with historical data, for each run we don't want to miss any data, thus we start with leftMost interest.setChildSelector(0) interest.setMustBeFresh(True) interest.setInterestLifetimeMilliseconds( DEFAULT_INTEREST_LIFETIME) if __debug__: print(' Issue interest: ' + interest.getName().toUri()) self._face.expressInterest(interest, self.onData, self.onTimeout) return
def onData(self, interest, data): self._keyChain.verifyData(data, self.onVerified, self.onVerifyFailed) dataName = data.getName() dataQueue = None if __debug__: print("Got data: " + dataName.toUri() + "; " + data.getContent().toRawStr()) for i in range(0, len(dataName)): if dataName.get(i).toEscapedString() == AGGREGATION_COMPONENT: dataType = dataName.get(i - 1).toEscapedString() aggregationType = dataName.get(i + 1).toEscapedString() startTime = int(dataName.get(i + 2).toEscapedString()) endTime = int(dataName.get(i + 3).toEscapedString()) childName = dataName.get(i - 3).toEscapedString() dataAndAggregationType = dataType + aggregationType dataDictKey = self.getDataDictKey(startTime, endTime, childName) dataQueue = self._dataQueue[dataAndAggregationType] dataQueue._dataDict[dataDictKey] = data break # TODO: check what if interval/starttime is misconfigured if dataQueue: self.calculateAggregation(dataType, aggregationType, dataQueue._childrenList, startTime, endTime - startTime, dataQueue._publishingPrefix) # Always ask for the next piece of data when we receive this one; assumes interval does not change; this also assumes there are no more components after endTime #newInterestName = dataName.getPrefix(i + 2).append(str(endTime)).append(str(endTime + (endTime - startTime))) # We don't expect aggregated data name to be continuous within our given time window, so we ask with exclusion instead newInterestName = dataName.getPrefix(i + 2) newInterest = Interest(interest) newInterest.setName(newInterestName) newInterest.setChildSelector(0) exclude = Exclude() exclude.appendAny() exclude.appendComponent(dataName.get(i + 2)) newInterest.setExclude(exclude) self._face.expressInterest(newInterest, self.onData, self.onTimeout) if __debug__: print(" issue interest: " + interest.getName().toUri()) return
def expressInterest(self): try: interestName = input('Interest name: ') if len(interestName): toSign = input('Signed? (y/N): ').upper().startswith('Y') interest = Interest(Name(interestName)) interest.setInterestLifetimeMilliseconds(5000) interest.setChildSelector(1) if (toSign): self.face.makeCommandInterest(interest) self.face.expressInterest(interest, self.onDataReceived, self.onInterestTimeout) else: print("Aborted") except KeyboardInterrupt: print("Aborted") finally: self.loop.call_soon(self.displayMenu)
def onSchemaVerified(self, data, onUpdateSuccess, onUpdateFailed): print "trust schema verified: " + data.getName().toUri() version = data.getName().get(-1) namespace = data.getName().getPrefix(-2).toUri() if not (namespace in self._trustSchemas): print "unexpected: received trust schema for application namespace that's not being followed; malformed data name?" return if version.toVersion() <= self._trustSchemas[namespace]["version"]: msg = "Got out-of-date trust schema" print msg if onUpdateFailed: onUpdateFailed(msg) return self._trustSchemas[namespace]["version"] = version.toVersion() if "pending-schema" in self._trustSchemas[namespace] and self._trustSchemas[namespace]["pending-schema"].getName().toUri() == data.getName().toUri(): # we verified a pending trust schema, don't need to keep that any more del self._trustSchemas[namespace]["pending-schema"] self._trustSchemas[namespace]["trust-schema"] = data.getContent().toRawStr() print self._trustSchemas[namespace]["trust-schema"] # TODO: what about trust schema for discovery, is discovery its own application? newInterest = Interest(Name(data.getName()).getPrefix(-1)) newInterest.setChildSelector(1) exclude = Exclude() exclude.appendAny() exclude.appendComponent(version) newInterest.setExclude(exclude) self._face.expressInterest(newInterest, lambda interest, data: self.onTrustSchemaData(interest, data, onUpdateSuccess, onUpdateFailed), lambda interest: self.onTrustSchemaTimeout(interest, onUpdateSuccess, onUpdateFailed)) # Note: this changes the verification rules for root cert, future trust schemas as well; ideally from the outside this doesn't have an impact, but do we want to avoid this? # Per reset function in ConfigPolicyManager; For now we don't call reset as we still want root cert in our certCache, instead of asking for it again (when we want to verify) each time we update the trust schema self._policyManager.config = BoostInfoParser() self._policyManager.config.read(self._trustSchemas[namespace]["trust-schema"], "updated-schema") if onUpdateSuccess: onUpdateSuccess(data.getContent().toRawStr(), self._trustSchemas[namespace]["is-initial"]) self._trustSchemas[namespace]["is-initial"] = False return
def expressInterest(self): try: interestName = input('Interest name: ') if len(interestName): toSign = input('Signed? (y/N): ').upper().startswith('Y') interest = Interest(Name(interestName)) print(interest) interest.setInterestLifetimeMilliseconds(10000) interest.setChildSelector(1) if (toSign): self.face.makeCommandInterest(interest) self.face.expressInterest(interest, self.onDataReceived, self.onInterestTimeout) else: print("Aborted") except KeyboardInterrupt: print("Aborted") finally: self.loop.call_soon(self.displayMenu)
def onSchemaVerificationFailed(self, data, reason, onUpdateSuccess, onUpdateFailed): print "trust schema verification failed: " + reason namespace = data.getName().getPrefix(-2).toUri() if not (namespace in self._trustSchemas): print "unexpected: received trust schema for application namespace that's not being followed; malformed data name?" return newInterest = Interest(Name(data.getName()).getPrefix(-1)) newInterest.setChildSelector(1) exclude = Exclude() exclude.appendAny() exclude.appendComponent(Name.Component.fromVersion(self._trustSchemas[namespace]["version"])) newInterest.setExclude(exclude) # Don't immediately ask for potentially the same content again if verification fails self._face.callLater(4000, lambda : self._face.expressInterest(newInterest, lambda interest, data: self.onTrustSchemaData(interest, data, onUpdateSuccess, onUpdateFailed), lambda interest: self.onTrustSchemaTimeout(interest, onUpdateSuccess, onUpdateFailed))) return
def expressInterestPirAndRepeat(self): self.log.debug("callbackCountUniqueData: " + str(self._callbackCountUniqueData) + ", callbackCountTimeout: " + str(self._callbackCountTimeout)) # Express interest for each pir we have discovered for pir in self.getPirs(): interest = Interest(Name(pir.id)) interest.setExclude(pir.status.getExclude()) interest.setInterestLifetimeMilliseconds(1000.0) interest.setChildSelector(1) self.face.expressInterest(interest, self.onDataPir, self.onTimeoutPir) self._countExpressedInterests += 1 debugStr = "Sent interest: " + interest.getName().toUri() debugStr += "\tExclude: " + interest.getExclude().toUri() debugStr += "\tLifetime: " + str(interest.getInterestLifetimeMilliseconds()) self.log.debug(debugStr) # Reschedule again in 0.5 sec self.loop.call_later(1.0, self.expressInterestPirAndRepeat)
def createFreshInterest(): freshInterest = Interest(Name("/ndn/abc")) freshInterest.setMustBeFresh(False) freshInterest.setMinSuffixComponents(4) freshInterest.setMaxSuffixComponents(6) freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST) freshInterest.getKeyLocator().setKeyData( bytearray([ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F ])) freshInterest.getExclude().appendComponent(Name("abc")[0]).appendAny() freshInterest.setInterestLifetimeMilliseconds(30000) freshInterest.setChildSelector(1) freshInterest.setMustBeFresh(True) freshInterest.setScope(2) return freshInterest
def handleCommandInterests(self, prefix, interest, transport, prefixId): # TODO: verification interestName = interest.getName() if len(interestName) <= len(prefix)+4: self.log.info("Bad command interest") commandName = str(interestName[len(prefix)].getValue()) responseMessage = RepoCommandResponseMessage() if commandName == 'insert': commandParams = interestName[len(prefix)+1].getValue() commandMessage = RepoCommandParameterMessage() ProtobufTlv.decode(commandMessage, commandParams) dataName = Name() fullSchemaName = Name() for component in commandMessage.command.name.components: fullSchemaName.append(component) if component == '_': continue dataName.append(component) self.log.info("Insert request for {}".format(dataName)) responseMessage.response.status_code = 100 processId = self.currentProcessId self.currentProcessId += 1 responseMessage.response.process_id = processId else: responseMessage.response.status_code = 403 responseData = Data(interestName) responseData.setContent(ProtobufTlv.encode(responseMessage)) transport.send(responseData.wireEncode().buf()) # now send the interest out to the publisher # TODO: pendingProcesses becomes list of all processes as objects i = Interest(dataName) i.setChildSelector(1) i.setInterestLifetimeMilliseconds(4000) try: self.pendingProcesses[processId] = (dataName, 100) except NameError: pass # wasn't valid insert request else: self._insertFace.expressInterest(i, self._onInsertionDataReceived, self._onInsertionDataTimeout)
def _onContentSet(self, namespace, contentNamespace, callbackId): if not (len(contentNamespace.name) >= len(self._namespace.name) + 1 and contentNamespace.name[len(self._namespace.name)].isSegment()): # Not a segment, ignore. return # TODO: Use the Namspace mechanism to validate the Data packet. metaInfo = contentNamespace.data.metaInfo if (metaInfo.getFinalBlockId().getValue().size() > 0 and metaInfo.getFinalBlockId().isSegment()): self._finalSegmentNumber = metaInfo.getFinalBlockId().toSegment() # Report as many segments as possible where the node already has content. while True: nextSegmentNumber = self._maxRetrievedSegmentNumber + 1 nextSegment = self.debugGetRightmostLeaf( self._namespace[Name.Component.fromSegment(nextSegmentNumber)]) if nextSegment.content.isNull(): break self._maxRetrievedSegmentNumber = nextSegmentNumber self._fireOnSegment(nextSegment) if (self._finalSegmentNumber != None and nextSegmentNumber == self._finalSegmentNumber): # Finished. self._fireOnSegment(None) return if self._finalSegmentNumber == None and not self._didRequestFinalSegment: self._didRequestFinalSegment = True # Try to determine the final segment now. interestTemplate = Interest() interestTemplate.setInterestLifetimeMilliseconds(4000) interestTemplate.setChildSelector(1) self._namespace.expressInterest(interestTemplate) self._requestNewSegments(self._interestPipelineSize)
def main(): interest = Interest() interest.wireDecode(TlvInterest) dump("Interest:") dumpInterest(interest) encoding = interest.wireEncode() dump("") dump("Re-encoded interest", encoding.toHex()) reDecodedInterest = Interest() reDecodedInterest.wireDecode(encoding) dump("Re-decoded Interest:") dumpInterest(reDecodedInterest) freshInterest = Interest(Name("/ndn/abc")) freshInterest.setMustBeFresh(False) dump(freshInterest.toUri()) freshInterest.setMinSuffixComponents(4) freshInterest.setMaxSuffixComponents(6) freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST) freshInterest.getKeyLocator().setKeyData( bytearray([ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F ])) freshInterest.getExclude().appendComponent(Name("abc")[0]).appendAny() freshInterest.setInterestLifetimeMilliseconds(30000) freshInterest.setChildSelector(1) freshInterest.setMustBeFresh(True) freshInterest.setScope(2) reDecodedFreshInterest = Interest() reDecodedFreshInterest.wireDecode(freshInterest.wireEncode()) dump("") dump("Re-decoded fresh Interest:") dumpInterest(reDecodedFreshInterest)
def _expressCustomInterest(self, interestName): # TODO: make this a form, add timeout field try: handled = False (returnCode, returnStr) = self.ui.prompt( "Send interest", interestName, preExtra=["--extra-button", "--extra-label", "Signed", "--ok-label", "Unsigned"], ) if returnCode == Dialog.DIALOG_ESC or returnCode == Dialog.DIALOG_CANCEL: self.loop.call_soon(self.expressInterest) else: interestName = Name(returnStr) doSigned = returnCode == Dialog.DIALOG_EXTRA interest = Interest(interestName) interest.setInterestLifetimeMilliseconds(5000) interest.setChildSelector(1) interest.setMustBeFresh(True) if doSigned: self.face.makeCommandInterest(interest) self.ui.alert("Waiting for response to {}".format(interestName.toUri()), False) self.face.expressInterest(interest, self.onDataReceived, self.onInterestTimeout) except: self.loop.call_soon(self.expressInterest)
def test_set_removes_nonce(self): # ensure that setting a value on an interest clears the nonce self.assertFalse(self.referenceInterest.getNonce().isNull()) interest = Interest(self.referenceInterest) interest.setChildSelector(0) self.assertTrue(interest.getNonce().isNull(), 'Interest should not have a nonce after changing fields')
def _onContentSet(self, namespace, contentNamespace, callbackId): if not (len(contentNamespace.name) >= len(self._namespace.name) + 1 and contentNamespace.name[len(self._namespace.name)].isSegment()): # Not a segment, ignore. # Debug: If this is the first call, we still need to request segments. return # TODO: Use the Namspace mechanism to validate the Data packet. metaInfo = contentNamespace.data.metaInfo if (metaInfo.getFinalBlockId().getValue().size() > 0 and metaInfo.getFinalBlockId().isSegment()): self._finalSegmentNumber = metaInfo.getFinalBlockId().toSegment() # Retrieve as many segments as possible from the store. while True: nextSegmentNumber = self._maxRetrievedSegmentNumber + 1 nextSegment = self.debugGetRightmostLeaf( self._namespace[Name.Component.fromSegment(nextSegmentNumber)]) if nextSegment.content == None: break self._maxRetrievedSegmentNumber = nextSegmentNumber self._fireOnSegment(nextSegment) if (self._finalSegmentNumber != None and nextSegmentNumber == self._finalSegmentNumber): # Finished. self._fireOnSegment(None) return if self._finalSegmentNumber == None and not self._didRequestFinalSegment: self._didRequestFinalSegment = True # Try to determine the final segment now. interestTemplate = Interest() interestTemplate.setInterestLifetimeMilliseconds(4000) interestTemplate.setChildSelector(1) self._namespace.expressInterest(interestTemplate) # Request new segments. childComponents = self._namespace.getChildComponents() # First, count how many are already requested and not received. nRequestedSegments = 0 for component in childComponents: if not component.isSegment(): # The namespace contains a child other than a segment. Ignore. continue child = self._namespace[component] # Debug: Check the leaf for content, but use the immediate child # for _debugSegmentStreamDidExpressInterest. if (self.debugGetRightmostLeaf(child).content == None and hasattr(child, '_debugSegmentStreamDidExpressInterest') and child._debugSegmentStreamDidExpressInterest): nRequestedSegments += 1 if nRequestedSegments >= self._interestPipelineSize: # Already maxed out on requests. break # Now find unrequested segment numbers and request. segmentNumber = self._maxRetrievedSegmentNumber while nRequestedSegments < self._interestPipelineSize: segmentNumber += 1 if (self._finalSegmentNumber != None and segmentNumber > self._finalSegmentNumber): break segment = self._namespace[Name.Component.fromSegment(segmentNumber)] if (self.debugGetRightmostLeaf(segment).content != None or (hasattr(segment, '_debugSegmentStreamDidExpressInterest') and segment._debugSegmentStreamDidExpressInterest)): # Already got the data packet or already requested. continue nRequestedSegments += 1 segment._debugSegmentStreamDidExpressInterest = True segment.expressInterest()