Exemple #1
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)
Exemple #2
0
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        """Called when an interest for the specified name is recieved"""

        # keep track of when first interest was recieved
        self._initial_time['download_time'] = time.time()

        # set data to a byte array of a specified size
        interestName = interest.getName()
        data = Data(interestName)
        data.setContent(self._byte_array)

        # sign and send data
        data.getMetaInfo().setFreshnessPeriod(3600 * 1000)
        self._key_chain.sign(data, self._key_chain.getDefaultCertificateName())
        transport.send(data.wireEncode().toBuffer())

        # print additional information if verobse flag is set
        if self._verbose:
            dump("Replied to:", interestName.toUri())

        # increment appropriate variables
        self._interests_recieved += 1
        self._interests_satisfied += 1
        self._num_interests += 1

        # stop loop if the required number of interests have been satisified
        if self._num_interests >= self._max_interests:
            self.shutdown()
Exemple #3
0
    def onPlayingCommand(self, prefix, interest, transport, prefixId):

        interestName = Name(interest.getName())
        commandComponent = interest.getName().get(self.prefix.size())
        if commandComponent == Name.Component("stop"):
            pass
        if commandComponent == Name.Component("play"):
            pass
        else:
            songName = commandComponent.toEscapedString()

        songList = []
        songList = songName.split('%2C')

        for i in songList:
            fmusic = i + str("-music.mp3")
            print "started getting music file", i

            g = GetFile(self._repoCommandPrefix, i, self._face, self.getOnset,
                        i)

            g.oStream = open(fmusic, 'wb')
            g.start()

            #self._getFiles.append(g)

        d = Data(interest.getName())
        d.setContent("start to play: " + songName + "\n")
        encodedData = d.wireEncode()
        transport.send(encodedData.toBuffer())
Exemple #4
0
    def onPlayingCommand(self, prefix, interest, transport, prefixId):
	print "receive interest"
        interestName = Name(interest.getName())
        commandComponent = interest.getName().get(self.prefix.size())
        if commandComponent == Name.Component("stop"):
            pass
        if commandComponent == Name.Component("play"):
            pass
        else:
            songName = commandComponent.toEscapedString()
	    print songName
	    songList = []
	    songList = songName.split('%2C')
	    print "songlist and its len",songList,len(songList)
	    for i in songList:
		self.song = i
            	fmusic = i+str("-music.mp3") 
		self.ftxt = i + str("-os.txt")
		self.ffreq = i + str("-freq.txt")
		print "FMUSIC:",fmusic 
		  
	    	self.thread = threading.Thread(target = self.mp.play_music, args = (fmusic,songList,self.q,))
	    	self.thread.daemon = True
            	g = GetFile(self._repoCommandPrefix, i, self._face, self.getOnset)
		#g = GetFile(self._repoCommandPrefix, ftxt, self._face, self.lightFunction)
            	g.oStream = open(fmusic,'wb')
            	g.start()
	   
		
	
	d = Data(interest.getName())
	d.setContent("start to play: " + songName + "\n")
	encodedData = d.wireEncode()
	transport.send(encodedData.toBuffer())	
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        interestName = interest.getName()

        data = Data(interestName)
        dt = datetime.now()

        if (interestName.toUri() == "/vanet-ndn/iklanpertama"):
            data.setContent(
                "\nLakukan Pengisian Pulsa Telkomsel sekarang juga \nDapatkan pulsa 5000 dan kelipatan untuk setiap pembelian pulsa 10000 dan kelipatannya\n"
            )  #bagian ini bisa diganti dengan informasi dari sensor
        elif (interestName.toUri() == "/vanet-ndn/iklankedua"):
            data.setContent(
                "\nLakukan Pengisian Kuota Indosat sekarang juga! \nDapatkan kemudahan dalam berinternet digenggamanmu\n"
            )  #bagian ini bisa diganti dengan informasi dari sensor
        elif (interestName.toUri() == "/vanet-ndn/iklanketiga"):
            data.setContent(
                "\nIngin memiliki Smartphone baru? \nDapatkan smartphone impian mu dengan XL\nCek xl.co.id untuk penawaran menarik\n"
            )  #bagian ini bisa diganti dengan informasi dari sensor
        else:
            data.setContent(
                "\nJarak kendaraan: \n"
            )  #bagian ini bisa diganti dengan informasi dari sensor

        hourMilliseconds = 10  #3600 * 1000 #1000 jam
        data.getMetaInfo().setFreshnessPeriod(hourMilliseconds)

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

        transport.send(data.wireEncode().toBuffer())

        print("Replied to: %s at %s" % (interestName.toUri(), dt))
        #print("==================================================================\n")
        pass
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        interestName = interest.getName()
        interestParams = str(interest.getApplicationParameters())
        addPrefixes = interestParams.split("|")
        interestParams = interestParams + "|" + get_device_ip()
        # For each Prefix recieved save it in local array
        # Add route for that prefix from User to gateway router
        for i in range(0, len(addPrefixes)):
            print addPrefixes[i]
            self.prefixesList.append(str(addPrefixes[i]))
            os.system("nfdc route add " + str(addPrefixes[i]) + " " +
                      self.gatewayFace)

        # Send prefixesList to gateway router
        subprocess.call([
            "python", "interestSender.py", "-u /ndnchat/register",
            "-p " + interestParams
        ])

        data = Data(interestName)
        data.setContent("Register Successful")

        hourMilliseconds = 3600 * 1000
        data.getMetaInfo().setFreshnessPeriod(hourMilliseconds)

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

        transport.send(data.wireEncode().toBuffer())

        print "Sent advertisement to gateway router"
