def publish(self, line):
        dataObject = json.loads(line)
        locationName = Name(
            self.msgLocationToHierarchicalName(dataObject["sensor_id"]))
        if not (locationName.toUri() in self._sensorList):
            print self._sensorLocations
            print locationName.toUri()
            if locationName.toUri() in self._sensorLocations:
                x = self._sensorLocations[locationName.toUri()]['X']
                y = self._sensorLocations[locationName.toUri()]['Y']
                self._sensorList[locationName.toUri()] = {
                    "id": locationName.toUri(),
                    "x": x,
                    "y": y
                }
            else:
                self._sensorList[locationName.toUri()] = {
                    "id": locationName.toUri()
                }
            self.publishMetadata()
        dataName = Name(self._namespace).append(locationName).append(
            self.msgTimestampToNameComponent(dataObject["timestamp"]))
        data = Data(dataName)
        data.setContent(line)
        data.getMetaInfo().setFreshnessPeriod(self._defaultFreshnessPeriod)
        self._keyChain.sign(data)
        self._cache.add(data)
        print("Data " + dataName.toUri() + " added for record: " + line)

        self.startRepoInsertion(data)
Example #2
0
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    face = Face("memoria.ndn.ucla.edu")

    counter = Counter()

    # Try to fetch anything.
    name1 = Name("/")
    dump("Express name ", name1.toUri())
    face.expressInterest(name1, counter.onData, counter.onTimeout)

    # Try to fetch using a known name.
    name2 = Name("/ndn/edu/ucla/remap/demo/ndn-js-test/hello.txt/%FDU%8D%9DM")
    dump("Express name ", name2.toUri())
    face.expressInterest(name2, counter.onData, counter.onTimeout)

    # Expect this to time out.
    name3 = Name("/test/timeout")
    dump("Express name ", name3.toUri())
    face.expressInterest(name3, counter.onData, counter.onTimeout)

    while counter._callbackCount < 3:
        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()
Example #3
0
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    loop = asyncio.get_event_loop()
    face = ThreadsafeFace(loop, "memoria.ndn.ucla.edu")

    # Counter will stop the ioService after callbacks for all expressInterest.
    counter = Counter(loop, 3)

    # Try to fetch anything.
    name1 = Name("/")
    dump("Express name ", name1.toUri())
    # These call to exressIinterest is thread safe because face is a ThreadsafeFace.
    face.expressInterest(name1, counter.onData, counter.onTimeout)

    # Try to fetch using a known name.
    name2 = Name("/ndn/edu/ucla/remap/demo/ndn-js-test/hello.txt/%FDU%8D%9DM")
    dump("Express name ", name2.toUri())
    face.expressInterest(name2, counter.onData, counter.onTimeout)

    # Expect this to time out.
    name3 = Name("/test/timeout")
    dump("Express name ", name3.toUri())
    face.expressInterest(name3, counter.onData, counter.onTimeout)

    # Run until the Counter calls stop().
    loop.run_forever()
    face.shutdown()
Example #4
0
def main():
    # Connect to the demo host at memoria.ndn.ucla.edu .
    face = Face("128.97.98.8")

    counter = Counter()

    # Try to fetch anything.
    name1 = Name("/")
    dump("Express name ", name1.toUri())
    face.expressInterest(name1, counter.onData, counter.onTimeout)

    # Try to fetch using a known name.
    name2 = Name("/ndn/edu/ucla/remap/demo/ndn-js-test/hello.txt/%FDX%DC5%1F")
    dump("Express name ", name2.toUri())
    face.expressInterest(name2, counter.onData, counter.onTimeout)

    # Expect this to time out.
    name3 = Name("/test/timeout")
    dump("Express name ", name3.toUri())
    face.expressInterest(name3, counter.onData, counter.onTimeout)

    while counter._callbackCount < 3:
        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()
Example #5
0
def main():
    face = Face("aleph.ndn.ucla.edu")

    counter = Counter()

    # Try to fetch anything.
    name1 = Name("/")
    dump("Express name ", name1.toUri())
    face.expressInterest(name1, counter.onData, counter.onTimeout)

    # Try to fetch using a known name.
    name2 = Name("/ndn/edu/ucla/remap/demo/ndn-js-test/hello.txt/%FDU%8D%9DM")
    dump("Express name ", name2.toUri())
    face.expressInterest(name2, counter.onData, counter.onTimeout)

    # Expect this to time out.
    name3 = Name("/test/timeout")
    dump("Express name ", name3.toUri())
    face.expressInterest(name3, counter.onData, counter.onTimeout)

    while counter._callbackCount < 3:
        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()
Example #6
0
    def test_append(self):
        # could possibly split this into different tests
        uri = "/localhost/user/folders/files/%00%0F"
        name = Name(uri)
        name2 = Name("/localhost").append(Name("/user/folders/"))
        self.assertEqual(
            len(name2), 3, 'Name constructed by appending names has ' +
            str(len(name2)) + ' components instead of 3')
        self.assertTrue(name2[2].getValue() == Blob("folders"),
                        'Name constructed with append has wrong suffix')
        name2 = name2.append("files")
        self.assertEqual(
            len(name2), 4, 'Name constructed by appending string has ' +
            str(len(name2)) + ' components instead of 4')
        name2 = name2.appendSegment(15)
        self.assertTrue(
            name2[4].getValue() == Blob(bytearray([0x00, 0x0F])),
            'Name constructed by appending segment has wrong segment value')

        self.assertTrue(
            name2 == name,
            'Name constructed with append is not equal to URI constructed name'
        )
        self.assertEqual(name2.toUri(), name.toUri(),
                         'Name constructed with append has wrong URI')
Example #7
0
def main():
    loop = asyncio.get_event_loop()
    # Connect to the demo host at memoria.ndn.ucla.edu .
    face = ThreadsafeFace(loop, "128.97.98.8")

    # Counter will stop the ioService after callbacks for all expressInterest.
    counter = Counter(loop, 3)

    # Try to fetch anything.
    name1 = Name("/")
    dump("Express name ", name1.toUri())
    # These call to exressIinterest is thread safe because face is a ThreadsafeFace.
    face.expressInterest(name1, counter.onData, counter.onTimeout)

    # Try to fetch using a known name.
    name2 = Name("/ndn/edu/ucla/remap/demo/ndn-js-test/hello.txt/%FDX%DC5%1F")
    dump("Express name ", name2.toUri())
    face.expressInterest(name2, counter.onData, counter.onTimeout)

    # Expect this to time out.
    name3 = Name("/test/timeout")
    dump("Express name ", name3.toUri())
    face.expressInterest(name3, counter.onData, counter.onTimeout)

    # Run until the Counter calls stop().
    loop.run_forever()
    face.shutdown()
