예제 #1
0
    def __init__(self):
        self.identityStorage = MemoryIdentityStorage()
        self.privateKeyStorage = MemoryPrivateKeyStorage()
        self.keyChain = KeyChain(IdentityManager(self.identityStorage, self.privateKeyStorage),
                        SelfVerifyPolicyManager(self.identityStorage))
        keyName = Name("/testname/DSK-123")
        self.defaultCertName = keyName[:-1].append(
          "KEY").append(keyName[-1]).append("ID-CERT").append("0")

        ecdsaKeyName = Name("/testEcdsa/DSK-123")
        self.ecdsaCertName = ecdsaKeyName[:-1].append(
          "KEY").append(ecdsaKeyName[-1]).append("ID-CERT").append("0")

        self.identityStorage.addKey(
          keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
        self.privateKeyStorage.setKeyPairForKeyName(
          keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER)

        self.identityStorage.addKey(
          ecdsaKeyName, KeyType.EC, Blob(DEFAULT_EC_PUBLIC_KEY_DER))
        self.privateKeyStorage.setKeyPairForKeyName(
          ecdsaKeyName, KeyType.EC, DEFAULT_EC_PUBLIC_KEY_DER, DEFAULT_EC_PRIVATE_KEY_DER)
예제 #2
0
    def createEncryptionKey(self, eKeyName, timeMarker):
        params = RsaKeyParams()
        eKeyName = Name(eKeyName)
        eKeyName.append(timeMarker)

        dKeyBlob = RsaAlgorithm.generateKey(params).getKeyBits()
        eKeyBlob = RsaAlgorithm.deriveEncryptKey(dKeyBlob).getKeyBits()
        self.decryptionKeys[eKeyName] = dKeyBlob

        keyData = Data(eKeyName)
        keyData.setContent(eKeyBlob)
        self.keyChain.sign(keyData, self.certificateName)
        self.encryptionKeys[eKeyName] = keyData
    def test_bad_certificate_name(self):
        interest1 = self._fixture.makeCommandInterest(self._fixture._identity)
        keyLocator = KeyLocator()
        keyLocator.setType(KeyLocatorType.KEYNAME)
        keyLocator.setKeyName(Name("/bad/cert/name"))
        signatureInfo = Sha256WithRsaSignature()
        signatureInfo.setKeyLocator(keyLocator)

        setNameComponent(
            interest1, CommandInterestSigner.POS_SIGNATURE_INFO,
            TlvWireFormat.get().encodeSignatureInfo(signatureInfo))
        self.validateExpectFailure(interest1,
                                   "Should fail (bad certificate name)")
예제 #4
0
    def setUp(self):
        # set up the keychain so we can sign data
        self.identityStorage = MemoryIdentityStorage()
        self.privateKeyStorage = MemoryPrivateKeyStorage()
        self.keyChain = KeyChain(IdentityManager(self.identityStorage, self.privateKeyStorage))
        self.privateKeyStorage = MemoryPrivateKeyStorage()

        # not using keychain for verification so we don't need to set the
        # policy manager
        self.keyChain = KeyChain(IdentityManager(self.identityStorage, self.privateKeyStorage))
        self.identityName = Name('/SecurityTestSecRule/Basic/Longer')
        keyName = Name(self.identityName).append('ksk-2439872')
        self.defaultCertName = self._certNameFromKeyName(keyName)
        self.identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
        self.privateKeyStorage.setKeyPairForKeyName(
      keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER)

        keyName = Name('/SecurityTestSecRule/Basic/ksk-0923489')
        self.identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
        self.privateKeyStorage.setKeyPairForKeyName(
      keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER)
        self.shortCertName = self._certNameFromKeyName(keyName, -2)
예제 #5
0
    def run(self):

        ControllerPrefixString = '/ndn/ie/tcd/controller01/ofndn/'
        ControllerPrefix = Name(ControllerPrefixString)
        self.face.setCommandSigningInfo(self.keyChain, \
                                   self.keyChain.getDefaultCertificateName())

        self.face.registerPrefix(ControllerPrefix, self.onInterest_Mian,
                                 self.onRegisterFailed)  # run prefix

        #filters:
        # hello_msg_prefix = Name('/ndn/ie/tcd/controller01/ofndn/--/n1.0/0/0/0/')
        # self.face.setInterestFilter(hello_msg_prefix,self.onInterest_Hello)   #for HelloReq msg

        error_msg_prefix = Name(
            '/ndn/ie/tcd/controller01/ofndn/--/n1.0/1/0/0/')
        self.face.setInterestFilter(error_msg_prefix,
                                    self.onInterest_ErrorMsg)  # for Error msg

        packetin_msg_prefix = Name(
            '/ndn/ie/tcd/controller01/ofndn/--/n1.0/10/0/0/')
        self.face.setInterestFilter(
            packetin_msg_prefix, self.onInterest_PacketIn)  #for packetin msg

        FlowRemoved_msg_prefix = Name(
            '/ndn/ie/tcd/controller01/ofndn/--/n1.0/11/0/0/')
        self.face.setInterestFilter(
            FlowRemoved_msg_prefix,
            self.onInterest_FlowRemoved)  #for FlowRemoved msg

        # cannot be here, conflict with helloreq, since both of them occupy the 'listening channel' and will not release.
        # CtrlInfo_msg_prefix = Name('/ndn/ie/tcd/controller01/ofndn/--/n1.0/36/0/0/')
        # self.face.setInterestFilter(CtrlInfo_msg_prefix, self.onInterest_CtrlInfo)

        # Run the event loop forever. Use a short sleep to
        # prevent the Producer from using 100% of the CPU.
        while not self.isDone:  #listen hello cannot stop
            self.face.processEvents()
            time.sleep(0.01)
예제 #6
0
    def onSetupComplete(defaultCertificateName, keyChain):
        def onRequestSuccess():
            print "data production authorized by controller"
            startProducers(defaultCertificateName, keyChain)
            return

        def onRequestFailed(msg):
            print "data production request failed : " + msg
            # For this test, we start anyway
            startProducers(defaultCertificateName, keyChain)
            return

        bootstrap.requestProducerAuthorization(Name(request_prefix), appName, onRequestSuccess, onRequestFailed)
예제 #7
0
    def test_encode_decode(self):
        name = Name("/local/ndn/prefix")

        encoding = name.wireEncode(TlvWireFormat.get())
        self.assertTrue(encoding.equals(Blob(TEST_NAME)))

        decodedName = Name()
        decodedName.wireDecode(Blob(TEST_NAME), TlvWireFormat.get())
        self.assertEqual(decodedName, name)

        # Test ImplicitSha256Digest.
        name2 = Name(
            "/local/ndn/prefix/sha256digest=" +
            "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f")

        encoding2 = name2.wireEncode(TlvWireFormat.get())
        self.assertTrue(encoding2.equals(Blob(TEST_NAME_IMPLICIT_DIGEST)))

        decodedName2 = Name()
        decodedName2.wireDecode(Blob(TEST_NAME_IMPLICIT_DIGEST),
                                TlvWireFormat.get())
        self.assertEqual(decodedName2, name2)
예제 #8
0
 def sendRandomCommand(self):
     try:
         chosenCommand = random.choice(self._ledCommands)
         interest = Interest(Name(chosenCommand))
         self.log.debug('Sending command {}'.format(chosenCommand))
         # uncomment the following line to sign interests (slower than unsigned)
         #self.face.makeCommandInterest(interest)
         self.face.expressInterest(interest, self.onCommandAck,
                                   self.onCommandTimeout)
     except IndexError:
         pass
     finally:
         self.loop.call_later(1, self.sendRandomCommand)
예제 #9
0
    def setUp(self):
        self.toyCertNotBefore = 1388100174000
        self.toyCertNotAfter = 1388100174000
        cert = Certificate()
        cert.setName(Name("/test/KEY/ksk-1457560485494/ID-CERT/%FD%00%00%01S%80H%E1%F3"))
        cert.setNotBefore(self.toyCertNotBefore)
        cert.setNotAfter(self.toyCertNotAfter)

        cert.addSubjectDescription(CertificateSubjectDescription(TEST_OID, "TEST NAME"))
        key = PublicKey(Blob(PUBLIC_KEY))

        cert.setPublicKeyInfo(key)
        self.toyCert = cert
예제 #10
0
def listenForOnboardingRequests():

    # Also use the default certificate name to sign data packets.
    onboardListener = OnboardListener(keyChain,
                                      keyChain.getDefaultCertificateName())
    prefix = Name("/NIST/library/mainroom/repo1/proxy/onboard")
    dump("Register prefix", prefix.toUri())
    face.registerPrefix(prefix, onboardListener.onInterest,
                        onboardListener.onRegisterFailed)

    while True:
        face.processEvents()
        time.sleep(0.01)
예제 #11
0
 def perform_delete(self, prefix: str, start_block_id: int,
                    end_block_id: int) -> int:
     """
     Perform DB delete.
     Return the number of data items deleted.
     """
     delete_num = 0
     for idx in range(start_block_id, end_block_id + 1):
         key = str(Name(prefix).append(str(idx)))
         if self.storage.exists(key):
             self.storage.remove(key)
             delete_num += 1
     return delete_num
예제 #12
0
파일: server.py 프로젝트: zjkmxy/GitSync
 def register_prefix(prefix: Union[str, Name]):
     self.face.registerPrefix(prefix, None, self.on_register_failed)
     self.face.setInterestFilter(Name(prefix).append("push"), self.on_push)
     self.face.setInterestFilter(Name(prefix).append("create-branch"), self.on_create_branch)
     self.face.setInterestFilter(Name(prefix).append("track-repo"), self.on_track_repo)
     self.face.setInterestFilter(Name(prefix).append("mount"), self.on_mount)
     self.face.setInterestFilter(Name(prefix).append("unmount"), self.on_unmount)
     self.face.setInterestFilter(Name(prefix).append("commit"), self.on_commit)
예제 #13
0
    def test_name_relation(self):
        policyManagerPrefix = ConfigPolicyManager("policy_config/relation_ruleset_prefix.conf")
        policyManagerStrict = ConfigPolicyManager("policy_config/relation_ruleset_strict.conf")
        policyManagerEqual = ConfigPolicyManager("policy_config/relation_ruleset_equal.conf")

        dataName = Name('/TestRule1')

        self.assertIsNotNone(
                policyManagerPrefix._findMatchingRule(dataName, 'data'),
                "Prefix relation should match prefix name")
        self.assertIsNotNone(
                policyManagerEqual._findMatchingRule(dataName, 'data'),
                "Equal relation should match prefix name")
        self.assertIsNone(
                policyManagerStrict._findMatchingRule(dataName, 'data'),
                "Strict-prefix relation should not match prefix name")

        dataName = Name('/TestRule1/hi')
        self.assertIsNotNone(
                policyManagerPrefix._findMatchingRule(dataName, 'data'),
                "Prefix relation should match longer name")
        self.assertIsNone(
                policyManagerEqual._findMatchingRule(dataName, 'data'),
                "Equal relation should not match longer name")
        self.assertIsNotNone(
                policyManagerStrict._findMatchingRule(dataName, 'data'),
                "Strict-prefix relation should match longer name")

        dataName = Name('/Bad/TestRule1/')
        self.assertIsNone(
                policyManagerPrefix._findMatchingRule(dataName, 'data'),
                "Prefix relation should not match inner components")
        self.assertIsNone(
                policyManagerEqual._findMatchingRule(dataName, 'data'),
                "Equal relation should not match inner components")
        self.assertIsNone(
                policyManagerStrict._findMatchingRule(dataName, 'data'),
                "Strict-prefix relation should  not match inner components")
예제 #14
0
async def fetch_object(face: Face, prefix: Name,
                       semaphore: asyncio.Semaphore) -> Optional[bytes]:
    async def retry_or_fail() -> Optional[Data]:
        nonlocal interest
        result = None
        # retry for up to FETCHER_MAX_ATTEMPT_NUMBER times
        for _ in range(FETCHER_MAX_ATTEMPT_NUMBER):
            # express interest
            async with semaphore:
                response = await fetch_data_packet(face, interest)
            if isinstance(response, Data):
                # if succeeded, jump out
                result = response
                break
            else:
                # if failed, wait for next time
                await asyncio.sleep(FETCHER_RETRY_INTERVAL / 1000.0)
        return result

    data = bytes("", "utf-8")
    final_id = FETCHER_FINAL_BLOCK_ID
    cur_id = 0
    while cur_id <= final_id:
        if cur_id == 0:
            interest = Interest(Name(prefix))
        else:
            interest = Interest(Name(prefix).appendSegment(cur_id))
        data_packet = await retry_or_fail()
        if data_packet is None:
            return None
        data += data_packet.content.toBytes()
        final_id_component = data_packet.metaInfo.getFinalBlockId()
        if final_id_component.isSegment():
            final_id = final_id_component.toSegment()
        else:
            break
        cur_id += 1
    return data
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)
예제 #16
0
    def _updateDeviceCapabilities(self, interest):
        """
        Take the received capabilities update interest and update our directory listings.
        """
        # we assume the sender is the one who signed the interest...
        signature = self._policyManager._extractSignature(interest)
        certificateName = signature.getKeyLocator().getKeyName()
        senderIdentity = IdentityCertificate.certificateNameToPublicKeyName(certificateName).getPrefix(-1)

        self.log.info('Updating capabilities for {}'.format(senderIdentity.toUri()))

        # get the params from the interest name
        messageComponent = interest.getName().get(self.prefix.size()+1)
        message = UpdateCapabilitiesCommandMessage()
        ProtobufTlv.decode(message, messageComponent.getValue())
        # we remove all the old capabilities for the sender
        tempDirectory = defaultdict(list)
        for keyword in self._directory:
            tempDirectory[keyword] = [cap for cap in self._directory[keyword] 
                    if not senderIdentity.match(Name(cap['name']))]

        # then we add the ones from the message
        for capability in message.capabilities:
            capabilityPrefix = Name()
            for component in capability.commandPrefix.components:
                capabilityPrefix.append(component)
            commandUri = capabilityPrefix.toUri()
            if not senderIdentity.match(capabilityPrefix):
                self.log.error("Node {} tried to register another prefix: {} - ignoring update".format(
                    senderIdentity.toUri(),commandUri))
            else:    
                for keyword in capability.keywords:
                    allUris = [info['name'] for info in tempDirectory[keyword]]
                    if capabilityPrefix not in allUris:
                        listing = {'signed':capability.needsSignature,
                                'name':commandUri}
                        tempDirectory[keyword].append(listing)
        self._directory= tempDirectory
