def main(): interest = Interest() interest.wireDecode(TlvInterest) # Use a hard-wired secret for testing. In a real application the signer # ensures that the verifier knows the shared key and its keyName. key = Blob(bytearray([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 ])) if KeyChain.verifyInterestWithHmacWithSha256(interest, key): dump("Hard-coded interest signature verification: VERIFIED") else: dump("Hard-coded interest signature verification: FAILED") freshInterest = Interest(Name("/ndn/abc")) freshInterest.setMustBeFresh(False) keyName = Name("key1") dump("Signing fresh interest", freshInterest.getName().toUri()) KeyChain.signWithHmacWithSha256(freshInterest, key, keyName) if KeyChain.verifyInterestWithHmacWithSha256(freshInterest, key): dump("Freshly-signed interest signature verification: VERIFIED") else: dump("Freshly-signed interest signature verification: FAILED")
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(): # silence the warning from interest wire encode Interest.setDefaultCanBePrefix(True) # set up a face that connects to the remote forwarder udp_connection_info = UdpTransport.ConnectionInfo("10.10.1.1", 6363) udp_transport = UdpTransport() face = Face(udp_transport, udp_connection_info) counter = Counter() # try to fetch from provided name name_text = input("Enter a name to request content from: ") name = Name(name_text) dump("Express name", name.toUri()) interest = Interest(name) interest.setMustBeFresh(False) face.expressInterest(interest, counter.onData, counter.onTimeout, counter.onNetworkNack) while counter._callbackCount < 1: face.processEvents() # don't use 100% of the CPU time.sleep(0.01) face.shutdown()
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 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 _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 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(): # Silence the warning from Interest wire encode. Interest.setDefaultCanBePrefix(True) interest = Interest() interest.wireDecode(TlvInterest) # Use a hard-wired secret for testing. In a real application the signer # ensures that the verifier knows the shared key and its keyName. key = Blob(bytearray([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 ])) if KeyChain.verifyInterestWithHmacWithSha256(interest, key): dump("Hard-coded interest signature verification: VERIFIED") else: dump("Hard-coded interest signature verification: FAILED") freshInterest = Interest(Name("/ndn/abc")) freshInterest.setMustBeFresh(False) keyName = Name("key1") dump("Signing fresh interest", freshInterest.getName().toUri()) KeyChain.signWithHmacWithSha256(freshInterest, key, keyName) if KeyChain.verifyInterestWithHmacWithSha256(freshInterest, key): dump("Freshly-signed interest signature verification: VERIFIED") else: dump("Freshly-signed interest signature verification: FAILED")
def create_ctrlinfo_req_interest(self, node_id, ctrlinfo_SN=100001): hello_name = self.add_of_head(self.prefix_controller, 36) + \ str("--{0}--{1}".format(node_id, ctrlinfo_SN)) interest = Interest(hello_name) interest.setMustBeFresh(True) interest.setInterestLifetimeMilliseconds(999999999999) return interest
def onInterest_StartDE(self, prefix, interest, face, interestFilterId, filter): interestName = interest.getName() print "Interest Name: %s" % interestName interest_name_components = interestName.toUri().split("/") if "start_de" in interest_name_components: #print 'Query database' #print 'Call decision engine algorithm' #parent_dir = os.path.split(self.script_dir)[0] #monitor_path = os.path.join(self.script_dir, parent_dir, 'Monitoring', 'Monitoring_DB') #print monitor_path #myDE = de(monitor_path) #json_lst_dict = myDE.get_lst_of_dictionaries() #json_server_Spec = self.json_server_Spec_default #node_name = myDE.selectHost_to_deploy_firstInstance(json_lst_dict, json_server_Spec) node_name = interest_name_components[ interest_name_components.index("start_de") + 2] print 'Selected Host Name %s' % node_name service_name = interest_name_components[ interest_name_components.index("start_de") + 1] print 'service name %s' % service_name print 'Start service deployment' deployService = self.prefix_deployService + node_name + '/' + service_name config_prefix_deployService = Name(deployService) interest = Interest(config_prefix_deployService) interest.setInterestLifetimeMilliseconds(self.interestLifetime) interest.setMustBeFresh(True) self.face.expressInterest( interest, None, None ) ## set None --> sent out only, don't wait for Data and Timeout print "Sent Push Interest to SEG %s" % config_prefix_deployService else: print "Interest name mismatch"
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 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 create_packetout_msg_interest(self, PacketOut_suffix): packetout_name = self.add_of_head(self.prefix_h1, 13) + "-----" + PacketOut_suffix #/ndn/h1-site/he/ofndn/--/n1.0/13/0/0/-------/PacketOut_suffix interest = Interest(packetout_name) interest.setMustBeFresh(True) interest.setInterestLifetimeMilliseconds(1000) return interest
def create_flowremoved_msg_interest(self, removed_prefix): frmsg_name = self.add_of_head(self.prefix_controller, 11) + "/--" + removed_prefix #/ndn/ie/tcd/controller01/ofndn/--/n1.0/11/0/0/--/removed_prefix interest = Interest(frmsg_name) interest.setMustBeFresh(True) interest.setInterestLifetimeMilliseconds(1000) return interest
def create_error_msg_interest(self, error_prefix): packetin_name = self.add_of_head(self.prefix_controller, 1) + "/--" + error_prefix # /ndn/ie/tcd/controller01/ofndn/--/n1.0/10/0/0/--/unknown_prefix interest = Interest(packetin_name) interest.setMustBeFresh(True) interest.setInterestLifetimeMilliseconds(4000) return interest
def create_hello_req_interest(self, node_id, feature_SN=1): hello_name = self.add_of_head(self.prefix_controller,0) + \ str("--{0}--{1}".format(node_id,feature_SN)) + \ str("--/ndn/{0}-site/{0}/ofndn/feature".format(node_id)) interest = Interest(hello_name) interest.setMustBeFresh(True) interest.setInterestLifetimeMilliseconds(4000) return interest
def sendInterest_mod(self): i = Interest() i.setMustBeFresh(True) i.setInterestLifetimeMilliseconds(5000) self.buildName() self.face.expressInterest(self.name, i, self.onData, self.onTimeout) self.status = 1
def sendInterest(self, name): interest = Interest(name) interestName = interest.getName() interest.setInterestLifetimeMilliseconds(4000) interest.setMustBeFresh(True) self.face.expressInterest( interest, None, None ) ## set None --> sent out only, don't wait for Data and Timeout print "Sent Interest for %s" % interestName
def _send(self, name): """Send a singular interest.""" interest = Interest(name) interest.setMustBeFresh(False) self._face.expressInterest(interest, self.onData, self.onTimeout, self.onNetworkNack) self._interests_sent += 1 if self._verbose >= 2: dump("Send interest with name", name)
def _decryptAndPrintRecord(self, recordData, keyName, parentDoc): keyUri = keyName.toUri() def cleanString(dirty): return ''.join(filter(string.printable.__contains__, str(dirty))) def onKeyDataReceived(keyInterest, keyData): self.log.debug('Got key for {}'.format(keyInterest.getName())) cipherText = str(keyData.getContent()) symKeyRaw = self.privateKey.decrypt(cipherText) symKey = symKeyRaw[-64:].decode('hex') msg = recordData[8:] iv = msg[:16] cipherText = msg[16:] cipher = AES.new(key=symKey, IV=iv, mode=AES.MODE_CBC) decData = cleanString(cipher.decrypt(cipherText)) fromJson = json.loads(decData) fromJson.update(parentDoc) self.knownKeys[keyUri] = keyData try: self.pendingKeys.remove(keyUri) except ValueError: pass # already removed self.resultQueue.put_nowait(fromJson) def onKeyTimeout(keyInterest): self.log.error('Could not get decryption key for {}'.format(keyInterest.getName())) self.resultQueue.put_nowait({}) i = Interest(keyName) i.setMustBeFresh(False) i.setInterestLifetimeMilliseconds(2000) if keyUri in self.knownKeys: self.log.debug('Using known key') onKeyDataReceived(i, self.knownKeys[keyUri]) elif keyUri in self.pendingKeys: self.log.debug('Waiting on pending key') timeout = 0 while keyUri not in self.knownKeys: yield From(asyncio.sleep(0.5)) timeout += 1 if timeout > 5: self.log.warn('Timed out on key {}'.format(keyUri)) onKeyTimeout(i) break else: onKeyDataReceived(i, self.knownKeys[keyUri]) else: self.log.debug('Adding {} to pending keys'.format(keyUri)) self.pendingKeys.append(keyUri) self.keyFace.expressInterest(i, onKeyDataReceived, onKeyTimeout)
def main(): if len(sys.argv) < 2: print("usage: python3 client-app.py {good/bad}") quit() #Interest.setDefaultCanBePrefix(True) with open("shared/system-info.json") as f: user_data = json.load(f) face = Face() counter = Counter() name = Name("/ndn-ss/austin") req_name = "/example/test" sym_key = base64.b64decode(user_data['austin']['sym_key']) iv, ct, tag = sym_encrypt(sym_key, req_name) enc_req_name = base64.b64encode(iv).decode('ascii') name.append(enc_req_name) enc_req_name = base64.b64encode(ct).decode('ascii') name.append(enc_req_name) enc_req_name = base64.b64encode(tag).decode('ascii') name.append(enc_req_name) priv_key = user_data['austin']['priv_key'] priv_key = base64.b64decode(priv_key) priv_key = load_priv_key(priv_key) sig =\ base64.b64encode(priv_key.sign(bytes("austin",'utf-8'))).decode('ascii') bad_sig =\ base64.b64encode(priv_key.sign(bytes("abstin",'utf-8'))).decode('ascii') i = Interest() i.setMustBeFresh(True) i.setInterestLifetimeMilliseconds(0) #face.expressInterest(name,counter.onData,counter.onTimeout) if sys.argv[1] == "good": name.append(sig) face.expressInterest(name, i, counter.onData, counter.onTimeout) elif sys.argv[1] == "bad": name.append(bad_sig) face.expressInterest(name, i, counter.onData, counter.onTimeout) else: print("c") while counter.rec == 1: face.processEvents() time.sleep(0.1) face.expressInterest(name, i, counter.onData, counter.onTimeout)
def _sendNextInterest(self, name): interest = Interest(name) uri = name.toUri() interest.setInterestLifetimeMilliseconds(12000) interest.setMustBeFresh(True) if uri not in self.outstanding: self.outstanding[uri] = 1 self.face.expressInterest(interest, self._onData, self._onTimeout) print "Sent Interest for %s" % uri
def onSyncTimeout(self, interest): newInterest = Interest(Name(self._syncPrefix).append(self._currentDigest)) newInterest.setInterestLifetimeMilliseconds(self._syncInterestLifetime) newInterest.setMustBeFresh(True) self._numOutstandingInterest -= 1 print "re-expressing: " + newInterest.getName().toUri() if self._numOutstandingInterest <= 0: self._face.expressInterest(newInterest, self.onSyncData, self.onSyncTimeout) self._numOutstandingInterest += 1 return
def _sendNextInterestWithSegment(self, name): interest = Interest(name) uri = name.toUri() interest.setInterestLifetimeMilliseconds(4000) interest.setMustBeFresh(True) if name.toUri() not in self.outstanding: self.outstanding[name.toUri()] = 1 self.face.expressInterest(interest, self._onData, None) print "Sent Interest for %s" % uri
def start(self): """ Starts the discovery """ interest = Interest(Name(self._syncPrefix).append(self._initialDigest)) interest.setMustBeFresh(True) interest.setInterestLifetimeMilliseconds(self._syncInterestLifetime) self._face.expressInterest(interest, self.onSyncData, self.onSyncTimeout) self._numOutstandingInterest += 1 if __debug__: print("Express interest: " + interest.getName().toUri()) return
def generateKeyAndSendNewInterest(self, probeTokenData): """ """ pib = self.keyChain.getPib() try: identity = pib.getIdentity(self.identityName) self.key = self.keyChain.createKey(identity) except Exception as e: identity = self.keyChain.createIdentityV2(self.identityName) self.key = identity.getDefaultKey() cert = CertificateV2() cert.setName( Name(self.key.getName()).append("cert-request").appendVersion( int(time.time()))) cert.getMetaInfo().setType(ContentType.KEY) cert.getMetaInfo().setFreshnessPeriod(24 * 3600) cert.setContent(self.key.getPublicKey()) signingInfo = SigningInfo(self.key) now = Common.getNowMilliseconds() signingInfo.setValidityPeriod( ValidityPeriod(now, now + 24 * 3600 * 1000.0)) self.keyChain.sign(cert, signingInfo) #cert = self.keyChain.selfSign(self.key) # Does not work because validity period is greater than certserver default interestName = Name(self.caPrefix).append("CA").append("_NEW") newInterest = Interest(interestName) newInterest.setMustBeFresh(True) newInterest.setCanBePrefix(False) ecdhPub = "{}\n".format(self.ecdh.getBase64PubKey()) ecdhCertReq = "{}\n".format( b64encode(cert.wireEncode().toBytes()).decode('utf-8')) probeToken = "{}\n".format( b64encode(probeTokenData.wireEncode().toBytes()).decode('utf-8')) jsonDump = json.dumps( { "ecdh-pub": ecdhPub, "cert-request": ecdhCertReq, "probe-token": probeToken }, indent=4) print(jsonDump) newInterest.setApplicationParameters(jsonDump) newInterest.appendParametersDigestToName() self.keyChain.sign(newInterest, SigningInfo(self.key)) print(newInterest.getName()) self.face.expressInterest(newInterest, self.onNewData, self.onTimeout)
def _sendNextInterest(self, name): self.start_time = time.time() interest = Interest(name) uri = name.toUri() interest.setInterestLifetimeMilliseconds(9000) interest.setMustBeFresh(False) if uri not in self.outstanding: self.outstanding[uri] = 1 self.face.expressInterest(interest, self._onData, self._onTimeout)
def _sendNextInterestWithSegment(self, name): interest = Interest(name) uri = name.toUri() interest.setInterestLifetimeMilliseconds(4000) interest.setMustBeFresh(True) if name.toUri() not in self.outstanding: self.outstanding[name.toUri()] = 1 self.face.expressInterest(interest, self._onData, self._onTimeout) print "Sent Interest for %s" % uri
def _sendNextInterest(self, name): interest = Interest(name) uri = name.toUri() interest.setInterestLifetimeMilliseconds(10000) interest.setMustBeFresh(True) if uri not in self.outstanding: self.outstanding[uri] = 1 self.face.expressInterest(interest, self._onData, self._onTimeout) print("========= Sent [ Interest ] ========= \n {0}\n \n".format(uri))
def _sendInterest_Publish(self, name): interest = Interest(name) uri = name.toUri() interest.setInterestLifetimeMilliseconds(4000) interest.setMustBeFresh(True) if uri not in self.outstanding: self.outstanding[uri] = 1 self.face.expressInterest(interest, None, None) print "Sent Interest for %s" % uri
def _sendNextInterest(self, name): interest = Interest(name) uri = name.toUri() interest.setApplicationParameters(self.prefixesToSend) interest.setInterestLifetimeMilliseconds(4000) interest.setMustBeFresh(True) if uri not in self.outstanding: self.outstanding[uri] = 1 self.face.expressInterest(interest, self._onData, self._onTimeout) print "Sent Chat Prefixes to host " + str(self.host)
def _sendNextInterest(self, name): # Create an Interest using the specificed run&clip number with the frame-annotation namespace and record it in our outstanding Interest. # Then, send the Interest out our Face. interest = Interest(name) uri_i = name.toUri() interest.setInterestLifetimeMilliseconds(4000) interest.setMustBeFresh(True) if uri_i not in self.outstanding: self.outstanding[uri_i] = 1 self.face.expressInterest(interest, self._onData, self._onTimeout) print("Sent Interest for %s" % uri_i)
def sendProbeInterest(self): probeInterest = Interest( Name(self.caPrefix).append("CA").append("_PROBE")) probeInterest.setMustBeFresh(True) probeInterest.setCanBePrefix(False) probeInterest.setApplicationParameters( json.dumps({"email": "*****@*****.**"}, indent=4)) probeInterest.appendParametersDigestToName() print("Expressing interest: {}".format(probeInterest.getName())) self.face.expressInterest(probeInterest, self.onProbeData, self.onTimeout)
def _sendNextInterest(self, name): interest = Interest(name) uri = name.toUri() interest.setInterestLifetimeMilliseconds(4000) interest.setMustBeFresh(True) if uri not in self.outstanding: self.outstanding[uri] = 1 self.face.expressInterest(interest, self._onData, self._onTimeout) print "Sent Interest for %s" % uri global start_time start_time = time.time()
def onCatalogConsumeComplete(self, data, result): print "Consume complete for catalog name: " + data.getName().toUri() catalog = json.loads(result.toRawStr()) for timestamp in catalog: # For encrypted data, timestamp format will have to change rawDataName = Name(self.rawDataPrefix).append( Schedule.toIsoString(timestamp * 1000)) dataInterest = Interest(rawDataName) dataInterest.setInterestLifetimeMilliseconds(2000) dataInterest.setMustBeFresh(True) self.face.expressInterest(dataInterest, self.onRawData, self.onRawDataTimeout) self.remainingData += 1 return
def sendInterest_to_DE(self, name): interest = Interest(name) interestName = interest.getName() interest.setInterestLifetimeMilliseconds(4000) interest.setMustBeFresh(True) #if uri not in self.outstanding: #self.outstanding[uri] = 1 # self.face.expressInterest(interest, self.onData, self._onTimeout) self.face.expressInterest( interest, None, None ) ## set None --> sent out only, don't wait for Data and Timeout print "Sent Push-Interest for %s" % interestName
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 _sendNextInterest(self, name): # Create an Interest using incoming name # and record it in our outstanding Interest. # Then, send the Interest out our Face. interest = Interest(name) uri = name.toUri() interest.setInterestLifetimeMilliseconds(60) interest.setMustBeFresh(True) if uri not in self.outstanding: self.outstanding[uri] = 1 self.face.expressInterest(interest, self._onData, self._onTimeout) #print ("Sent Interest for %s \n===================================" % uri) pass
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 run(self): try: interest = Interest(self.name) uri = self.name.toUri() interest.setInterestLifetimeMilliseconds(4000) interest.setMustBeFresh(True) self.face.expressInterest(interest, self._onData, self._onTimeout) while not self.isDone: self.face.processEvents() time.sleep(0.01) print "Sent Interest for %s" % uri except RuntimeError as e: print "ERROR: %s" % e
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 _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 publishObject(self, name, entityInfo): """ Adds another object and registers prefix for that object's name :param name: the object's name string :type name: str :param entityInfo: the application given entity info to describe this object name with :type entityInfo: EntityInfo """ # If this is the first object we host, we register for sync namespace: meaning a participant not hosting anything # is only "listening" for sync, and will not help in the sync process if len(self._hostedObjects.keys()) == 0: self._memoryContentCache.registerPrefix(self._syncPrefix, self.onRegisterFailed, self.onSyncInterest) if self.addObject(name, False): # Do not add itself to contentCache if its currentDigest is "00". if self._currentDigest != self._initialDigest: self.contentCacheAddSyncData(Name(self._syncPrefix).append(self._currentDigest)) self.updateDigest() interest = Interest(Name(self._syncPrefix).append(self._currentDigest)) interest.setInterestLifetimeMilliseconds(self._syncInterestLifetime) interest.setMustBeFresh(True) self._face.expressInterest(interest, self.onSyncData, self.onSyncTimeout) self._numOutstandingInterest += 1 self._hostedObjects[name] = entityInfo self.contentCacheAddEntityData(name, entityInfo) self.notifyObserver(name, "ADD", "") # TODO: should the user configure this prefix as well? self._memoryContentCache.registerPrefix(Name(name), self.onRegisterFailed, self.onEntityDataNotFound) else: if __debug__: print("Item with this name already added") return
def fetchData(self,name): interest = Interest(name) interest.setInterestLifetimeMilliseconds(self._interestLifetime) interest.setMustBeFresh(self.m_mustBeFresh) self._face.expressInterest(interest,self.onData,self.onTimeout)
def onReceivedSyncData(self, itemName): interest = Interest(Name(itemName)) interest.setInterestLifetimeMilliseconds(4000) interest.setMustBeFresh(False) self._face.expressInterest(interest, self.onEntityData, self.onEntityTimeout) return