Exemple #7
0
    def onGetAllData(self, producedDataName, outerDataName):
        maxLng = -1000
        minLng = 1000
        maxLat = -1000
        minLat = 1000
        for item in self._tasks[producedDataName]["dataset"]:
            dataObject = json.loads(str(item))
            if dataObject["lat"] > maxLat:
                maxLat = dataObject["lat"]
            if dataObject["lat"] < minLat:
                minLat = dataObject["lat"]
            if dataObject["lng"] > maxLng:
                maxLng = dataObject["lng"]
            if dataObject["lng"] < minLng:
                minLng = dataObject["lng"]

        if not self._encryptResult:
            innerData = Data(Name(str(producedDataName)))
            innerData.setContent(json.dumps({"minLat": minLat, "maxLat": maxLat, "minLng": minLng, "maxLng": maxLng}))
            #self.keyChain.sign(innerData)

            outerData = Data(Name(str(outerDataName)))
            outerData.setContent(innerData.wireEncode())
            #self.keyChain.sign(outerData)

            self.memoryContentCache.add(outerData)
            self.initiateContentStoreInsertion("/ndn/edu/ucla/remap/ndnfit/repo", outerData)
            print "Calculation completed, put data to repo"
        else:
            print "Encrypt result is not implemented"
Exemple #8
0
    def onLightingCommand(self, prefix, interest, transport, prefixId):
        interestName = Name(interest.getName())
        #d = Data(interest.getName().getPrefix(prefix.size()+1))
        d = Data(interest.getName())
        # get the command parameters from the name
        try:
            commandComponent = interest.getName().get(prefix.size())
            commandParams = interest.getName().get(prefix.size()+1)

            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.sendLightPayload(1)
            d.setContent("Gotcha: " + colorStr+ "\n")
        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())
	def onPlayingCommand(self, prefix, interest, transport, prefixId):
		
		interestName = Name(interest.getName())
		commandComponent = interest.getName().get(self.prefix.size())
		if commandComponent == Name.Component("stop"):
			pass
		if commandComponent == Name.Component("play"):
			pass
		else:
			songName = commandComponent.toEscapedString()
	    
		songList = []
		songList = songName.split('%2C')
	    
		for i in songList:
			fmusic = i + str("-music.mp3") 
			print "started getting music file", i
			
			g = GetFile(self._repoCommandPrefix, i, self._face, self.getOnset, i)
			
			g.oStream = open(fmusic,'wb')
			g.start()
			
			#self._getFiles.append(g)
			
		d = Data(interest.getName())
		d.setContent("start to play: " + songName + "\n")
		encodedData = d.wireEncode()
		transport.send(encodedData.toBuffer())	
Exemple #10
0
    def publishData(self):
        timestamp = time.time()
        info = {''}
        if self._pir == None:
            cpu_use = ps.cpu_percent()
            users = [u.name for u in ps.users()]
            nProcesses = len(ps.pids())
            memUse = ps.virtual_memory().percent
            swapUse = ps.swap_memory().percent

            info = {'count': self._count, 'cpu_usage':cpu_use, 'users':users, 'processes':nProcesses,
                    'memory_usage':memUse, 'swap_usage':swapUse}
        else:
            info = {'count': self._count, 'pir_bool': self._pir.read()}
        self._count += 1
        
        dataOut = Data(Name(self._dataPrefix).appendVersion(int(timestamp)))
        dataOut.setContent(json.dumps(info))
        dataOut.getMetaInfo().setFreshnessPeriod(10000)
        self.signData(dataOut)

        #self._dataCache.add(dataOut)
        # instead of adding data to content cache, we put data to nfd anyway
        self.send(dataOut.wireEncode().buf())
        print('data name: ' + dataOut.getName().toUri() + '; content: ' + str(info))

        # repeat every 1 seconds
        self.loop.call_later(1, self.publishData)
Exemple #11
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"
Exemple #12
0
    def _onConfigurationReceived(self, prefix, interest, transport, prefixId):
        # the interest we get here is signed by HMAC, let's verify it
        self.tempPrefixId = prefixId # didn't get it from register because of the event loop
        interestName = interest.getName()
        replyData = Data(interestName)
        if len(interestName) == len(prefix):
            # this is a discovery request. Check the exclude to see if we should
            # return our serial
            serial = self.getSerial()
            serialComponent = Name.Component(serial)
            if not interest.getExclude().matches(serialComponent):
                replyData.setContent(serial)
                self.sendData(replyData, transport, False) # no point in signing
        elif (self._hmacHandler.verifyInterest(interest)):
            # we have a match! decode the network parameters
            configComponent = interest.getName()[len(prefix)+1]
            replyData.setContent('200')
            self._hmacHandler.signData(replyData, keyName=self.prefix)
            transport.send(replyData.wireEncode().buf())

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

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

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

            self._configureIdentity = Name(networkPrefix).append(self.deviceSuffix) 
            self._sendCertificateRequest(self._configureIdentity)