예제 #17
0
    def populateSensorNDNDictFromCSV(self, csvFileName):
        with open(csvFileName, 'rU') as csvFile:
            reader = csv.reader(csvFile, delimiter=',', quotechar='|')

            campusComponentName = "ucla"
            for row in reader:
                if (len(row)) > 5:
                    # sensor full name, building name, room name, sensor name, sensor data type
                    #print(row[1], row[2], row[3], row[4], row[5])
                    key = ''
                    dataType = "unknown_data_type"
                    if (row[5] != ''):
                        dataType = row[5]
                    if (row[3] != ''):
                        key = row[2].lower().strip() + '.' + row[3].lower(
                        ).strip() + '.' + row[4].lower().strip()
                        ndnNameString = campusComponentName + '/' + row[
                            2].lower().strip() + '/' + row[3].lower().strip(
                            ) + '/' + row[4].lower().strip()
                        aggregationName = Name(ndnNameString).append(
                            'data').append(dataType).append('aggregation')
                        instName = Name(ndnNameString).append('data').append(
                            dataType).append('inst')

                        self._sensorNDNDict[key] = SensorNDNDictItem(
                            aggregationName, instName)
                    else:
                        key = row[2].lower().strip() + '.' + row[4].lower(
                        ).strip()
                        ndnNameString = campusComponentName + '/' + row[
                            2].lower().strip() + '/' + row[4].lower().strip()
                        aggregationName = Name(ndnNameString).append(
                            'data').append(dataType).append('aggregation')
                        instName = Name(ndnNameString).append('data').append(
                            dataType).append('inst')

                        self._sensorNDNDict[key] = SensorNDNDictItem(
                            aggregationName, instName)
