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")
예제 #2
0
    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
예제 #3
0
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)
예제 #5
0
    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
예제 #6
0
 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)
예제 #7
0
    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")
예제 #9
0
 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
예제 #10
0
 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"
예제 #11
0
 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"))
예제 #13
0
 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
예제 #14
0
 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
예제 #15
0
 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
예제 #16
0
 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
예제 #17
0
    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
예제 #18
0
 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
예제 #19
0
    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)
예제 #20
0
    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)
예제 #21
0
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)
예제 #22
0
    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
예제 #23
0
    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
예제 #24
0
    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
예제 #25
0
 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
예제 #26
0
    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)
예제 #27
0
    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)
예제 #28
0
    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
예제 #29
0
    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))
예제 #30
0
    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
예제 #31
0
    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)
예제 #32
0
    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)
예제 #33
0
    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)
예제 #34
0
    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()
예제 #35
0
    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
예제 #36
0
    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
예제 #37
0
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
예제 #38
0
    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
예제 #39
0
    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
예제 #40
0
    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
예제 #41
0
    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
예제 #42
0
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
예제 #43
0
 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)
예제 #44
0
    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
예제 #45
0
 def fetchData(self,name):
     interest = Interest(name)
     interest.setInterestLifetimeMilliseconds(self._interestLifetime)
     interest.setMustBeFresh(self.m_mustBeFresh)
     
     self._face.expressInterest(interest,self.onData,self.onTimeout)
예제 #46
0
 def onReceivedSyncData(self, itemName):
     interest = Interest(Name(itemName))
     interest.setInterestLifetimeMilliseconds(4000)
     interest.setMustBeFresh(False)
     self._face.expressInterest(interest, self.onEntityData, self.onEntityTimeout) 
     return