Exemple #13
0
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        filepath = 'cpu.txt'
        counter = 0.0
        avg = 0
        fp = open(filepath)
        line = fp.readline()
        cnt = 0
        while line:
            conv_int = float(line)
            line = fp.readline()
            #print("Line {}: {}".format(cnt, line.strip()))
            counter = counter + conv_int
            cnt += 1
        total = (cnt)
        #print (total)
        avg = (counter) / total
        #print (avg)
        interestName = interest.getName()

        data = Data(interestName)
        data.setContent("CPU avg:" + str(avg))

        hourMilliseconds = 3600 * 1000
        data.getMetaInfo().setFreshnessPeriod(hourMilliseconds)

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

        transport.send(data.wireEncode().toBuffer())

        print "Replied to: %s" % interestName.toUri()
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())
    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())
Exemple #16
0
    def _onConfigurationReceived(self, prefix, interest, transport, prefixId):
        # the interest we get here is signed by HMAC, let's verify it
        self.tempPrefixId = prefixId # didn't get it from register because of the event loop
        dataName = Name(interest.getName())
        replyData = Data(dataName)
        if (self._hmacHandler.verifyInterest(interest)):
            # we have a match! decode the controller's name
            configComponent = interest.getName().get(prefix.size())
            replyData.setContent('200')
            self._hmacHandler.signData(replyData, keyName=self.prefix)
            transport.send(replyData.wireEncode().buf())

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

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

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

            self._configureIdentity = Name(networkPrefix).append(self.deviceSuffix) 
            self._sendCertificateRequest(self._configureIdentity)
Exemple #17
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
Exemple #18
0
 def onInterest(prefix, interest, transport, prefixID):
     interestCallbackCount[0] += 1
     data = Data(interest.getName())
     data.setContent("SUCCESS")
     self.keyChain.sign(data, self.keyChain.getDefaultCertificateName())
     encodedData = data.wireEncode()
     transport.send(encodedData.toBuffer())
Exemple #19
0
    def wrap_content(self, name, content, key=None, key_locator=None):
        """
        @param name - name of the data
        @param content - data to be wrapped
        @param key - key used to sign the data
        @return the content object created
        wraps the given name and content into a content object
        """
        co = Data(Name(name))
        co.setContent(content)
        co.getMetaInfo().setFreshnessPeriod(5000)
        co.getMetaInfo().setFinalBlockID(Name("/%00%09")[0])

        identityStorage = MemoryIdentityStorage()
        privateKeyStorage = MemoryPrivateKeyStorage()
        identityManager = IdentityManager(identityStorage, privateKeyStorage)
        keyChain = KeyChain(identityManager, None)

        # Initialize the storage.
        keyName = Name("/ndn/bms/DSK-default")
        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)

        keyChain.sign(co, certificateName)

        _data = co.wireEncode()

        return _data.toRawStr()
Exemple #20
0
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        """
        Append the next segment number to the prefix and send a new data packet.
        If the last packet is sent, then set self._enabled[0] = False.
        """
        maxSegment = 2
        if self._segment >= maxSegment:
            return

        dump("Got interest", interest.toUri())

        # Make and sign a Data packet for the segment.
        self._segment += 1
        data = Data(Name(prefix).appendSegment(self._segment))
        content = "Segment number " + repr(self._segment)
        data.content = content
        self._keyChain.sign(data, self._certificateName)
        encodedData = data.wireEncode()

        transport.send(encodedData.toBuffer())
        dump("Sent data packet", data.name.toUri())

        if self._segment >= maxSegment:
            # We sent the final data packet, so stop.
            self._enabled[0] = False
Exemple #21
0
    def handleDataInterests(self, prefix, interest, transport, prefixId):
        # TODO: verification
        
        # we match the components to the name, and any '_' components
        # are discarded. Then we run a MongoDB query and append the
        # object id to allow for excludes

        chosenSchema = (s for s in self.schemaList 
                if s.dbPrefix.match(prefix)).next()

        interestName = interest.getName()
        responseName = Name(interestName)
        nameFields = chosenSchema.matchNameToSchema(interestName)
        self.log.info("Data requested with params:\n\t{}".format(nameFields))
        allResults = []
        segment = 0
        try:
            segmentComponent = interest.getName()[-4]
            segment = segmentComponent.toSegment()
        except RuntimeError:
            pass
        
        (startPos, results) = self._segmentResponseData(nameFields, segment)
        for result in results:
            dataId = result[u'_id']
            self.log.debug("Found object {}".format(dataId))
            allResults.append(result)

        #responseName.append(str(dataId))
        totalCount = results.count(False)
        responseObject = {'count':totalCount, 'skip':startPos, 'results':allResults}
        responseData = Data(responseName)
        resultEncoded = BSON.encode(responseObject)
        responseData.setContent(resultEncoded)
        transport.send(responseData.wireEncode().buf())