예제 #18
0
    def _sendInterest(self, syncStates, isRecovery):
        """
        Send a Chat Interest to fetch chat messages after the user gets the Sync
        data packet back but will not send interest.
        """
        # This is used by _onData to decide whether to display the chat messages.
        self._isRecoverySyncState = isRecovery

        sendList = []  # of str
        sessionNoList = []  # of int
        sequenceNoList = []  # of int
        for j in range(len(syncStates)):
            syncState = syncStates[j]
            nameComponents = Name(syncState.getDataPrefix())
            tempName = nameComponents.get(-1).toEscapedString()
            sessionNo = syncState.getSessionNo()
            if not tempName == self._screenName:
                index = -1
                for k in range(len(sendList)):
                    if sendList[k] == syncState.getDataPrefix():
                        index = k
                        break

                if index != -1:
                    sessionNoList[index] = sessionNo
                    sequenceNoList[index] = syncState.getSequenceNo()
                else:
                    sendList.append(syncState.getDataPrefix())
                    sessionNoList.append(sessionNo)
                    sequenceNoList.append(syncState.getSequenceNo())

        for i in range(len(sendList)):
            uri = (sendList[i] + "/" + str(sessionNoList[i]) + "/" +
                   str(sequenceNoList[i]))
            interest = Interest(Name(uri))
            interest.setInterestLifetimeMilliseconds(self._syncLifetime)
            self._face.expressInterest(interest, self._onData,
                                       self._chatTimeout)