Example #8
0
    def onBootstrapData(self, interest, data):
        dump("Bootstrap data received.")

        if (self._accessControlManager.verifyDataWithHMACKey(data, self._bootstrapKey)):
            dump("Verified")
            content = json.loads(data.getContent().toRawStr(), encoding="latin-1")
            deviceNewIdentity = Name(content["deviceNewIdentity"])
            controllerIdentity = Name(content["controllerIdentity"])
            controllerPublicKeyInfo = content["controllerPublicKey"]
              
            #add prefix to device profile
            self._deviceProfile.setPrefix(deviceNewIdentity.toUri())

            seed = HMACKey(content["seedSequence"], 0, str(content["seed"]), "seedName")
            self._seed = seed

            configurationTokenSequence = content["configurationTokenSequence"]
           
            #generate configuration token
            configurationTokenName = controllerIdentity.toUri()+"/"+str(configurationTokenSequence)

            configurationTokenKey = hmac.new(seed.getKey(), configurationTokenName, sha256).digest()
            self._configurationToken = HMACKey(configurationTokenSequence, 0, configurationTokenKey, configurationTokenName)

            #register new identity 
            dump("Registered new prefix: ", deviceNewIdentity.toUri())
            self.face.registerPrefix(content["deviceNewIdentity"],self.onInterest,self.onRegisterFailed)

            #set new identity as default and generate default key-pair with KSK Certificate
            self._identityStorage.addIdentity(deviceNewIdentity)
            self._identityManager.setDefaultIdentity(deviceNewIdentity)
            try:
                self._identityManager.getDefaultKeyNameForIdentity(deviceNewIdentity)
                dump("device identity already exists")
            except SecurityException:
                #generate new key-pair and certificate for new identity
                dump("Install new identity as default\nGenerate new key-pair and self signed certificate")
                newKey = self._identityManager.generateRSAKeyPairAsDefault(Name(deviceNewIdentity), isKsk=True)
                newCert = self._identityManager.selfSign(newKey)
                self._identityManager.addCertificateAsIdentityDefault(newCert)
            
            #add controller's identity and public key
            keyType = controllerPublicKeyInfo["keyType"]
            keyName = Name(controllerPublicKeyInfo["keyName"])
            keyDer = Blob().fromRawStr(controllerPublicKeyInfo["publicKeyDer"])

            self._identityStorage.addIdentity(controllerIdentity)
            try:
                self._identityStorage.addKey(keyName, keyType, keyDer)
                dump("Controller's identity, key and certificate installled")
            except SecurityException:
                dump("Controller's identity, key, certificate already exists.")

            #express an certificate request interest
            #defaultKeyName = self._identityManager.getDefaultKeyNameForIdentity(self._keyChain.getDefaultIdentity() )
            #self.requestCertificate(defaultKeyName)
        else:
            dump("Not verified")
Example #9
0
def status_put(name, data):

    # Use the system default key chain and certificate name to sign commands.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())
    
    # Also use the default certificate name to sign data packets.
    echo = Echo(keyChain, keyChain.getDefaultCertificateName(), data)
    prefix = Name(name)
    dump("Register prefix", prefix.toUri())
    logging.debug('Register prefix ' + prefix.toUri())

    face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed)
    face.processEvents()
Example #10
0
    def test_append(self):
        # could possibly split this into different tests
        uri = "/localhost/user/folders/files/%00%0F"
        name = Name(uri)
        name2 = Name("/localhost").append(Name("/user/folders/"))
        self.assertEqual(len(name2), 3, 'Name constructed by appending names has ' + str(len(name2)) + ' components instead of 3')
        self.assertTrue(name2[2].getValue() == Blob("folders"), 'Name constructed with append has wrong suffix')
        name2 = name2.append("files")
        self.assertEqual(len(name2), 4, 'Name constructed by appending string has ' + str(len(name2)) + ' components instead of 4')
        name2 = name2.appendSegment(15)
        self.assertTrue(name2[4].getValue() == Blob(bytearray([0x00, 0x0F])), 'Name constructed by appending segment has wrong segment value')

        self.assertTrue(name2 == name, 'Name constructed with append is not equal to URI constructed name')
        self.assertEqual(name2.toUri(), name.toUri(), 'Name constructed with append has wrong URI')
def onDataInterest(prefix, interest, transport, pxID):
    '''
       For publishing face
    '''
    # just make up some data and return it
    interestName = interest.getName()
    logger.info("Interest for " + interestName.toUri())

    ## CURRENTLY ASSUMES THERE'S A VERSION/SEGMENT SUFFIX!
    dataName = Name(interestName.getPrefix(-1))
    ts = (time.time())
    segmentId = 0
    try:
       segmentId = interestName().get(-1).toSegment()
    except:
        logger.debug("Could not find segment id!")
    dataName.appendSegment(segmentId)

    versionStr = interestName.get(-2).getValue().toRawStr()
    logger.debug('publishing ' + versionStr)
    info = getInfoForVersion(versionStr)

    d = Data(dataName)
    content = "(" + str(ts) +  ") Data named " + dataName.toUri()
    d.setContent(content)
    d.getMetaInfo().setFinalBlockID(segmentId)
    keychain.sign(d, certName)

    encodedData = d.wireEncode()
    now = time.time()

    if info is not None:
        info['publish_time'] = now
    transport.send(encodedData.toBuffer())
Example #12
0
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
                        None)
    keyChain.setFace(face)

    # 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)

    echo = Echo(keyChain, certificateName)
    prefix = Name("/testecho")
    dump("Register prefix", prefix.toUri())
    face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed)

    while echo._responseCount < 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()