Exemple #22
0
    def test_encode_decode(self):
        data = Data()
        data.wireDecode(codedData2)
        data.setContent(data.getContent())
        encoding = data.wireEncode()

        reDecodedData = Data()
        reDecodedData.wireDecode(encoding)
        self.assertEqual(dumpData(reDecodedData), initialDump2, 'Re-decoded data does not match original dump')
Exemple #23
0
    def test_encode_decode(self):
        data = Data()
        data.wireDecode(codedData)
        data.setContent(data.getContent())
        encoding = data.wireEncode()

        reDecodedData = Data()
        reDecodedData.wireDecode(encoding)
        self.assertEqual(dumpData(reDecodedData), initialDump, 'Re-decoded data does not match original dump')
Exemple #24
0
    def onInterest(self, prefix, interest, face, interestFilterId, filter):

        interestName = interest.getName()
        data = Data(interestName)
        data.setContent("Test Push Interest Polling model")
        hourMilliseconds = 600 * 1000
        data.getMetaInfo().setFreshnessPeriod(hourMilliseconds)
        self.keyChain.sign(data, self.keyChain.getDefaultCertificateName())
        face.send(data.wireEncode().toBuffer())
        print "Replied to Interest name: %s" % interestName.toUri()
        print "Replied with Data name: %s" % interestName.toUri()
Exemple #25
0
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        self._responseCount += 1

        # Make and sign a Data packet.
        data = Data(interest.getName())
        content = "Echo " + interest.getName().toUri()
        data.setContent(content)
        self._keyChain.sign(data, self._certificateName)
        encodedData = data.wireEncode()

        dump("Sent content", content)
        transport.send(encodedData.toBuffer())
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        self._responseCount += 1

        # Make and sign a Data packet.
        data = Data(interest.getName())
        content = "Echo " + interest.getName().toUri()
        data.setContent(content)
        self._keyChain.sign(data, self._certificateName)
        encodedData = data.wireEncode()

        dump("Sent content", content)
        transport.send(encodedData.toBuffer())
Exemple #27
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()
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        interestName = interest.getName()

        data = Data(interestName)
        data.setContent("Hello, " + interestName.toUri())

        hourMilliseconds = 3600 * 1000
        data.getMetaInfo().setFreshnessPeriod(hourMilliseconds)

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

        transport.send(data.wireEncode().toBuffer())

        print "Replied to: %s" % interestName.toUri()
Exemple #29
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()
    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 onInterest(self, prefix, interest, transport, registeredPrefixId):
        interestName = interest.getName()

        data = Data(interestName)
        data.setContent("Hello, " + interestName.toUri())

        hourMilliseconds = 3600 * 1000
        data.getMetaInfo().setFreshnessPeriod(3600 * 1000)

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

        transport.send(data.wireEncode().toBuffer())

        print "Replied to: %s" % interestName.toUri()
Exemple #32
0
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        """
        FileSync:
            To be written (TBW)

        """
        util.dump("Got interest packet with name", interest.getName().toUri())
        util.dumpInterest(interest)

        content = fileSyncBuf_pb2.FileSync()
        sequenceNo = int(interest.getName().get(self.fileFolderPrefix.size() +
                                                1).toEscapedString())
        gotContent = False

        #loop through all cached data and find out if you have some new content to respond with
        for i in range(len(self.syncDataCache) - 1, -1, -1):
            data = self.syncDataCache[i]
            if data.sequenceNo == sequenceNo:
                if data.dataType != fileSyncBuf_pb2.FileSync.UPDATE:
                    # Use setattr because "from" is a reserved keyword.
                    setattr(content, "from", self.screenName)
                    content.to = self.fileFolderName
                    content.dataType = data.dataType
                    content.timestamp = int(round(data.time / 1000.0))
                else:
                    setattr(content, "from", self.screenName)
                    content.to = self.fileFolderName
                    content.dataType = data.dataType
                    content.data = data.data
                    content.timestamp = int(round(data.time / 1000.0))
                gotContent = True
                break

        if gotContent:
            logging.info("new content!")
            #Serialize the pklistbuf
            array = content.SerializeToString()
            #Initialize the data with Name
            data = Data(interest.getName())
            #Set content for the data --> the serialized content to bytes
            data.setContent(Blob(array))
            #Add sign the data
            self.keyChain.sign(data, self.certificateName)
            try:
                transport.send(data.wireEncode().toBuffer())
            except Exception as ex:
                logging.getLogger(__name__).error(
                    "Error in transport.send: %s", str(ex))
                return
Exemple #33
0
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        """Called when an interest for the specified name is recieved"""
        interestName = interest.getName()

        data = Data(interestName)
        data.setContent("Hello, " + interestName.toUri())

        hourMilliseconds = 3600 * 1000
        data.getMetaInfo().setFreshnessPeriod(hourMilliseconds)

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

        transport.send(data.wireEncode().toBuffer())

        dump("Replied to:", interestName.toUri())
Exemple #34
0
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        print("========= received [ interest ] ========= :\n" + interest.getName().toUri())  # for test
        interestName = interest.getName()
        appcontentstr = interest.getApplicationParameters()

        data = Data(interestName)
        data.setContent("Hello! This data come from producer-01.")

        # hourMilliseconds = 3600 * 1000
        hourMilliseconds = 0  # here I should set it 0 since it always need to fresh.

        data.getMetaInfo().setFreshnessPeriod(hourMilliseconds)
        self.keyChain.sign(data, self.keyChain.getDefaultCertificateName())
        transport.send(data.wireEncode().toBuffer())
        print("\n ######## Replied [ data ] ########\n \n")
