def _updateCapabilities(self): """ Send the controller a list of our commands. """ fullCommandName = Name( self._policyManager.getTrustRootIdentity()).append( 'updateCapabilities') capabilitiesMessage = UpdateCapabilitiesCommandMessage() for command in self._commands: commandName = Name(self.prefix).append(Name(command.suffix)) capability = capabilitiesMessage.capabilities.add() for i in range(commandName.size()): capability.commandPrefix.components.append( str(commandName.get(i).getValue())) for kw in command.keywords: capability.keywords.append(kw) capability.needsSignature = command.isSigned encodedCapabilities = ProtobufTlv.encode(capabilitiesMessage) fullCommandName.append(encodedCapabilities) interest = Interest(fullCommandName) interest.setInterestLifetimeMilliseconds(5000) self.face.makeCommandInterest(interest) signature = self._policyManager._extractSignature(interest) self.log.info("Sending capabilities to controller") self.face.expressInterest(interest, self._onCapabilitiesAck, self._onCapabilitiesTimeout) # update twice a minute self.loop.call_later(30, self._updateCapabilities)
def _sendCertificateRequest(self, keyIdentity): """ We compose a command interest with our public key info so the controller can sign us a certificate that can be used with other nodes in the network. """ #TODO: GENERATE A NEW PUBLIC/PRIVATE PAIR INSTEAD OF COPYING makeKey = False try: defaultKey = self._identityStorage.getDefaultKeyNameForIdentity( keyIdentity) newKeyName = defaultKey except SecurityException: defaultIdentity = self._keyChain.getDefaultIdentity() defaultKey = self._identityStorage.getDefaultKeyNameForIdentity( defaultIdentity) newKeyName = self._identityStorage.getNewKeyName(keyIdentity, True) makeKey = True self.log.debug("Found key: " + defaultKey.toUri() + " renaming as: " + newKeyName.toUri()) keyType = self._identityStorage.getKeyType(defaultKey) keyDer = self._identityStorage.getKey(defaultKey) if makeKey: try: privateDer = self._identityManager.getPrivateKey(defaultKey) except SecurityException: # XXX: is recovery impossible? pass else: try: self._identityStorage.addKey(newKeyName, keyType, keyDer) self._identityManager.addPrivateKey(newKeyName, privateDer) except SecurityException: # TODO: key shouldn't exist... pass message = CertificateRequestMessage() message.command.keyType = keyType message.command.keyBits = keyDer.toRawStr() for component in range(newKeyName.size()): message.command.keyName.components.append( newKeyName.get(component).toEscapedString()) paramComponent = ProtobufTlv.encode(message) interestName = Name(self._policyManager.getTrustRootIdentity()).append( "certificateRequest").append(paramComponent) interest = Interest(interestName) interest.setInterestLifetimeMilliseconds( 10000) # takes a tick to verify and sign self._hmacHandler.signInterest(interest, keyName=self.prefix) self.log.info("Sending certificate request to controller") self.log.debug("Certificate request: " + interest.getName().toUri()) self.face.expressInterest(interest, self._onCertificateReceived, self._onCertificateTimeout)
def main(): # Silence the warning from Interest wire encode. Interest.setDefaultCanBePrefix(True) # The default Face connects to the local NFD. face = Face() interest = Interest(Name("/localhost/nfd/faces/list")) interest.setInterestLifetimeMilliseconds(4000) dump("Express interest", interest.getName().toUri()) enabled = [True] def onComplete(content): enabled[0] = False printFaceStatuses(content) def onError(errorCode, message): enabled[0] = False dump(message) SegmentFetcher.fetch(face, interest, None, onComplete, onError) # Loop calling processEvents until a callback sets enabled[0] = False. while enabled[0]: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01)
def _scanForUnconfiguredDevices(self): # unconfigured devices should register '/localhop/configure' # we keep asking for unconfigured devices until we stop getting replies foundDevices = [] self.ui.alert("Scanning for unconfigured devices...", False) def onDeviceTimeout(interest): # assume we're done - everyone is excluded self.unconfiguredDevices = foundDevices self.loop.call_soon(self._showConfigurationList) def onDeviceResponse(interest, data): updatedInterest = Interest(interest) deviceSerial = str(data.getContent()) if len(deviceSerial) > 0: foundDevices.append(deviceSerial) updatedInterest.getExclude().appendComponent(Name.Component(deviceSerial)) # else ignore the malformed response self.face.expressInterest(updatedInterest, onDeviceResponse, onDeviceTimeout) interest = Interest(Name("/localhop/configure")) interest.setInterestLifetimeMilliseconds(2000) self.face.expressInterest(interest, onDeviceResponse, onDeviceTimeout)
def consume(self, prefix, onVerified, onVerifyFailed, onTimeout): """ Consume data continuously under a given prefix, maintaining pipelineSize number of interest in the pipeline :param name: prefix to consume data under :type name: Name :param onData: onData(data) gets called after received data's onVerifyFailed :type onData: function object :param onVerifyFailed: onVerifyFailed(data) gets called if received data cannot be verified :type onVerifyFailed: function object :param onTimeout: onTimeout(interest) gets called if a consumer interest times out :type onTimeout: function object """ num = self._emptySlot for i in range(0, num): name = Name(prefix).append(str(self._currentSeqNumber)) interest = Interest(name) # interest configuration / template? interest.setInterestLifetimeMilliseconds(self._defaultInterestLifetime) self._face.expressInterest(interest, lambda i, d : self.onData(i, d, onVerified, onVerifyFailed, onTimeout), lambda i: self.beforeReplyTimeout(i, onVerified, onVerifyFailed, onTimeout)) self._currentSeqNumber += 1 self._emptySlot -= 1 return
def _onData(self, interest, data): """ Process the incoming Chat data. """ # TODO: Check if this works in Python 3. content = chatbuf_pb2.ChatMessage() content.ParseFromString(data.getContent().toRawStr()) if self.getNowMilliseconds() - content.timestamp * 1000.0 < 120000.0: # Use getattr because "from" is a reserved keyword. name = getattr(content, "from") prefix = data.getName().getPrefix(-2).toUri() sessionNo = int(data.getName().get(-2).toEscapedString()) sequenceNo = int(data.getName().get(-1).toEscapedString()) nameAndSession = name + str(sessionNo) l = 0 # Update roster. while l < len(self._roster): entry = self._roster[l] tempName = entry[0:len(entry) - 10] tempSessionNo = int(entry[len(entry) - 10:]) if (name != tempName and content.type != chatbuf_pb2.ChatMessage.LEAVE): l += 1 else: if name == tempName and sessionNo > tempSessionNo: self._roster[l] = nameAndSession break if l == len(self._roster): self._roster.append(nameAndSession) print(name + ": Join") # Set the alive timeout using the Interest timeout mechanism. # TODO: Are we sure using a "/local/timeout" interest is the best # future call approach? timeout = Interest(Name("/local/timeout")) timeout.setInterestLifetimeMilliseconds(120000) self._face.expressInterest( timeout, self._dummyOnData, self._makeAlive(sequenceNo, name, sessionNo, prefix)) # isRecoverySyncState_ was set by sendInterest. # TODO: If isRecoverySyncState_ changed, this assumes that we won't get # data from an interest sent before it changed. # Use getattr because "from" is a reserved keyword. if (content.type == chatbuf_pb2.ChatMessage.CHAT and not self._isRecoverySyncState and getattr(content, "from") != self._screenName): print(getattr(content, "from") + ": " + content.data) elif content.type == chatbuf_pb2.ChatMessage.LEAVE: # leave message try: n = self._roster.index(nameAndSession) if name != self._screenName: self._roster.pop(n) print(name + ": Leave") except ValueError: pass
def main(): # The default Face connects to the local NFD. face = Face() interest = Interest(Name("/localhost/nfd/rib/list")) interest.setInterestLifetimeMilliseconds(4000) dump("Express interest", interest.getName().toUri()) enabled = [True] def onComplete(content): enabled[0] = False printRibEntries(content) def onError(errorCode, message): enabled[0] = False dump(message) SegmentFetcher.fetch(face, interest, None, onComplete, onError) # Loop calling processEvents until a callback sets enabled[0] = False. while enabled[0]: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01)
def _updateCapabilities(self): """ Send the controller a list of our commands. """ fullCommandName = Name(self._policyManager.getTrustRootIdentity() ).append('updateCapabilities') capabilitiesMessage = UpdateCapabilitiesCommandMessage() for command in self._commands: commandName = Name(self.prefix).append(Name(command.suffix)) capability = capabilitiesMessage.capabilities.add() for i in range(commandName.size()): capability.commandPrefix.components.append( str(commandName.get(i).getValue())) for kw in command.keywords: capability.keywords.append(kw) capability.needsSignature = command.isSigned encodedCapabilities = ProtobufTlv.encode(capabilitiesMessage) fullCommandName.append(encodedCapabilities) interest = Interest(fullCommandName) interest.setInterestLifetimeMilliseconds(5000) self.face.makeCommandInterest(interest) signature = self._policyManager._extractSignature(interest) self.log.info("Sending capabilities to controller") self.face.expressInterest(interest, self._onCapabilitiesAck, self._onCapabilitiesTimeout) # update twice a minute self.loop.call_later(30, self._updateCapabilities)
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 main(): # The default Face will connect using a Unix socket, or to "localhost". face = Face() counter = Counter() #if sys.version_info[0] <= 2: # word = raw_input("Enter a video name: ") #else: # word = input("Enter a video name: ") name = Name("/kebapp/video/video") #name.append(word) dump("Express name ", name.toUri()) interest = Interest(name) #interest.setInterestLifeTimeMilliseconds(30000) interest.setInterestLifetimeMilliseconds(30000) face.expressInterest(interest, counter.onData, counter.onTimeout) #face.expressInterest(name, counter.onData, counter.onTimeout) while counter._callbackCount < 1: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01) face.shutdown()
def onHeartbeatTimeout(self, interest): if self.incrementTimeoutCnt(interest.getName().toUri()): print "Remove: " + interest.getName().toUri() + " because of consecutive timeout cnt exceeded" else: newInterest = Interest(interest.getName()) newInterest.setInterestLifetimeMilliseconds(4000) self._face.expressInterest(newInterest, self.onHeartbeatData, self.onHeartbeatTimeout)
def _scanForUnconfiguredDevices(self): # unconfigured devices should register '/localhop/configure' # we keep asking for unconfigured devices until we stop getting replies foundDevices = [] self.ui.alert('Scanning for unconfigured devices...', False) def onDeviceTimeout(interest): # assume we're done - everyone is excluded self.unconfiguredDevices = foundDevices self.loop.call_soon(self._showConfigurationList) def onDeviceResponse(interest, data): updatedInterest = Interest(interest) deviceSerial = str(data.getContent()) if len(deviceSerial) > 0: foundDevices.append(deviceSerial) updatedInterest.getExclude().appendComponent( Name.Component(deviceSerial)) # else ignore the malformed response self.face.expressInterest(updatedInterest, onDeviceResponse, onDeviceTimeout) interest = Interest(Name('/localhop/configure')) interest.setInterestLifetimeMilliseconds(2000) self.face.expressInterest(interest, onDeviceResponse, onDeviceTimeout)
def helper(identityName, signerName): try: self._defaultIdentity = identityName self._defaultCertificateName = self._identityManager.getDefaultCertificateNameForIdentity(self._defaultIdentity) self._defaultKeyName = self._identityManager.getDefaultKeyNameForIdentity(identityName) except SecurityException: msg = "Identity " + identityName.toUri() + " in configuration does not exist. Please configure the device with this identity first." if onSetupFailed: onSetupFailed(msg) return if not self._defaultCertificateName: msg = "Unable to get default certificate name for identity " + identityName.toUri() + ". Please configure the device with this identity first." if onSetupFailed: onSetupFailed(msg) return if not self._defaultKeyName: msg = "Unable to get default key name for identity " + identityName.toUri() + ". Please configure the device with this identity first." if onSetupFailed: onSetupFailed(msg) return # Note we'll not be able to issue face commands before this point self._face.setCommandSigningInfo(self._keyChain, self._defaultCertificateName) # Serve our own certificate self._certificateContentCache.registerPrefix(Name(self._defaultCertificateName).getPrefix(-1), self.onRegisterFailed) self._certificateContentCache.add(self._keyChain.getCertificate(self._defaultCertificateName)) actualSignerName = self._keyChain.getCertificate(self._defaultCertificateName).getSignature().getKeyLocator().getKeyName() if not signerName: print "Deriving from " + actualSignerName.toUri() + " for controller name" else: if signerName and actualSignerName.toUri() != signerName.toUri(): msg = "Configuration signer names mismatch: expected " + signerName.toUri() + "; got " + actualSignerName.toUri() print msg if onSetupFailed: onSetupFailed(msg) self._controllerName = self.getIdentityNameFromCertName(actualSignerName) print "Controller name: " + self._controllerName.toUri() try: self._controllerCertificate = self._keyChain.getCertificate(self._identityManager.getDefaultCertificateNameForIdentity(self._controllerName)) # TODO: this does not seem a good approach, implementation-wise and security implication self._policyManager._certificateCache.insertCertificate(self._controllerCertificate) if onSetupComplete: onSetupComplete(Name(self._defaultCertificateName), self._keyChain) except SecurityException as e: print "don't have controller certificate " + actualSignerName.toUri() + " yet" controllerCertInterest = Interest(Name(actualSignerName)) controllerCertInterest.setInterestLifetimeMilliseconds(4000) controllerCertRetries = 3 self._face.expressInterest(controllerCertInterest, lambda interest, data: self.onControllerCertData(interest, data, onSetupComplete, onSetupFailed), lambda interest: self.onControllerCertTimeout(interest, onSetupComplete, onSetupFailed, controllerCertRetries)) return
async def _check(self, method: str, repo_name: str, process_id: int) -> RepoCommandResponseMessage: """ Return parsed insert check response message. """ parameter = RepoCommandParameterMessage() parameter.repo_command_parameter.process_id = process_id param_blob = ProtobufTlv.encode(parameter) name = Name(repo_name).append(method + ' check').append(Name.Component(param_blob)) interest = Interest(name) interest.canBePrefix = True interest.setInterestLifetimeMilliseconds(1000) self.face.makeCommandInterest(interest) logging.info('Send ' + method + 'check interest') ret = await fetch_data_packet(self.face, interest) if not isinstance(ret, Data): logging.warning('Check error') return None try: response = self.decode_cmd_response_blob(ret) except RuntimeError as exc: logging.warning('Response blob decoding failed') return None return response
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 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 _sendCertificateRequest(self, keyIdentity): """ We compose a command interest with our public key info so the controller can sign us a certificate that can be used with other nodes in the network. """ try: defaultKey = self._identityStorage.getDefaultKeyNameForIdentity(keyIdentity) except SecurityException: defaultKey = self._identityManager.generateRSAKeyPairAsDefault(keyIdentity) self.log.debug("Key name: " + defaultKey.toUri()) message = CertificateRequestMessage() publicKey = self._identityManager.getPublicKey(defaultKey) message.command.keyType = publicKey.getKeyType() message.command.keyBits = publicKey.getKeyDer().toRawStr() for component in range(defaultKey.size()): message.command.keyName.components.append(defaultKey.get(component).toEscapedString()) paramComponent = ProtobufTlv.encode(message) interestName = Name(self._policyManager.getTrustRootIdentity()).append("certificateRequest").append(paramComponent) interest = Interest(interestName) interest.setInterestLifetimeMilliseconds(10000) # takes a tick to verify and sign self._hmacHandler.signInterest(interest, keyName=self.prefix) self.log.info("Sending certificate request to controller") self.log.debug("Certificate request: "+interest.getName().toUri()) self.face.expressInterest(interest, self._onCertificateReceived, self._onCertificateTimeout)
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 _onData(self, interest, data): """ Process the incoming Chat data. """ # TODO: Check if this works in Python 3. content = chatbuf_pb2.ChatMessage() content.ParseFromString(data.getContent().toBytes()) if self.getNowMilliseconds() - content.timestamp * 1000.0 < 120000.0: # Use getattr because "from" is a reserved keyword. name = getattr(content, "from") prefix = data.getName().getPrefix(-2).toUri() sessionNo = int(data.getName().get(-2).toEscapedString()) sequenceNo = int(data.getName().get(-1).toEscapedString()) nameAndSession = name + str(sessionNo) l = 0 # Update roster. while l < len(self._roster): entry = self._roster[l] tempName = entry[0:len(entry) - 10] tempSessionNo = int(entry[len(entry) - 10:]) if (name != tempName and content.type != chatbuf_pb2.ChatMessage.LEAVE): l += 1 else: if name == tempName and sessionNo > tempSessionNo: self._roster[l] = nameAndSession break if l == len(self._roster): self._roster.append(nameAndSession) print(name + ": Join") # Set the alive timeout using the Interest timeout mechanism. # TODO: Are we sure using a "/local/timeout" interest is the best # future call approach? timeout = Interest(Name("/local/timeout")) timeout.setInterestLifetimeMilliseconds(120000) self._face.expressInterest( timeout, self._dummyOnData, self._makeAlive(sequenceNo, name, sessionNo, prefix)) # isRecoverySyncState_ was set by sendInterest. # TODO: If isRecoverySyncState_ changed, this assumes that we won't get # data from an interest sent before it changed. # Use getattr because "from" is a reserved keyword. if (content.type == chatbuf_pb2.ChatMessage.CHAT and not self._isRecoverySyncState and getattr(content, "from") != self._screenName): print(getattr(content, "from") + ": " + content.data) elif content.type == chatbuf_pb2.ChatMessage.LEAVE: # leave message try: n = self._roster.index(nameAndSession) if name != self._screenName: self._roster.pop(n) print(name + ": Leave") except ValueError: pass
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 run(self): # The default Face connects to the local NFD. face = Face() interest = Interest(Name("/localhost/nfd/faces/channels")) interest.setInterestLifetimeMilliseconds(4000) self.dump("Express interest", interest.getName().toUri()) enabled = [True] def onComplete(content): enabled[0] = False self.printChannelStatuses(content) def onError(errorCode, message): enabled[0] = False self.dump(message) SegmentFetcher.fetch(face, interest, None, onComplete, onError) # Loop calling processEvents until a callback sets enabled[0] = False. while enabled[0]: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01) # print('==================run Channels_status_getter finished===================') face.shutdown() return (self.total_result)
def expressInterest(self, interestTemplate = None): """ Call expressInterest on this (or a parent's) Face where the interest name is the name of this Namespace node. When the Data packet is received this calls setData, so you should use a callback with addOnContentSet. This uses ExponentialReExpress to re-express a timed-out interest with longer lifetimes. TODO: How to alert the application on a final interest timeout? TODO: Replace this by a mechanism for requesting a Data object which is more general than a Face network operation. :raises RuntimeError: If a Face object has not been set for this or a parent Namespace node. :param Interest interestTemplate: (optional) The interest template for expressInterest. If omitted, just use a default interest lifetime. """ face = self._getFace() if face == None: raise ValueError("A Face object has not been set for this or a parent.") def onData(interest, data): self[data.name].setData(data) if interestTemplate == None: interestTemplate = Interest() interestTemplate.setInterestLifetimeMilliseconds(4000) face.expressInterest( self._name, interestTemplate, onData, ExponentialReExpress.makeOnTimeout(face, onData, None))
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 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 get_mpd_ndn(url): """ Module to download the MPD from the URL and save it to file""" print 'Entered get mpd ndn' face = Face("server.simpleNDN.ch-geni-net.geni.case.edu") counter = Counter() s = time.clock() try: name = Name(url) face.expressInterest(name, counter.onData, counter.onTimeout) while counter._callbackCount < 1: face.processEvents() # Try to fetch using a known name. name = Name(url + Version) dump("Express name ", name.toUri()) interest = Interest(name) interest.setInterestLifetimeMilliseconds(1000) SegmentFetcher.fetch(face, interest, None, counter.onComplete, counter.onError) except: config_dash.LOG.error("Unable to download MPD file NDN error") return None while counter._callbackCount < 2: face.processEvents() print("time taken to copy all segments:" + str(time.clock() - s)) mpd_data = Content mpd_file = url.split('/')[-1] mpd_file_handle = open(mpd_file, 'w') print mpd_file_handle mpd_file_handle.write(mpd_data) mpd_file_handle.close() config_dash.LOG.info("Downloaded the MPD file {}".format(mpd_file)) return mpd_file
def main(): # The default Face connects to the local NFD. face = Face() interest = Interest(Name("/localhost/nfd/rib/list")) interest.setInterestLifetimeMilliseconds(4000) dump("Express interest", interest.getName().toUri()) enabled = [True] def onComplete(content): enabled[0] = False printRibEntries(content) def onError(errorCode, message): enabled[0] = False dump(message) SegmentFetcher.fetch( face, interest, SegmentFetcher.DontVerifySegment, onComplete, onError) # Loop calling processEvents until a callback sets enabled[0] = False. while enabled[0]: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01)
def expressInterest(self, interestTemplate=None): """ Call expressInterest on this (or a parent's) Face where the interest name is the name of this Namespace node. When the Data packet is received this calls setData, so you should use a callback with addOnContentSet. This uses ExponentialReExpress to re-express a timed-out interest with longer lifetimes. TODO: How to alert the application on a final interest timeout? TODO: Replace this by a mechanism for requesting a Data object which is more general than a Face network operation. :raises RuntimeError: If a Face object has not been set for this or a parent Namespace node. :param Interest interestTemplate: (optional) The interest template for expressInterest. If omitted, just use a default interest lifetime. """ face = self._getFace() if face == None: raise ValueError( "A Face object has not been set for this or a parent.") def onData(interest, data): self[data.name].setData(data) if interestTemplate == None: interestTemplate = Interest() interestTemplate.setInterestLifetimeMilliseconds(4000) face.expressInterest( self._name, interestTemplate, onData, ExponentialReExpress.makeOnTimeout(face, onData, None))
def requestCertificate(self, keyIdentity): """ We compose a command interest with our public key info so the controller can sign us a certificate that can be used with other nodes in the network. Name format : /home/<device-category>/KEY/<device-id>/<key-id>/<publickey>/ID-CERT/<version-number> """ certificateRequestName = self._keyChain.getDefaultIdentity() deviceIdComponent = certificateRequestName.get(-1) keyIdComponent = keyIdentity.get(-1) certificateRequestName = certificateRequestName certificateRequestName.append("KEY") #certificateRequestName.append(deviceIdComponent) certificateRequestName.append(keyIdComponent) key = self._identityManager.getPublicKey(keyIdentity) keyInfo = {} keyInfo["keyType"] = key.getKeyType() keyInfo["keyDer"] = key.getKeyDer().toRawStr() certificateRequestName.append(json.dumps(keyInfo, encoding="latin-1")) certificateRequestName.append("ID-CERT") certificateRequest = Interest(certificateRequestName) certificateRequest.setInterestLifetimeMilliseconds(5000) self._hmacHelper.signInterest(certificateRequest) dump("Sending certificate request : ",certificateRequestName) self.face.expressInterest(certificateRequest, self.onCertificateData, self.onTimeout)
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 consume(self, prefix, onVerified, onVerifyFailed, onTimeout): """ Consume data continuously under a given prefix, each time sending interest with the last timestamp excluded :param name: prefix to consume data under :type name: Name :param onData: onData(data) gets called after received data's onVerifyFailed :type onData: function object :param onVerifyFailed: onVerifyFailed(data) gets called if received data cannot be verified :type onVerifyFailed: function object :param onTimeout: onTimeout(interest) gets called if a consumer interest times out :type onTimeout: function object """ name = Name(prefix) interest = Interest(name) interest.setInterestLifetimeMilliseconds(self._defaultInterestLifetime) if self._currentTimestamp: exclude = Exclude() exclude.appendAny() exclude.appendComponent(Name.Component.fromVersion(self._currentTimestamp)) interest.setExclude(exclude) self._face.expressInterest(interest, lambda i, d : self.onData(i, d, onVerified, onVerifyFailed, onTimeout), lambda i: self.beforeReplyTimeout(i, onVerified, onVerifyFailed, 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 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 onEntityData(self, interest, data): self.addObject(interest.getName().toUri(), True) self.notifyObserver(interest.getName().toUri(), "ADD", ""); dummyInterest = Interest(Name("/local/timeout")) dummyInterest.setInterestLifetimeMilliseconds(4000) self._face.expressInterest(dummyInterest, self.onDummyData, lambda a : self.expressHeartbeatInterest(a, interest)) return
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 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_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_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 onProfileRequestTimeout(self, interest): dump("Time out for device profile request, send again") interestName = interest.getName().getPrefix(-2) profileRequest = Interest(interestName) profileRequest.setInterestLifetimeMilliseconds(3000) self._accessControlManager.signInterestWithHMACKey(profileRequest,self._newDevice['configurationToken']) self.face.expressInterest(profileRequest, self.onProfile, self.onProfileRequestTimeout)
def _requestDeviceList(self, successCallback, timeoutCallback): self.ui.alert('Requesting services list...', False) interestName = Name(self.prefix).append('listCommands') interest = Interest(interestName) interest.setInterestLifetimeMilliseconds(3000) #self.face.makeCommandInterest(interest) self.face.expressInterest( interest, self._makeOnCommandListCallback(successCallback), self._makeOnCommandListTimeoutCallback(timeoutCallback))
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 expressProfileRequest(self,deviceName): profileRequest = Interest(deviceName.append("profile")) profileRequest.setInterestLifetimeMilliseconds(3000) dump("Request device Profile: ", profileRequest.toUri()) #sign profile request with configuration token self._accessControlManager.signInterestWithHMACKey(profileRequest,self._newDevice['configurationToken']) self.face.expressInterest(profileRequest, self.onProfile, self.onProfileRequestTimeout)
def issueListCommand(self,excludeDevice=None): if excludeDevice == None: interestName = Name(self.listPrefix) #when the controller receive the list from a storage device, it will exclude it from broadcast list. else: interestName = Name(self.listPrefix).append(str("exc")+excludeDevice) command = Interest(interestName) command.setInterestLifetimeMilliseconds(4000) self.face.expressInterest(command,self.onListResponse,self.onListTimeout)
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 _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 _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 _sendCertificateRequest(self, keyIdentity): """ We compose a command interest with our public key info so the controller can sign us a certificate that can be used with other nodes in the network. """ #TODO: GENERATE A NEW PUBLIC/PRIVATE PAIR INSTEAD OF COPYING makeKey = False try: defaultKey = self._identityStorage.getDefaultKeyNameForIdentity(keyIdentity) newKeyName = defaultKey except SecurityException: defaultIdentity = self._keyChain.getDefaultIdentity() defaultKey = self._identityStorage.getDefaultKeyNameForIdentity(defaultIdentity) newKeyName = self._identityStorage.getNewKeyName(keyIdentity, True) makeKey = True self.log.debug("Found key: " + defaultKey.toUri()+ " renaming as: " + newKeyName.toUri()) keyType = self._identityStorage.getKeyType(defaultKey) keyDer = self._identityStorage.getKey(defaultKey) if makeKey: try: privateDer = self._identityManager.getPrivateKey(defaultKey) except SecurityException: # XXX: is recovery impossible? pass else: try: self._identityStorage.addKey(newKeyName, keyType, keyDer) self._identityManager.addPublicKey(newKeyName, keyDer) self._identityManager.addPrivateKey(newKeyName, privateDer) except SecurityException: # TODO: key shouldn't exist... pass message = CertificateRequestMessage() message.command.keyType = keyType message.command.keyBits = keyDer.toRawStr() for component in range(newKeyName.size()): message.command.keyName.components.append(newKeyName.get(component).toEscapedString()) paramComponent = ProtobufTlv.encode(message) interestName = Name(self._policyManager.getTrustRootIdentity()).append("certificateRequest").append(paramComponent) interest = Interest(interestName) interest.setInterestLifetimeMilliseconds(10000) # takes a tick to verify and sign self._hmacHandler.signInterest(interest, keyName=self.prefix) self.log.info("Sending certificate request to controller") self.log.debug("Certificate request: "+interest.getName().toUri()) self.face.expressInterest(interest, self._onCertificateReceived, self._onCertificateTimeout)
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 _requestDeviceList(self, successCallback, timeoutCallback): self.ui.alert("Requesting services list...", False) interestName = Name(self.prefix).append("listCommands") interest = Interest(interestName) interest.setInterestLifetimeMilliseconds(3000) # self.face.makeCommandInterest(interest) self.face.expressInterest( interest, self._makeOnCommandListCallback(successCallback), self._makeOnCommandListTimeoutCallback(timeoutCallback), )
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 _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 _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 issueListCommand(self, excludeDevice=None): if excludeDevice == None: interestName = Name(self.listPrefix) #when the controller receive the list from a storage device, it will exclude it from broadcast list. else: interestName = Name( self.listPrefix).append(str("exc") + excludeDevice) command = Interest(interestName) command.setInterestLifetimeMilliseconds(4000) self.face.expressInterest(command, self.onListResponse, self.onListTimeout)
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 beforeReplyVerificationFailed(self, data, interest, onVerified, onVerifyFailed, onTimeout): # for now internal to the library: verification failed cause the library to retransmit the interest after some time newInterest = Interest(interest) newInterest.refreshNonce() dummyInterest = Interest(Name("/local/timeout")) dummyInterest.setInterestLifetimeMilliseconds(self._verifyFailedRetransInterval) self._face.expressInterest(dummyInterest, self.onDummyData, lambda i: self.retransmitInterest(newInterest, onVerified, onVerifyFailed, onTimeout)) onVerifyFailed(data) return
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 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 main(): if len(sys.argv) < 2: print("argv error: please input turnOn, turnOff or status") exit(1) else: cmd = sys.argv[1] loop = asyncio.get_event_loop() #face = ThreadsafeFace(loop, "localhost") face = Face("localhost") # Counter will stop the ioService after callbacks for all expressInterest. counter = Counter(loop, 3) seed = HMACKey(0,0,"seed","seedName") # Try to fetch anything. name1 = Name("/home/sensor/LED/0/"+cmd+"/0/0") commandTokenName = '/home/sensor/LED/0/'+cmd+'/token/0' commandTokenKey = hmac.new(seed.getKey(), commandTokenName, sha256).digest() accessTokenName = '/home/sensor/LED/0/'+cmd+'/token/0/user/Tom/token/0' accessTokenKey = hmac.new(commandTokenKey, accessTokenName, sha256).digest() accessToken = HMACKey(0,0,accessTokenKey,accessTokenName) dump("seed.getKey() :",seed.getKey()) dump("commandTokenName :",commandTokenName) dump("commandTokenKey :",base64.b64encode(commandTokenKey)) dump("accessTokenName :",accessTokenName) dump("accessTokenKey :",base64.b64encode(accessTokenKey)) interest = Interest(name1) interest.setInterestLifetimeMilliseconds(3000) a = AccessControlManager() a.signInterestWithHMACKey(interest,accessToken) dump("Express name ", interest.toUri()) face.expressInterest(interest, counter.onData, counter.onTimeout) """ name2 = Name("/home/sensor/LED/T0829374723/turnOff") dump("Express name ", name2.toUri()) face.expressInterest(name2, counter.onData, counter.onTimeout) """ while counter._callbackCount < 1: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(2) face.shutdown()
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): 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()