Example #13
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)
    def onPublishInterest(self, prefix, interest, transport, pxID):
        '''
           For publishing face
        '''
        # just make up some data and return it
        interestName = interest.getName()
        logger.info("Interest for " + interestName.toUri())

        ## CURRENTLY ASSUMES THERE'S A VERSION+SEGMENT SUFFIX!
        dataName = Name(interestName)
        ts = (time.time())
        segmentId = 0
        #try:
        #   segmentId = interestName.get(-1).toSegment()
        #except:
            #logger.debug("Could not find segment id!")
            #dataName.appendSegment(segmentId)
        versionStr = str(interestName.get(-2).getValue())
        logger.debug('Publishing ' + versionStr + ' @ ' + str(ts))

        d = Data(dataName)
        content = "(" + str(ts) +  ") Data named " + dataName.toUri()
        d.setContent(content)
        d.getMetaInfo().setFinalBlockID(segmentId)
        d.getMetaInfo().setFreshnessPeriod(1000)
        self.keychain.sign(d, self.certificateName)

        encodedData = d.wireEncode()

        stats.insertDataForVersion(versionStr, {'publish_time': time.time()})
        transport.send(encodedData.toBuffer())
Example #15
0
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
	print "received interest"
        initInterest = Name(interest.getName())
        print "interest name:",initInterest.toUri()
	d = Data(interest.getName().append(self.deviceComponent))
	try:
		print "start to set data's content"
                
		currentString = ','.join(currentList)
		d.setContent("songList of " +self.device+":"+currentString+ "\n")
		self.face.registerPrefix(self.changePrefix,self.onInterest,self.onRegisterFailed)	



	    

	except KeyboardInterrupt:
		print "key interrupt"
		sys.exit(1)
	except Exception as e:
		print e
		d.setContent("Bad command\n")
	finally:
		self.keychain.sign(d,self.certificateName)

	encodedData = d.wireEncode()
	transport.send(encodedData.toBuffer())
	print d.getName().toUri()
	print d.getContent()

	self.loop.close()
     
        self.face.shutdown()
        self.face = None
    def __init__(self, prefix, maxCount=1):
        self.keyChain = KeyChain()
        self.prefix = Name(prefix)
        self.isDone = False

        # Initialize list for Data packet storage.
        # We'll treat the indices as equivalent to the sequence
        # number requested by Interests.
        self.data = []

        finalBlock = Name.Component.fromNumberWithMarker(maxCount - 1, 0x00)
        hourMilliseconds = 3600 * 1000

        # Pre-generate and sign all of Data we can serve.
        # We can also set the FinalBlockID in each packet
        # ahead of time because we know the entire sequence.

        for i in range(maxCount):
            dataName = Name(prefix).appendSegment(i)

            data = Data(dataName)
            data.setContent("Hello, " + dataName.toUri())
            data.getMetaInfo().setFinalBlockID(finalBlock)
            data.getMetaInfo().setFreshnessPeriod(hourMilliseconds)

            self.keyChain.sign(data, self.keyChain.getDefaultCertificateName())

            self.data.append(data)
Example #17
0
    def run(self, namespace, max_interests):
        """Starts listening for interest packets in the given namespace"""

        prefix = Name(namespace)
        self._max_interests = max_interests

        # Use the system default key chain and certificate name to sign commands.
        self._face.setCommandSigningInfo(
            self._key_chain, self._key_chain.getDefaultCertificateName())

        # Also use the default certificate name to sign Data packets.
        self._face.registerPrefix(prefix, self.onInterest,
                                  self.onRegisterFailed)

        dump("Registering prefix", prefix.toUri())

        print(f"Listening for interests under {namespace}...")
        print(f"Will satisfy {max_interests} before termination.")

        # Run the event loop forever. Use a short sleep to
        # prevent the Producer from using 100% of the CPU.
        while not self._is_done:
            self._face.processEvents()
            time.sleep(0.01)

        # shutdown this face - TODO: figure out why this can't be done in the self.shutdown() method
        self._face.shutdown()
Example #18
0
def main():
    face = Face("localhost")

    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(
      IdentityManager(identityStorage, privateKeyStorage), None)
    keyChain.setFace(face)

    # Initialize the storage.
    keyName = Name("/testname/DSK-reposerver")
    certificateName = keyName.getSubName(0, keyName.size() - 1).append(
      "KEY").append(keyName[-1]).append("ID-CERT").append("0")
    identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_PUBLIC_KEY_DER))
    privateKeyStorage.setKeyPairForKeyName(
      keyName, DEFAULT_PUBLIC_KEY_DER, DEFAULT_PRIVATE_KEY_DER)

    echo = RepoServer(keyChain, certificateName)
    prefix = Name("/ndn/ucla.edu/bms")
    dump("Register prefix", prefix.toUri())
    face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed)

    while True: 
        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 main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(
      IdentityManager(identityStorage, privateKeyStorage), None)
    keyChain.setFace(face)

    # 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)

    echo = Echo(keyChain, certificateName)
    prefix = Name("/testecho")
    dump("Register prefix", prefix.toUri())
    face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed)

    while echo._responseCount < 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()
Example #20
0
def main():
    # 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.
    #print("key1")
    #keyChain = KeyChain()
    #print("key2")
    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
                        NoVerifyPolicyManager())
    identityName = Name("TestProducer")
    certificateName = keyChain.createIdentityAndCertificate(identityName)
    keyChain.getIdentityManager().setDefaultIdentity(identityName)

    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    # Also use the default certificate name to sign data packets.
    ubicdn = UbiCDN(keyChain, certificateName)
    prefix = Name("/ubicdn/video")
    dump("Register prefix", prefix.toUri())
    face.registerPrefix(prefix, ubicdn.onInterest, ubicdn.onRegisterFailed)

    while 1:
        #while ubicdn._responseCount < 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()
Example #21
0
    def _createCertificateFromRequest(self, message):
        """
        Generate an IdentityCertificate from the public key information given.
        """
        # TODO: Verify the certificate was actually signed with the private key
        # matching the public key we are issuing a cert for!!

        keyComponents = message.command.keyName.components
        keyName = Name("/".join(keyComponents))

        self.log.debug("Key name: " + keyName.toUri())

        if not self._policyManager.getEnvironmentPrefix().match(keyName):
            # we do not issue certs for keys outside of our network
            return None

        keyDer = Blob(message.command.keyBits)
        keyType = message.command.keyType

        try:
            self._identityStorage.addKey(keyName, keyType, keyDer)
        except SecurityException:
            # assume this is due to already existing?
            pass

        certificate = self._identityManager.generateCertificateForKey(keyName)

        self._keyChain.sign(certificate, self.getDefaultCertificateName())
        # store it for later use + verification
        self._identityStorage.addCertificate(certificate)
        self._policyManager._certificateCache.insertCertificate(certificate)
        return certificate
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()
Example #23
0
    def _createCertificateFromRequest(self, message):
        """
        Generate an IdentityCertificate from the public key information given.
        """
        # TODO: Verify the certificate was actually signed with the private key
        # matching the public key we are issuing a cert for!!

        keyComponents = message.command.keyName.components
        keyName = Name("/".join(keyComponents))

        self.log.debug("Key name: " + keyName.toUri())

        if not self._policyManager.getEnvironmentPrefix().match(keyName):
            # we do not issue certs for keys outside of our network
            return None

        keyDer = Blob(message.command.keyBits)
        keyType = message.command.keyType

        try:
            self._identityStorage.addKey(keyName, keyType, keyDer)
        except SecurityException:
            # assume this is due to already existing?
            pass

        certificate = self._identityManager.generateCertificateForKey(keyName)

        self._keyChain.sign(certificate, self.getDefaultCertificateName())
        # store it for later use + verification
        self._identityStorage.addCertificate(certificate)
        return certificate