예제 #19
0
    def _onConfigurationReceived(self, prefix, interest, transport, prefixId):
        # the interest we get here is signed by HMAC, let's verify it
        self.tempPrefixId = prefixId  # didn't get it from register because of the event loop
        interestName = interest.getName()
        replyData = Data(interestName)
        if len(interestName) == len(prefix):
            # this is a discovery request. Check the exclude to see if we should
            # return our serial
            serial = self.getSerial()
            serialComponent = Name.Component(serial)
            if not interest.getExclude().matches(serialComponent):
                replyData.setContent(serial)
                self.sendData(replyData, transport,
                              False)  # no point in signing
        elif (self._hmacHandler.verifyInterest(interest)):
            # we have a match! decode the network parameters
            configComponent = interest.getName()[len(prefix) + 1]
            replyData.setContent('200')
            self._hmacHandler.signData(replyData, keyName=self.prefix)
            transport.send(replyData.wireEncode().buf())

            environmentConfig = DeviceConfigurationMessage()
            ProtobufTlv.decode(environmentConfig, configComponent.getValue())
            networkPrefix = self._extractNameFromField(
                environmentConfig.configuration.networkPrefix)
            controllerName = self._extractNameFromField(
                environmentConfig.configuration.controllerName)
            controllerName = Name(networkPrefix).append(controllerName)

            self._policyManager.setEnvironmentPrefix(networkPrefix)
            self._policyManager.setTrustRootIdentity(controllerName)

            self.deviceSuffix = self._extractNameFromField(
                environmentConfig.configuration.deviceSuffix)

            self._configureIdentity = Name(networkPrefix).append(
                self.deviceSuffix)
            self._sendCertificateRequest(self._configureIdentity)