Exemple #35
0
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        logging.debug('Received interest')

        self._responseCount += 1
	global g_responseCount 
	g_responseCount += 1

        # Make and sign a Data packet.
        data = Data(interest.getName())
        content = self.data#interest.getName().toUri()
        data.setContent(content)
        self._keyChain.sign(data, self._certificateName)
        encodedData = data.wireEncode()

        #dump("Sent content", content)
        transport.send(encodedData.toBuffer())
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        lines = open('cpu.txt', 'r')
        numbers = map(float, lines)
        max_number = max(numbers)
        interestName = interest.getName()
        data = Data(interestName)
        data.setContent("CPU max:" + str(max_number))

        hourMilliseconds = 3600 * 1000
        data.getMetaInfo().setFreshnessPeriod(hourMilliseconds)

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

        transport.send(data.wireEncode().toBuffer())

        print "Replied to: %s" % interestName.toUri()
Exemple #37
0
def main():
    data = Data()
    data.wireDecode(TlvData)
    dump("Decoded Data:")
    dumpData(data)

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

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

    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)

    keyChain.verifyData(reDecodedData, makeOnVerified("Re-decoded Data"),
                        makeOnVerifyFailed("Re-decoded Data"))

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

    keyChain.verifyData(freshData, makeOnVerified("Freshly-signed Data"),
                        makeOnVerifyFailed("Freshly-signed Data"))
Exemple #38
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())
Exemple #39
0
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        print 'Interest received: %s' % interest.getName().toUri()

        # Make and sign a Data packet.
        encoded_data = self.repo.extract_from_repo(interest)
        if not encoded_data:
            data = Data(interest.getName())
            content = "No match found"
            data.setContent(content)
            self._keyChain.sign(data, self._certificateName)
            encoded_data = data.wireEncode().toBuffer()
        else:
            dumpData(encoded_data)
            encoded_data = encoded_data.wireEncode().toBuffer()

        transport.send(encoded_data)
        print 'sent'
Exemple #40
0
        async def checkout():
            nonlocal fetcher, result
            await fetcher.wait_until_finish()
            if not fetcher.success:
                return

            # TODO W-A-W conflict
            timestamp = await self.sync.publish_data(branch)

            head_data_name = Name(self.repo_prefix).append("refs")
            head_data_name = head_data_name.append(branch).appendTimestamp(timestamp)
            head_data = Data(head_data_name)
            head_data.content = commit.encode("utf-8")
            # TODO Sign data

            self.update_branch(branch, timestamp, commit, head_data.wireEncode().toBytes())
            result = True
    def _onCommandReceived(self, prefix, interest, transport, prefixId):
        """
        """
        interestName = interest.getName()

        #if it is a certificate name, serve the certificate
        foundCert = self._identityStorage.getCertificate(interestName)
        if foundCert is not None:
            self.log.debug("Serving certificate request")
            transport.send(foundCert.wireEncode().buf())
            return

        afterPrefix = interestName.get(prefix.size()).toEscapedString()
        if afterPrefix == "listCommands":
            #compose device list
            self.log.debug("Received device list request")
            response = self._prepareCapabilitiesList(interestName)
            self.sendData(response, transport)
        elif afterPrefix == "certificateRequest":
            #build and sign certificate
            self.log.debug("Received certificate request")
            self._handleCertificateRequest(interest, transport)
        elif afterPrefix == "updateCapabilities":
            # needs to be signed!
            self.log.debug("Received capabilities update")
            def onVerifiedCapabilities(interest):
                response = Data(interest.getName())
                response.setContent(str(time.time()))
                self.sendData(response, transport)
                self._updateDeviceCapabilities(interest)
            self._keyChain.verifyInterest(interest, 
                    onVerifiedCapabilities, self.verificationFailed)
        elif afterPrefix == "addDevice":
            self.log.debug("Received pairing request")
            def onVerifiedPairingRequest(interest):
                response = Data(interest.getName())
                encryptedMessage = interest.getName()[len(prefix)+1]
                responseCode = self._beginPairing(encryptedMessage)
                response.setContent(str(responseCode))
                self.sendData(response, transport)
            self._keyChain.verifyInterest(interest, onVerifiedPairingRequest, self.verificationFailed)
        else:
            response = Data(interest.getName())
            response.setContent("500")
            response.getMetaInfo().setFreshnessPeriod(1000)
            transport.send(response.wireEncode().buf())
    def onInterest(self, prefix, interest, transport, registeredPrefixId):

        if self.delay is not None:
            time.sleep(self.delay)

        interestName = interest.getName()

        data = Data(interestName)
        data.setContent("Hello " + interestName.toUri())
        data.getMetaInfo().setFreshnessPeriod(3600 * 1000)

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

        transport.send(data.wireEncode().toBuffer())

        self.nDataServed += 1
        print "Replied to: %s (#%d)" % (interestName.toUri(), self.nDataServed)