Example #24
0
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 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()
Example #26
0
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        print "received interest"
        initInterest = Name(interest.getName())
        print "interest name:", initInterest.toUri()
        #d = Data(interest.getName().getPrefix(prefix.size()+1))
        #self.excludeDevice = interest.getName().get(prefix.size())
        #initInterest = interest.getName()
        d = Data(interest.getName().append(self.deviceComponent))
        try:
            print "start to set data's content"

            currentString = ','.join(currentList)
            d.setContent("songList of " + self.device + ":" + currentString +
                         "\n")
            self.face.registerPrefix(self.changePrefix, self.onInterest,
                                     self.onRegisterFailed)

        except KeyboardInterrupt:
            print "key interrupt"
            sys.exit(1)
        except Exception as e:
            print e
            d.setContent("Bad command\n")
        finally:
            self.keychain.sign(d, self.certificateName)

        encodedData = d.wireEncode()
        transport.send(encodedData.toBuffer())
        print d.getName().toUri()
        print d.getContent()

        self.stop()
        '''print"remove register"
    def startConsuming(self):
        if self.consumeCatalog:
            contentName = Name(
                "/org/openmhealth/haitao/SAMPLE/fitness/physical_activity/time_location/catalog/20161024T213400"
            )
            catalogInterest = Interest(contentName)
            self.face.expressInterest(catalogInterest,
                                      self.onCatalogConsumeComplete,
                                      self.onCatalogConsumeFailed)
            # self.consumer.consume(contentName, self.onCatalogConsumeComplete, self.onConsumeFailed)
            print "Trying to consume: " + contentName.toUri()
        else:
            contentName = Name(
                "/org/openmhealth/haitao/SAMPLE/fitness/physical_activity/time_location/"
            )
            dataNum = 60
            baseZFill = 3
            basetimeString = "20160620T080"

            for i in range(0, dataNum):
                timeString = basetimeString + str(i).zfill(baseZFill)
                timeFloat = Schedule.fromIsoString(timeString)

                self.consumer.consume(
                    Name(contentName).append(timeString),
                    self.onConsumeComplete, self.onConsumeFailed)
                print "Trying to consume: " + Name(contentName).append(
                    timeString).toUri()
    def generateData(self, baseName):
        '''
           This appends the segment number to the data name, since repo-ng tends to expect it
        '''
        # just make up some data and return it
        ts = (time.time())
        segmentId = 0 # compatible with repo-ng test: may change to test segmented data

        versionStr = baseName.get(-1).toEscapedString()
        dataName = Name(baseName)
        dataName.appendSegment(segmentId)

        d = Data(dataName)
        content = "(" + str(ts) +  ") Data named " + dataName.toUri()
        d.setContent(content)
        d.getMetaInfo().setFinalBlockID(segmentId)
        d.getMetaInfo().setFreshnessPeriod(-1)
        if shouldSign:
            self.keychain.sign(d, self.certificateName)
        else:
            d.setSignature(self.fakeSignature)

        stats.insertDataForVersion(versionStr, {'publish_time':time.time()})
        logger.debug('Publishing: '+d.getName().toUri())
        return d
Example #29
0
def generateData(baseName):
    '''
       This appends the segment number to the data name
    '''
    # just make up some data and return it
    ts = (time.time())
    segmentId = 0 # compatible with repo-ng test: may change to test segmented data

    versionComponent = baseName.get(-1) # should have a ts
    dataName = Name(baseName)
    dataName.appendSegment(segmentId)

    d = Data(dataName)
    content = "(" + str(ts) +  ") Data named " + dataName.toUri()
    d.setContent(content)
    d.getMetaInfo().setFinalBlockID(segmentId)
    d.getMetaInfo().setFreshnessPeriod(-1)
    if shouldSign:
        keychain.sign(d, certName)
    else:
        d.setSignature(fakeSignature)

    if shouldCollectStats:
        info = getInfoForVersion(versionComponent.toEscapedString())
        if info is not None:
            info['publish_time'] = ts

    return d
Example #30
0
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    # 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 word to echo: ")
    else:
        word = input("Enter a word to echo: ")

    name = Name("/testecho")
    name.append(word)
    dump("Express name ", name.toUri())
    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()
Example #31
0
def registerPrefixForSeqReq():

    seqReqListener = SeqReqListener(keyChain,
                                    keyChain.getDefaultCertificateName())
    prefix = Name("/NIST/library/mainroom/repo1/proxy").append("initialSeq")
    dump("Registering time stamp request prefix", prefix.toUri())
    face.registerPrefix(prefix, seqReqListener.onInterest,
                        seqReqListener.onRegisterFailed)
Example #32
0
def decode_name(name) -> str:
    """
    Convert a Protobuf Name to uri
    """
    ret = Name()
    for comp in name.component:
        ret.append(comp)
    return ret.toUri()
Example #33
0
def registerPrefixForDeviceIDReq():

    deviceIDReqListener = DeviceIDReqListener(
        keyChain, keyChain.getDefaultCertificateName())
    prefix = Name("/NIST/library/mainroom/repo1/proxy").append("deviceIDList")
    dump("Registering device IDs request prefix", prefix.toUri())
    face.registerPrefix(prefix, deviceIDReqListener.onInterest,
                        deviceIDReqListener.onRegisterFailed)
Example #34
0
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("/localhost/repo1")
    repoDataPrefix = Name("/NIST/library/mainroom/ESP32ID001")

    nowMilliseconds = int(time.time() * 1000.0)
    fetchPrefix = Name(repoDataPrefix).append(
        Name.Component.fromNumber(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]

    def onFinished():
        dump("All data was inserted.")
        enabled[0] = False

    produceSegments = ProduceSegments(keyChain,
                                      keyChain.getDefaultCertificateName(),
                                      startBlockId, endBlockId, onFinished)
    dump("Register prefix", fetchPrefix.toUri())

    def onRegisterFailed(prefix):
        dump("Register failed for prefix", prefix.toUri())
        enabled[0] = False

    face.registerPrefix(fetchPrefix, produceSegments.onInterest,
                        onRegisterFailed)

    time.sleep(0.2)

    def onInsertStarted():
        dump("Insert started for", fetchPrefix.toUri())

    def onFailed():
        enabled[0] = False

    requestInsert(face, repoCommandPrefix, fetchPrefix, onInsertStarted,
                  onFailed)

    # Run until all the data is sent.
    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)

    face.shutdown()
Example #35
0
class Consumer(object):
    def __init__(self):

        Prefix1 = '/umobile/notification/push'
        self.configPrefix = Name(Prefix1)
        self.outstanding = dict()
        self.isDone = False
        self.keyChain = KeyChain()

        self.face = Face("127.0.0.1")

    def run(self):
        try:

            self.face.setCommandSigningInfo(self.keyChain, \
                                            self.keyChain.getDefaultCertificateName())
            self.face.registerPrefix(self.configPrefix, self.onInterest, self.onRegisterFailed)
            print "Registering listening prefix : " + self.configPrefix.toUri()

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

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

    def onInterest(self, prefix, interest, face, interestFilterId, filter):

        interestName = interest.getName()
        ### Extract Data content from Interest name
        interest_name_components = interestName.toUri().split("/")
        Data_content = interest_name_components[interest_name_components.index("push") + 1]
        print 'Received Data: %s' %Data_content
        data = Data(interestName)
        data.setContent("ACK")
        hourMilliseconds = 600 * 1000
        data.getMetaInfo().setFreshnessPeriod(hourMilliseconds)
        self.keyChain.sign(data, self.keyChain.getDefaultCertificateName())
        face.send(data.wireEncode().toBuffer())
        print "Sending ACK"


    def _onTimeout(self, interest):
        name = interest.getName()
        uri = name.toUri()

        print "TIMEOUT #%d: %s" % (self.outstanding[uri], uri)
        self.outstanding[uri] += 1

        if self.outstanding[uri] <= 3:
            self._sendNextInterest(name)
        else:
            self.isDone = True

    def onRegisterFailed(self, prefix):
        print "Register failed for prefix", prefix.toUri()
        self.isDone = True
Example #36
0
    def sendData(self, prefix, interest, face, registeredPrefixId, content):      #onInterest

        #transport.send(encodedData.toBuffer())
	#print(prefix)
        # Publish segments
        dataSize = len(content)
        print("Dat size: ",dataSize)
        segmentBegin = 0
        segmentNo = 0
        print "Start"
        while segmentBegin < dataSize: 
            segmentEnd = segmentBegin + 2000 #Common.MAX_NDN_PACKET_SIZE

            if segmentEnd > dataSize:
                segmentEnd = dataSize

            # Make and sign a Data packet.
	    print("Prefix: ")
	    print(prefix)
            if not "%" in str(prefix)[-7:]:
                segmentName = prefix
		#print("NO % in name: ", segmentName)
                segmentName.appendSegment(segmentNo)
            else:
                segmentName = str(prefix)[:-1]
                #print("% in name: ",segmentName)
		segmentName += str(segmentNo)
		segmentName = Name(segmentName)
            print("Segment Name: ")
	    print(segmentName)

            print("Segment Name appended: ", segmentName)

            print "Segmenting data from %d to %d" % (segmentBegin, segmentEnd)
            print("COntent: ")
            print(content[segmentBegin:segmentEnd])

            data = Data(segmentName)
            data.setContent(content[segmentBegin:segmentEnd])
            data.getMetaInfo().setFreshnessPeriod(2000)
            self._keyChain.sign(data, self._certificateName)

            if segmentEnd >= dataSize:
              print("yes")
              data.getMetaInfo().setFinalBlockId(segmentName[-1])

            #encodedData = data.wireEncode()

            segmentBegin = segmentEnd

            print "Sending data " + segmentName.toUri()
            #transport.send(encodedData.toBuffer())
            face.putData(data)

            segmentNo += 1
            time.sleep(0.5)
        print "Finish"
Example #37
0
def download_segment_ndn(segment_url, dash_folder):
    """ Module to download the segment """
    print 'Entered download segment ndn'
    face = Face("server.simpleNDN.ch-geni-net.geni.case.edu")
    counter = Counter()

    try:
        name = Name(segment_url)
        dump("Express name ", name.toUri())
        face.expressInterest(name, counter.onData, counter.onTimeout)
        while counter._callbackCount < 1:
            face.processEvents()
        # Try to fetch using a known name.
        name = Name(segment_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()

    parsed_uri = urlparse.urlparse(segment_url)
    segment_path = '{uri.path}'.format(uri=parsed_uri)
    while segment_path.startswith('/'):
        segment_path = segment_path[1:]
    segment_filename = os.path.join(dash_folder,
                                    os.path.basename(segment_path))
    make_sure_path_exists(os.path.dirname(segment_filename))
    segment_file_handle = open(segment_filename, 'wb')
    segment_size = 0
    while True:
        segment_data = Content
        segment_size += len(segment_data)
        segment_file_handle.write(segment_data)
        if len(segment_data) < DOWNLOAD_CHUNK:
            break
    segment_file_handle.close()
    return segment_size, segment_filename
Example #38
0
def main():
    """
    Call startRepoWatch and register a prefix so that SendSegments will answer
    interests from the repo to send data packets for the watched prefix.  When
    all the data is sent (or an error), call stopRepoWatch. 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)
    watchPrefix = Name(repoDataPrefix).append("testwatch").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 start the repo watch at the same time.
    enabled = [True]

    def onFinishedSending():
        stopRepoWatchAndQuit(face, repoCommandPrefix, watchPrefix, enabled)

    sendSegments = SendSegments(keyChain, keyChain.getDefaultCertificateName(),
                                onFinishedSending)

    def onRegisterFailed(prefix):
        dump("Register failed for prefix", prefix.toUri())
        enabled[0] = False

    dump("Register prefix", watchPrefix.toUri())
    face.registerPrefix(watchPrefix, sendSegments.onInterest, onRegisterFailed)

    def onRepoWatchStarted():
        dump("Watch started for", watchPrefix.toUri())

    def onStartFailed():
        dump("startRepoWatch failed.")
        stopRepoWatchAndQuit(face, repoCommandPrefix, watchPrefix, enabled)

    startRepoWatch(face, repoCommandPrefix, watchPrefix, onRepoWatchStarted,
                   onStartFailed)

    # Run until someone sets enabled[0] = False.
    enabled[0] = True
    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)

    face.shutdown()
Example #39
0
def listenForOnboardingRequests():

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

    while True:
        face.processEvents()
        time.sleep(0.01)
Example #40
0
 def leftKey(event):
     global currentSlideName
     allVersions = newspaper.getChildComponents()
     currentVersion = currentSlideName[-1]
     selected = allVersions[0]
     for c in allVersions:
         print(str(c.toVersion()))
         if c.toVersion() == currentVersion.toVersion():
             break
         selected = c
     currentSlideName = Name(newspaper.getName()).append(selected)
     displayImage(newspaper.getChild(selected).content.toRawStr(), currentSlideName.toUri())
Example #41
0
    def test_02_device_methods(self):
        #create device
        prefixStr = '/home/sensor/LED/1'
        name = Name(prefixStr)
        profile = DeviceProfile(prefix = name)
        location = 'living_room'
        profile.setLocation(location)
        serviceProfileList  = ['/standard/sensor/simple-camera-control/v0', '/standard/sensor/simple-motionsensor-control/v0']
        profile.setServiceProfile(serviceProfileList)
        keyContent = 'this is key content'
        seedName = 'led1'
        seed =  HMACKey( 0, 0 ,keyContent, seedName)
        configurationToken =  HMACKey(0, 0, keyContent) 
  
        commandName1 = 'turn_on'
        commandName2 = 'turn_off' 
        commandList =  [commandName1, commandName2]
        result = self.manager.createDevice(profile, seed, configurationToken, commandList)
        self.assertTrue(result, 'fail to create device')
       
        #getDeviceProfile()
        deviceProfile = self.manager.getDeviceProfile(name)
        self.assertTrue(deviceProfile.getLocation() == location, 'wrong location in device profile ')
        self.assertTrue(deviceProfile.getServiceProfileList() == serviceProfileList, 'wrong service profile list in device profile' )
     
        #getSeed()
        seed = self.manager.getSeed(name)
        self.assertTrue(seed.getName() == seedName, 'wrong seed name')
        
        #getConfigurationToken()
        configurationToken = self.manager.getConfigurationToken(name)
        self.assertTrue(configurationToken.getKey()== keyContent, 'wrong configration token')
       
        #getCommandToken()
        commandToken1 = self.manager.getCommandToken(name, commandName1)
        commandToken2 = self.manager.getCommandToken(name, commandName2)
        commandTokenName1 = name.toUri()+"/"+ commandName1 +"/token/0"
        commandTokenName2 = name.toUri()+"/"+ commandName2 +"/token/0"

        self.assertTrue(commandToken1.getName() == commandTokenName1, 'wrong commandToken')
        self.assertTrue(commandToken2.getName() == commandTokenName2, 'wrong commandToken')
 
        #getCommandsOfDevice()
        commandNameList = self.manager.getCommandsOfDevice(name)
        self.assertTrue(commandName1 in commandNameList, 'command:' + commandName1 + ' not found')
        self.assertTrue(commandName2 in commandNameList, 'command:' + commandName2 + ' not found')

        #getServiceProfilesOfDevice()
        serviceProfileListReturned = self.manager.getServiceProfilesOfDevice(name)
        self.assertTrue(serviceProfileList[0] in serviceProfileListReturned, 'service profile:' + serviceProfileList[0] + ' not found')
        self.assertTrue(serviceProfileList[1] in serviceProfileListReturned, 'service profile:' + serviceProfileList[1] + ' not found')
Example #42
0
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]
    def onFinished():
        dump("All data was inserted.")
        enabled[0] = False
    produceSegments = ProduceSegments(
      keyChain, keyChain.getDefaultCertificateName(), startBlockId, endBlockId,
      onFinished)
    dump("Register prefix", fetchPrefix.toUri())
    def onRegisterFailed(prefix):
        dump("Register failed for prefix", prefix.toUri())
        enabled[0] = False
    face.registerPrefix(
      fetchPrefix, produceSegments.onInterest, onRegisterFailed)

    def onInsertStarted():
        dump("Insert started for", fetchPrefix.toUri())
    def onFailed():
        enabled[0] = False
    requestInsert(
      face, repoCommandPrefix, fetchPrefix, onInsertStarted, onFailed,
      startBlockId, endBlockId)

    # Run until all the data is sent.
    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)

    face.shutdown()
Example #43
0
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
	print "received interest"
        initInterest = Name(interest.getName())
        print "interest name:",initInterest.toUri()
        #d = Data(interest.getName().getPrefix(prefix.size()+1))
        #self.excludeDevice = interest.getName().get(prefix.size())
	#initInterest = interest.getName()
	d = Data(interest.getName().append(self.deviceComponent))
	
		  
        try:
	    if(initInterest == self.prefix):
	    
		print "start to set data's content"
                
		currentString = ','.join(currentList)
		d.setContent("songList of " +self.device+":"+currentString+ "\n")
		
		
            else:
		self.excludeDevice = initInterest.get(prefix.size())
		print "excludeDevice",self.excludeDevice.toEscapedString()
		if(self.excludeDevice != self.deviceComponent):
			print "start to set data's content"
                
			currentString = ','.join(currentList)
			d.setContent("songList of " +self.device+":"+currentString+ "\n")
		else:

			print"remove register"
                	self.face.removeRegisteredPrefix(registeredPrefixId)
                	time.sleep(30)
                	#sleep 30s which means user cannot update the song list twice within 1 minutes
			print"register again"
                	self.face.registerPrefix(self.prefix, self.onInterest, self.onRegisterFailed)
	    

	except KeyboardInterrupt:
		print "key interrupt"
		sys.exit(1)
	except Exception as e:
		print e
		d.setContent("Bad command\n")
	finally:
		self.keychain.sign(d,self.certificateName)

	encodedData = d.wireEncode()
	transport.send(encodedData.toBuffer())
	print d.getName().toUri()
	print d.getContent()
Example #44
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")
Example #45
0
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        print "received interest"
        initInterest = Name(interest.getName())
        print "interest name:", initInterest.toUri()
        #d = Data(interest.getName().getPrefix(prefix.size()+1))
        #self.excludeDevice = interest.getName().get(prefix.size())
        #initInterest = interest.getName()
        d = Data(interest.getName().append(self.deviceComponent))

        try:
            if (initInterest == self.prefix):

                print "start to set data's content"

                currentString = ','.join(currentList)
                d.setContent("songList of " + self.device + ":" +
                             currentString + "\n")

            else:
                self.excludeDevice = initInterest.get(prefix.size())
                print "excludeDevice", self.excludeDevice.toEscapedString()
                if (self.excludeDevice != self.deviceComponent):
                    print "start to set data's content"

                    currentString = ','.join(currentList)
                    d.setContent("songList of " + self.device + ":" +
                                 currentString + "\n")
                else:

                    print "remove register"
                    self.face.removeRegisteredPrefix(registeredPrefixId)
                    time.sleep(30)
                    #sleep 30s which means user cannot update the song list twice within 1 minutes
                    print "register again"
                    self.face.registerPrefix(self.prefix, self.onInterest,
                                             self.onRegisterFailed)

        except KeyboardInterrupt:
            print "key interrupt"
            sys.exit(1)
        except Exception as e:
            print e
            d.setContent("Bad command\n")
        finally:
            self.keychain.sign(d, self.certificateName)

        encodedData = d.wireEncode()
        transport.send(encodedData.toBuffer())
        print d.getName().toUri()
        print d.getContent()
Example #46
0
    async def face_event(self):
        last_seq = -1
        retry_time = 3000
        retry_count_limit = 60000 // retry_time
        retry_count = 0
        while self.running and self.face:
            name = Name("/localhost/nfd/faces/events")
            face_interest = Interest()
            if last_seq >= 0:
                name.appendSequenceNumber(last_seq + 1)
                face_interest.canBePrefix = False
            else:
                face_interest.mustBeFresh = True
                face_interest.canBePrefix = True
            logging.info("Face event notification stream %s", name.toUri())
            face_interest.name = name
            # face_interest.interestLifetimeMilliseconds = 60000
            face_interest.interestLifetimeMilliseconds = retry_time

            ret = await fetch_data_packet(self.face, face_interest)
            timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

            if isinstance(ret, Data):
                retry_count = 0
                last_seq = ret.name[-1].toSequenceNumber()
                face_event = FaceEventNotificationMessage()
                try:
                    ProtobufTlv.decode(face_event, ret.content)

                    dic = self.face_event_to_dict(face_event.face_event_notification)
                    dic['seq'] = str(last_seq)
                    dic['time'] = timestamp
                    self.emit('face event', dic)
                    self.event_list.append(dic)
                except RuntimeError as exc:
                    logging.fatal('Decode failed %s', exc)
                    last_seq = -1
            elif ret is None:
                if retry_count >= retry_count_limit:
                    logging.info("No response: face event")
                    last_seq = -1
                    retry_count = 0
                else:
                    retry_count += 1
            else:
                logging.info("NFD is not running: start reconnection")
                self.start_reconnection()
                return

            await asyncio.sleep(0.1)
Example #47
0
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        initInterest = Name(interest.getName())
        print "interest name:",initInterest.toUri()
	d = Data(interest.getName().append(self.deviceComponent))
	
		  
        try:
	    if(initInterest == self.listPrefix):
	    
		print "initial db,start to set data's content"
                
		currentString = ','.join(currentList)
		d.setContent(currentString)
		encodedData = d.wireEncode()
		transport.send(encodedData.toBuffer())
		print d.getName().toUri()
		print d.getContent()
		
		
		
            else:
		self.excludeDevice = initInterest.get(self.listPrefix.size())
		excDevice = self.excludeDevice.toEscapedString()
		if(excDevice != str("exc")+self.device):
			print "not init db,start to set data's content"
                
			currentString = ','.join(currentList)
			d.setContent(currentString)
			encodedData = d.wireEncode()
			transport.send(encodedData.toBuffer())
			print d.getName().toUri()
			print d.getContent()
			
		else:
			
			print"controller has exclude me, I have to remove register!!!!!!!"
                	self.face.removeRegisteredPrefix(registeredPrefixId)
			print"register again"
                	self.face.registerPrefix(self.listPrefix,self.onInterest,self.onRegisterFailed)
    

	except KeyboardInterrupt:
		print "key interrupt"
		sys.exit(1)
	except Exception as e:
		print e
		d.setContent("Bad command\n")
	finally:
		self.keychain.sign(d,self.certificateName)
Example #48
0
    def test_typed_name_component(self):
        otherTypeCode = 99
        uri = "/ndn/" + str(otherTypeCode) + "=value"
        name = Name()
        name.append("ndn").append("value", ComponentType.OTHER_CODE, otherTypeCode)
        self.assertEqual(uri, name.toUri())

        nameFromUri = Name(uri)
        self.assertEqual("value", str(nameFromUri.get(1).getValue()))
        self.assertEqual(otherTypeCode, nameFromUri.get(1).getOtherTypeCode())

        decodedName = Name()
        decodedName.wireDecode(name.wireEncode())
        self.assertEqual("value", str(decodedName.get(1).getValue()))
        self.assertEqual(otherTypeCode, decodedName.get(1).getOtherTypeCode())
def main():
    loop = asyncio.get_event_loop()
    face = ThreadsafeFace(loop, "aleph.ndn.ucla.edu")

    counter = Counter()
    face.stopWhen(lambda: counter._callbackCount >= 1)

    name1 = Name("/") 
    dump("Express name ", name1.toUri())
    # This call to exressIinterest is thread safe because face is a ThreadsafeFace.
    face.expressInterest(name1, counter.onData, counter.onTimeout)

    # Run until stopWhen stops the loop.
    loop.run_forever()
    face.shutdown()
    def test_published_kdks(self):
        for user in self._fixture._userIdentities:
            kdkName = Name("/access/policy/identity/NAC/dataset/KDK")
            kdkName.append(
              self._fixture._nacIdentity.getDefaultKey().getName().get(-1)).append(
              "ENCRYPTED-BY").append(
              user.getDefaultKey().getName())

            self._fixture._face.receive(
              Interest(kdkName).setCanBePrefix(True).setMustBeFresh(True))

            self.assertTrue(
              self._fixture._face._sentData[0].getName().equals(kdkName),
              "Sent Data does not have the KDK name " + kdkName.toUri())
            self._fixture._face._sentData = []
Example #51
0
def main():
    """
    Call startRepoWatch and register a prefix so that SendSegments will answer
    interests from the repo to send data packets for the watched prefix.  When
    all the data is sent (or an error), call stopRepoWatch. 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)
    watchPrefix = Name(repoDataPrefix).append("testwatch").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 start the repo watch at the same time.
    enabled = [True]
    def onFinishedSending():
        stopRepoWatchAndQuit(face, repoCommandPrefix, watchPrefix, enabled)
    sendSegments = SendSegments(
      keyChain, keyChain.getDefaultCertificateName(), onFinishedSending)
    def onRegisterFailed(prefix):
        dump("Register failed for prefix", prefix.toUri())
        enabled[0] = False
    dump("Register prefix", watchPrefix.toUri())
    face.registerPrefix(watchPrefix, sendSegments.onInterest, onRegisterFailed)

    def onRepoWatchStarted():
        dump("Watch started for", watchPrefix.toUri())
    def onStartFailed():
        dump("startRepoWatch failed.")
        stopRepoWatchAndQuit(face, repoCommandPrefix, watchPrefix, enabled)
    startRepoWatch(
      face, repoCommandPrefix, watchPrefix, onRepoWatchStarted, onStartFailed)

    # Run until someone sets enabled[0] = False.
    enabled[0] = True
    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)

    face.shutdown()
Example #52
0
    def onLightingCommand(self, prefix, interest, transport, prefixId):
        #print datetime.datetime.now()
        self.receiveFile.write('{0:f}'.format(self.unix_time_now()) + '\n')
        interestName = Name(interest.getName())
        #interstname: /ndn/ucla.edu/sculptures/ai_bus/lights/setRGB/%83%0D%84%0B%87%09%89%01%04%8A%01%01%8B%01%01
        #d: <pyndn.data.Data object at 0xb64825d0>
        print "interstname", interestName.toUri()
        d = Data(interest.getName())
        # get the command parameters from the name
        try:
            commandComponent = interest.getName().get(prefix.size())
            #print commandComponent.toEscapedString():setRGB
            #print "prefix ",prefix.toUri():/ndn/ucla.edu/sculpture/ai_bus/lights
            #print "get name",interest.getName().toUri()
            commandParams = interest.getName().get(prefix.size()+1)
            #print "commandParams ",commandParams:%83%0D%84%0B%87%09%89%01%04%8A%01%01%8B%01%01

            lightingCommand = LightCommandMessage()
            ProtobufTlv.decode(lightingCommand, commandParams.getValue())
            #self.log.info("Command: " + commandComponent.toEscapedString())
            requestedColor = lightingCommand.command.pattern.colors[0] 
            colorStr = str((requestedColor.r, requestedColor.g, requestedColor.b))
            #self.log.info("Requested color: " + colorStr)
            self.setPayloadColor(0, requestedColor)
            
            self.lightState = not self.lightState
            if self.lightState:
                print "Off"
            else:
                print "On"
            
            #print requestedColor
            
            self.sendLightPayload(1)
            d.setContent("Gotcha: " + colorStr+ "\n")
        except KeyboardInterrupt:
            print "key interrupt"
            sys.exit(1)
        except Exception as e:
            print e
            d.setContent("Bad command\n")
        finally:
            d.getMetaInfo().setFinalBlockID(0)
            self.signData(d)

        encodedData = d.wireEncode()
        transport.send(encodedData.toBuffer())
Example #53
0
    def run(self, namespace):

        # The default Face will connect using a Unix socket
        face = Face()
        prefix = Name(namespace)

        # Use the system default key chain and certificate name to sign commands.
        face.setCommandSigningInfo(self.keyChain, self.keyChain.getDefaultCertificateName())

        # Also use the default certificate name to sign data packets.
        face.registerPrefix(prefix, self.onInterest, self.onRegisterFailed)

        print "Registering prefix", prefix.toUri()

        while True:
            face.processEvents()
            time.sleep(0.01)
    def startConsuming(self):
        if self.consumeCatalog:
            contentName = Name("/org/openmhealth/zhehao/SAMPLE/fitness/physical_activity/time_location/catalog/20160620T080000")
            self.consumer.consume(contentName, self.onCatalogConsumeComplete, self.onConsumeFailed)
            print "Trying to consume: " + contentName.toUri()
        else:
            contentName = Name("/org/openmhealth/zhehao/SAMPLE/fitness/physical_activity/time_location/")
            dataNum = 60
            baseZFill = 3
            basetimeString = "20160620T080"

            for i in range(0, dataNum):
                timeString = basetimeString + str(i).zfill(baseZFill)
                timeFloat = Schedule.fromIsoString(timeString)

                self.consumer.consume(Name(contentName).append(timeString), self.onConsumeComplete, self.onConsumeFailed)
                print "Trying to consume: " + Name(contentName).append(timeString).toUri()
Example #55
0
def main():
    face = Face("localhost")
    
    counter = Counter()

    ignored, name = argv
    name = "/ndn/ucla.edu/bms/" + name
    name1 = Name(name)
    dump("Express name ", name1.toUri())
    face.expressInterest(name1, 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 createInsertInterest(fullName):
    # we have to do the versioning when we poke the repo
    interestName = Name(fullName)
    logger.debug('Creating insert interest for: '+interestName.toUri())
    
    insertionName = Name("/repotest/repo/insert")
    commandParams = RepoCommandParameterMessage()

    for i in range(interestName.size()):
        commandParams.repo_command_parameter.name.component.append(interestName.get(i).toEscapedString())

    commandParams.repo_command_parameter.start_block_id = 0
    commandParams.repo_command_parameter.end_block_id = 0

    commandName = insertionName.append(ProtobufTlv.encode(commandParams))
    interest = Interest(commandName)

    return interest
Example #57
0
class Consumer(object):
    '''Sends Interest, listens for data'''

    def __init__(self, name):
        self.name = Name(name)
        self.face = Face()
        self.isDone = False


    def run(self):
        try:
            interest = Interest(self.name)
            uri = self.name.toUri()

            interest.setInterestLifetimeMilliseconds(4000)
            interest.setMustBeFresh(True)

            self.face.expressInterest(interest, self._onData, self._onTimeout)

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

            print "Sent Interest for %s" % uri

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


    def _onData(self, interest, data):
        payload = data.getContent()
        name = data.getName()

        print "Received data: %s\n" % payload.toRawStr()
        self.isDone = True


    def _onTimeout(self, interest):
        name = interest.getName()
        uri = name.toUri()

        print "TIMEOUT ", uri
        self.isDone = True