예제 #20
0
def main():
    data = Data()
    data.wireDecode(TlvData)
    dump("Decoded Data:")
    dumpData(data)

    # Set the content again to clear the cached encoding so we encode again.
    data.setContent(data.getContent())
    encoding = data.wireEncode()

    reDecodedData = Data()
    reDecodedData.wireDecode(encoding)
    dump("")
    dump("Re-decoded Data:")
    dumpData(reDecodedData)

    # Set up the KeyChain.
    keyChain = KeyChain("pib-memory:", "tpm-memory:")
    keyChain.importSafeBag(
        SafeBag(Name("/testname/KEY/123"),
                Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False),
                Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)))
    validator = Validator(ValidationPolicyFromPib(keyChain.getPib()))

    validator.validate(reDecodedData, makeSuccessCallback("Re-decoded Data"),
                       makeFailureCallback("Re-decoded Data"))

    freshData = Data(Name("/ndn/abc"))
    freshData.setContent("SUCCESS!")
    freshData.getMetaInfo().setFreshnessPeriod(5000)
    freshData.getMetaInfo().setFinalBlockId(Name("/%00%09")[0])
    keyChain.sign(freshData)
    dump("")
    dump("Freshly-signed Data:")
    dumpData(freshData)

    validator.validate(freshData, makeSuccessCallback("Freshly-signed Data"),
                       makeFailureCallback("Freshly-signed Data"))