Exemple #43
0
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        interestName = interest.getName()

        data = Data(interestName)
        data.setContent("Hello, " + interestName.toUri())

        # hourMilliseconds = 3600 * 1000
        # data.getMetaInfo().setFreshnessPeriod(hourMilliseconds)

        #manually adjust the FreshnessPeriod based on the time of producing a data packet
        productionTimeGap = 3600 * 1000
        data.getMetaInfo().setFreshnessPeriod(productionTimeGap)

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

        transport.send(data.wireEncode().toBuffer())

        print("Replied to: %s" % interestName.toUri())
def main():
    data = Data()
    data.wireDecode(TlvData)
    dump("Decoded Data:")
    dumpData(data)

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

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

    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)

    keyChain.verifyData(reDecodedData, makeOnVerified("Re-decoded Data"),
                        makeOnVerifyFailed("Re-decoded Data"))

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

    keyChain.verifyData(freshData, makeOnVerified("Freshly-signed Data"),
                        makeOnVerifyFailed("Freshly-signed Data"))
Exemple #45
0
    def handleCommandInterests(self, prefix, interest, transport, prefixId):
        # TODO: verification
        interestName = interest.getName()
        if len(interestName) <= len(prefix)+4:
            self.log.info("Bad command interest")
        commandName = str(interestName[len(prefix)].getValue())
        responseMessage =  RepoCommandResponseMessage()
        if commandName == 'insert':
            commandParams = interestName[len(prefix)+1].getValue()
            commandMessage = RepoCommandParameterMessage()
            ProtobufTlv.decode(commandMessage, commandParams)
            dataName = Name()
            fullSchemaName = Name()
            for component in commandMessage.command.name.components:
                fullSchemaName.append(component)
                if component == '_':
                    continue
                dataName.append(component)
            self.log.info("Insert request for {}".format(dataName))
            responseMessage.response.status_code = 100
            processId = self.currentProcessId
            self.currentProcessId += 1
            responseMessage.response.process_id = processId
        else:
            responseMessage.response.status_code = 403
        responseData = Data(interestName)
        responseData.setContent(ProtobufTlv.encode(responseMessage))
        transport.send(responseData.wireEncode().buf())

        # now send the interest out to the publisher
        # TODO: pendingProcesses becomes list of all processes as objects
        i = Interest(dataName)
        i.setChildSelector(1)
        i.setInterestLifetimeMilliseconds(4000)
        try:
            self.pendingProcesses[processId] = (dataName, 100)
        except NameError:
            pass # wasn't valid insert request
        else:
            self._insertFace.expressInterest(i, 
                    self._onInsertionDataReceived,
                    self._onInsertionDataTimeout)
Exemple #46
0
    def sendingFile(self, file_path, interest, face, freshness):
        print "Sending File Function"
        interestName = interest.getName()
        interestNameSize = interestName.size()

        try:
            SegmentNum = (interestName.get(interestNameSize - 1)).toSegment()
            dataName = interestName.getSubName(0, interestNameSize - 1)

        # If no segment number is included in the INTEREST, set the segment number as 0 and set the file name to configuration script to be sent
        except RuntimeError as e:
            SegmentNum = 0
            dataName = interestName
        # Put file to the Data message
        try:
            # due to overhead of NDN name and other header values; NDN header overhead + Data packet content = < maxNdnPacketSize
            # So Here segment size is hard coded to 5000 KB.
            # Class Enumerate publisher is used to split large files into segments and get a required segment ( segment numbers started from 0)
            dataSegment, last_segment_num = EnumeratePublisher(
                file_path, self.Datamessage_size, SegmentNum).getFileSegment()
            print 'SegmentNum:%s last_segment_num: %s' % (SegmentNum,
                                                          last_segment_num)
            # create the DATA name appending the segment number
            dataName = dataName.appendSegment(SegmentNum)
            data = Data(dataName)
            data.setContent(dataSegment)

            # set the final block ID to the last segment number
            last_segment = (Name.Component()).fromNumber(last_segment_num)
            data.getMetaInfo().setFinalBlockId(last_segment)
            #hourMilliseconds = 600 * 1000
            data.getMetaInfo().setFreshnessPeriod(freshness)

            # currently Data is signed from the Default Identitiy certificate
            self.keyChain.sign(data, self.keyChain.getDefaultCertificateName())
            # Sending Data message
            face.send(data.wireEncode().toBuffer())
            print "Replied to Interest name: %s" % interestName.toUri()
            print "Replied with Data name: %s" % dataName.toUri()

        except ValueError as err:
            print "ERROR: %s" % err