예제 #21
0
 def rightKey(event):
     global currentSlideName
     allVersions = newspaper.getChildComponents()
     currentVersion = currentSlideName[-1]
     selected = None
     for c in allVersions[::-1]:
         if c.toVersion() == currentVersion.toVersion():
             break
         selected = c
     if selected:
         currentSlideName = Name(newspaper.getName()).append(selected)
         displayImage(newspaper.getChild(selected).content.toRawStr(), currentSlideName.toUri())
     else:
         print("no slides to show")
예제 #22
0
    def run(self):

        try:

            self._sendNextInterest(Name(self.nameInput))

            while not self.isDone:
                self.face.processEvents()
                time.sleep(0.01)

        except RuntimeError as e:
            print "ERROR: %s" % e

        return True
예제 #23
0
 def onInterest_pullService(self, prefix, interest, face, interestFilterId,
                            filter):
     ### This function is used in ACM ICN where the SEG receive the trigger message to pull the service
     interestName = interest.getName()
     print "Interest Name: %s" % interestName
     interest_name_components = interestName.toUri().split("/")
     image_fileName = interest_name_components[
         interest_name_components.index("pull_Service") + 1]
     if "pull_Service" in interest_name_components:
         prefix_pullImage = Name("/picasso/service_deployment_pull/" +
                                 image_fileName)
         print 'Sending Interest message: %s' % prefix_pullImage
         self._sendNextInterest(prefix_pullImage, self.interestLifetime,
                                'pull')
    def publishMetadata(self):
        # For now, hardcoded sensor list on gateway's end
        data = Data(
            Name(self._namespace).append("_meta").append(
                str(int(time.time() * 1000.0))))
        data.setContent(json.dumps(self._sensorList))
        data.getMetaInfo().setFreshnessPeriod(self._defaultFreshnessPeriod)
        self._keyChain.sign(data)
        self._cache.add(data)
        print("Metadata " + data.getName().toUri() +
              " added for sensor list: " + str(self._sensorList))

        self.startRepoInsertion(data)
        return
 def test_encode_decode_with_no_name(self):
     parameters = ControlParameters()
     parameters.setStrategy(Name("/localhost/nfd/strategy/broadcast"))
     parameters.setUri("null://")
     # encode
     encoded = parameters.wireEncode()
     # decode
     decodedParameters = ControlParameters()
     decodedParameters.wireDecode(encoded)
     # compare
     self.assertEqual(decodedParameters.getName(), None)
     self.assertEqual(parameters.getStrategy().toUri(),
                      decodedParameters.getStrategy().toUri())
     self.assertEqual(parameters.getUri(), decodedParameters.getUri())
def main():
    """
    Call requestInsert and register a prefix so that ProduceSegments will answer
    interests from the repo to send the data packets. This assumes that repo-ng
    is already running (e.g. `sudo ndn-repo-ng`).
    """
    repoCommandPrefix = Name("/example/repo/1")
    repoDataPrefix = Name("/example/data/1")

    nowMilliseconds = int(time.time() * 1000.0)
    fetchPrefix = Name(repoDataPrefix).append("testinsert").appendVersion(
        nowMilliseconds)

    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()
    # Use the system default key chain and certificate name to sign commands.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    # Register the prefix and send the repo insert command at the same time.
    startBlockId = 0
    endBlockId = 1
    enabled = [True]