Exemple #47
0
def main():
    data = Data()
    data.wireDecode(TlvData)
    dump("Decoded Data:")
    dumpData(data)

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

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

    # Set up the KeyChain.
    pibImpl = PibMemory()
    keyChain = KeyChain(
      pibImpl, TpmBackEndMemory(), SelfVerifyPolicyManager(pibImpl))
    # This puts the public key in the pibImpl used by the SelfVerifyPolicyManager.
    keyChain.importSafeBag(SafeBag
      (Name("/testname/KEY/123"),
       Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False),
       Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)))

    keyChain.verifyData(reDecodedData, makeOnVerified("Re-decoded Data"),
                        makeOnValidationFailed("Re-decoded Data"))

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

    keyChain.verifyData(freshData, makeOnVerified("Freshly-signed Data"),
                        makeOnValidationFailed("Freshly-signed Data"))
    def _onInterest(self, prefix, interest, transport, registeredPrefixId):
        """
        Send back a Chat Data Packet which contains the user's message.
        """
        content = chatbuf_pb2.ChatMessage()
        sequenceNo = int(
          interest.getName().get(self._chatPrefix.size() + 1).toEscapedString())
        gotContent = False
        for i in range(len(self._messageCache) - 1, -1, -1):
            message = self._messageCache[i]
            if message.sequenceNo == sequenceNo:
                if message.messageType != chatbuf_pb2.ChatMessage.CHAT:
                    # Use setattr because "from" is a reserved keyword.
                    setattr(content, "from", self._screenName)
                    content.to = self._chatRoom
                    content.type = message.messageType
                    content.timestamp = int(round(message.time / 1000.0))
                else:
                    setattr(content, "from", self._screenName)
                    content.to = self._chatRoom
                    content.type = message.messageType
                    content.data = message.message
                    content.timestamp = int(round(message.time / 1000.0))

                gotContent = True
                break

        if gotContent:
            # TODO: Check if this works in Python 3.
            array = content.SerializeToString()
            data = Data(interest.getName())
            data.setContent(Blob(array))
            self._keyChain.sign(data, self._certificateName)
            try:
                transport.send(data.wireEncode().toBuffer())
            except Exception as ex:
                logging.getLogger(__name__).error(
                  "Error in transport.send: %s", str(ex))
                return
Exemple #49
0
def insert_fake_data():
    i = 0
    while i < 10:
        i += 1
        fake_data = Data(
            Name('/ndn/' + random_string() + '/' + random_string()))
        fake_data.setContent(random_string(100))
        try:
            controlCenterDB.put(fake_data.name.__str__(),
                                fake_data.wireEncode().toBytes())
        except:
            return connectivity_error()

    return render_template(
        'message.html',
        title='Success',
        heading='Success',
        message='Ten fake Data packets have been inserted into the repo',
        time=datetime.datetime.now(),
        badge_tag='success',
        alert_tag='success',
        badge_text='OK')
Exemple #50
0
        async def checkout():
            nonlocal fetcher, result
            await fetcher.wait_until_finish()
            if not fetcher.success:
                return

            # TODO W-A-W conflict
            timestamp = await self.sync.publish_data(branch)
            self.branches[branch].timestamp = timestamp
            self.branches[branch].head = commit

            # Fix the database
            head_data_name = Name(self.repo_prefix).append("refs")
            head_data_name = head_data_name.append(branch).appendTimestamp(
                timestamp)
            head_data = Data(head_data_name)
            head_data.content = commit.encode("utf-8")
            # TODO Sign data
            self.branches[branch].head_data = head_data.wireEncode().toBytes()
            self.repo_db.put(branch, pickle.dumps(self.branches[branch]))
            self.branches[branch].head_data = b""
            result = True
def main():
    data = Data()
    data.wireDecode(TlvData)
    dump("Decoded Data:")
    dumpData(data)

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

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

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

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

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

    validator.validate(freshData, makeSuccessCallback("Freshly-signed Data"),
      makeFailureCallback("Freshly-signed Data"))
Exemple #52
0
    def _onConfigurationReceived(self, prefix, interest, transport, prefixId):
        # the interest we get here is signed by HMAC, let's verify it
        self.tempPrefixId = prefixId  # didn't get it from register because of the event loop
        interestName = interest.getName()
        replyData = Data(interestName)
        if len(interestName) == len(prefix):
            # this is a discovery request. Check the exclude to see if we should
            # return our serial
            serial = self.getSerial()
            serialComponent = Name.Component(serial)
            if not interest.getExclude().matches(serialComponent):
                replyData.setContent(serial)
                self.sendData(replyData, transport,
                              False)  # no point in signing
        elif (self._hmacHandler.verifyInterest(interest)):
            # we have a match! decode the network parameters
            configComponent = interest.getName()[len(prefix) + 1]
            replyData.setContent('200')
            self._hmacHandler.signData(replyData, keyName=self.prefix)
            transport.send(replyData.wireEncode().buf())

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

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

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

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

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

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

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

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

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

    validator.validate(freshData, makeSuccessCallback("Freshly-signed Data"),
                       makeFailureCallback("Freshly-signed Data"))
Exemple #54
0
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        interestName = interest.getName()

        data = Data(interestName)

        print "Downloading : %s" % interestName.toUri()

        min_char = self.maxNdnPacketSize - 400
        max_char = self.maxNdnPacketSize - 400
        allchar = string.ascii_letters + string.punctuation + string.digits
        rint = randint(min_char, max_char)
        cont = "".join(choice(allchar) for x in range(rint))
        data.setContent(cont)
        time.sleep(2)

        hourMilliseconds = 3600 * 1000
        data.getMetaInfo().setFreshnessPeriod(hourMilliseconds)

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

        transport.send(data.wireEncode().toBuffer())

        print "Replied to: %s" % interestName.toUri()