예제 #27
0
def stopRepoWatch(face, repoCommandPrefix, watchPrefix, onRepoWatchStopped,
                  onFailed):
    """
    Send a command interest for the repo to stop watching the given watchPrefix.
    Since this calls expressInterest, your application must call face.processEvents.

    :param Face face: The Face used to call makeCommandInterest and expressInterest.
    :param Name repoCommandPrefix: The repo command prefix.
    :param Name watchPrefix: The prefix that the repo will stop watching.
    :param onRepoWatchStopped: When the stop watch command successfully returns,
      this calls onRepoWatchStopped().
    :type onRepoWatchStopped: function object
    :param onFailed: If the command fails for any reason, this prints an error
      and calls onFailed().
    :type onFailed: function object
    """
    # repo_command_parameter_pb2 was produced by protoc.
    parameter = repo_command_parameter_pb2.RepoCommandParameterMessage()
    for i in range(watchPrefix.size()):
        parameter.repo_command_parameter.name.component.append(
            watchPrefix[i].getValue().toBytes())

    # Create the command interest.
    interest = Interest(
        Name(repoCommandPrefix).append("watch").append("stop").append(
            Name.Component(ProtobufTlv.encode(parameter))))
    face.makeCommandInterest(interest)

    # Send the command interest and get the response or timeout.
    def onData(interest, data):
        # repo_command_response_pb2 was produced by protoc.
        response = repo_command_response_pb2.RepoCommandResponseMessage()
        try:
            ProtobufTlv.decode(response, data.content)
        except:
            dump("Cannot decode the repo command response")
            onFailed()

        if response.repo_command_response.status_code == 101:
            onRepoWatchStopped()
        else:
            dump("Got repo command error code",
                 response.repo_command_response.status_code)
            onFailed()

    def onTimeout(interest):
        dump("Stop repo watch command timeout")
        onFailed()

    face.expressInterest(interest, onData, onTimeout)
예제 #28
0
 def __init__(self, namePrefix, producerName):
     self.configPrefix = Name(namePrefix)
     self.outstanding = dict()
     self.isDone = False
     self.keyChain = KeyChain()
     self.face = Face("127.0.0.1")
     #self.DataStore = DS.readDataStore_json()
     #self.DataStore = DS.table
     self.script_path = os.path.abspath(
         __file__)  # i.e. /path/to/dir/foobar.py
     self.script_dir = os.path.split(
         self.script_path)[0]  #i.e. /path/to/dir/
     self.Datamessage_size = 8000  #8kB --> Max Size from NDN standard
     self.producerName = producerName
예제 #29
0
    def test_nacked_interests(self):
        def processInterest(interest, onData, onTimeout, onNetworkNack):
            networkNack = NetworkNack()
            networkNack.setReason(NetworkNack.Reason.NO_ROUTE)

            onNetworkNack(interest, networkNack)
        self._fixture._face._processInterest = processInterest

        data = Data(Name("/Security/V2/ValidatorFixture/Sub1/Sub2/Data"))
        self._fixture._keyChain.sign(data, SigningInfo(self._fixture._subIdentity))

        self.validateExpectFailure(data, "All interests should get NACKed")
        # There should be multiple expressed interests due to retries.
        self.assertTrue(len(self._fixture._face._sentInterests) > 1)
예제 #30
0
        def __init__(self, namespace, userPrefix, face, keyChain,
                     certificateName):
            self._namespace = namespace
            self._namespacePrefix = namespace.getName()
            self._userPrefix = userPrefix
            self._face = face
            self._keyChain = keyChain
            self._certificateName = certificateName

            self._messageCache = []  # of CachedMessage
            self._maxMessageCacheLength = 100
            self._isRecoverySyncState = False
            self._syncLifetime = 5000.0  # milliseconds
            self._namespaceMessageFreshnessPeriod = 4000.0

            self._sync = ChronoSync2013(
                self._sendInterest, self._initial, Name(userPrefix),
                Name("/ndn/broadcast/namesync").append(self._namespacePrefix),
                0, face, keyChain, certificateName, self._syncLifetime,
                self._onRegisterFailed)

            face.registerPrefix(self._userPrefix, self._onInterest,
                                self._onRegisterFailed)