Exemple #55
0
    def onConsumeComplete(self, data, result, producedDataName, outerDataName):
        print "Consume complete for data name: " + data.getName().toUri()

        if producedDataName in self._tasks:
            self._tasks[producedDataName]["current_num"] += 1
            self._tasks[producedDataName]["dataset"].append(result)
            if self._tasks[producedDataName]["current_num"] == self._tasks[producedDataName]["cap_num"]:
                maxLng = -1000
                minLng = 1000
                maxLat = -1000
                minLat = 1000
                for item in self._tasks[producedDataName]["dataset"]:
                    dataObject = json.loads(str(item))
                    if dataObject["lat"] > maxLat:
                        maxLat = dataObject["lat"]
                    if dataObject["lat"] < minLat:
                        minLat = dataObject["lat"]
                    if dataObject["lng"] > maxLng:
                        maxLng = dataObject["lng"]
                    if dataObject["lng"] < minLng:
                        minLng = dataObject["lng"]

                if not self._encryptResult:
                    innerData = Data(Name(str(producedDataName)))
                    innerData.setContent(json.dumps({"minLat": minLat, "maxLat": maxLat, "minLng": minLng, "maxLng": maxLng}))
                    #self.keyChain.sign(innerData)

                    outerData = Data(Name(str(outerDataName)))
                    outerData.setContent(innerData.wireEncode())
                    #self.keyChain.sign(outerData)

                    self.memoryContentCache.add(outerData)
                    self.initiateContentStoreInsertion("/ndn/edu/ucla/remap/ndnfit/repo", outerData)
                    print "Calculation completed, put data to repo"
                else:
                    print "Encrypt result is not implemented"
Exemple #56
0
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        global stopServing

        if stopServing:
            print "refusing to serve " + interest.getName().toUri()
            self.consoleThread.join()
            print "join'd thread"
            return

        if self.delay is not None:
            time.sleep(self.delay)

        interestName = interest.getName()

        data = Data(interestName)
        data.setContent("Hello " + interestName.toUri())
        data.getMetaInfo().setFreshnessPeriod(3600 * 1000)

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

        transport.send(data.wireEncode().toBuffer())

        self.nDataServed += 1
        print "Replied to: %s (#%d)" % (interestName.toUri(), self.nDataServed)
def benchmarkEncodeDataSeconds(nIterations, useComplex, useCrypto):
    """
    Loop to encode a data packet nIterations times.

    :param int nIterations: The number of iterations.
    :param bool useComplex: If true, use a large name, large content and all
      fields. If false, use a small name, small content and only required
      fields.
    :param bool useCrypto: If true, sign the data packet.  If false, use a blank
      signature.
    :return: A tuple (duration, encoding) where duration is the number of
      seconds for all iterations and encoding is the wire encoding.
    :rtype: (float, Blob)
    """
    if useComplex:
        # Use a large name and content.
        name = Name(
          "/ndn/ucla.edu/apps/lwndn-test/numbers.txt/%FD%05%05%E8%0C%CE%1D/%00")

        contentString = ""
        count = 1
        contentString += "%d" % count
        count += 1
        while len(contentString) < 1115:
            contentString += " %d" % count
            count += 1
        content = Name.fromEscapedString(contentString)
    else:
        # Use a small name and content.
        name = Name("/test")
        content = Name.fromEscapedString("abc")
    finalBlockId = Name("/%00")[0]

    # Initialize the private key storage in case useCrypto is true.
    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
                        SelfVerifyPolicyManager(identityStorage))
    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)

    # Set up signatureBits in case useCrypto is false.
    signatureBits = Blob(bytearray(256))
    emptyBlob = Blob([])

    start = getNowSeconds()
    for i in range(nIterations):
        data = Data(name)
        data.setContent(content)
        if useComplex:
            data.getMetaInfo().setFreshnessPeriod(1000)
            data.getMetaInfo().setFinalBlockId(finalBlockId)

        if useCrypto:
            # This sets the signature fields.
            keyChain.sign(data, certificateName)
        else:
            # Imitate IdentityManager.signByCertificate to set up the signature
            # fields, but don't sign.
            sha256Signature = data.getSignature()
            keyLocator = sha256Signature.getKeyLocator()
            keyLocator.setType(KeyLocatorType.KEYNAME)
            keyLocator.setKeyName(certificateName)
            sha256Signature.setSignature(signatureBits)

        encoding = data.wireEncode()

    finish = getNowSeconds()

    return (finish - start, encoding)
Exemple #58
0
from pyndn import Data
from pyndn.security import KeyChain

import sys

from RepoSocketPublisher import RepoSocketPublisher

publisher = RepoSocketPublisher(12345)

keyChain = KeyChain()

max_packets = 50000

total_size = 0

n = Name("/test").append(str(0))
d = Data(n)
d.setContent("this is a test.")
d.getMetaInfo().setFreshnessPeriod(4000)
keyChain.sign(d, keyChain.getDefaultCertificateName())

for i in range(0, max_packets + 1):
    n = Name("/test").append(str(i))
    d.setName(n)
    if i % 100000 == 0:
        print str(i)
    if i == max_packets:
        print str(total_size)
    total_size = total_size + d.wireEncode().size()
    publisher.put(d)