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)
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()
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 publishData(self): timestamp = time.time() 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 = { 'cpu_usage': cpu_use, 'users': users, 'processes': nProcesses, 'memory_usage': memUse, 'swap_usage': swapUse } dataOut = Data(Name(self._dataPrefix).appendVersion(int(timestamp))) dataOut.setContent(json.dumps(info)) dataOut.getMetaInfo().setFreshnessPeriod(10000) self.signData(dataOut) self._dataCache.add(dataOut) # repeat every 5 seconds self.loop.call_later(5, self.publishData)
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()
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
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
def __init__(self, prefix, transferfile): self.keyChain = KeyChain() self.prefix = Name(prefix) self.isDone = False self.transferfile = transferfile # Initialize list for Data packet storage. # We'll treat the indices as equivalent to the sequence # number requested by Interests. self.data = [] f = open(transferfile, 'rb') imgdata = f.read() chunks = list(chunkstring(imgdata, 8192)) print len(chunks) finalBlock = Name.Component.fromNumberWithMarker(len(chunks) - 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(0, len(chunks)): dataName = Name(prefix).appendSegment(i) print dataName data = Data(dataName) data.setContent(chunks[i]) data.getMetaInfo().setFinalBlockID(finalBlock) data.getMetaInfo().setFreshnessPeriod(hourMilliseconds) self.keyChain.sign(data, self.keyChain.getDefaultCertificateName()) self.data.append(data)
def test_malformed_certificate(self): # Copy the default certificate. malformedCertificate = Data( self._fixture._subIdentity.getDefaultKey().getDefaultCertificate()) malformedCertificate.getMetaInfo().setType(ContentType.BLOB) self._fixture._keyChain.sign( malformedCertificate, SigningInfo(self._fixture._identity)) # It has the wrong content type and a missing ValidityPeriod. try: CertificateV2(malformedCertificate).wireEncode() self.fail("Did not throw the expected exception") except CertificateV2.Error: pass else: self.fail("Did not throw the expected exception") originalProcessInterest = self._fixture._face._processInterest def processInterest(interest, onData, onTimeout, onNetworkNack): if interest.getName().isPrefixOf(malformedCertificate.getName()): onData(interest, malformedCertificate) else: originalProcessInterest.processInterest( interest, onData, onTimeout, onNetworkNack) self._fixture._face._processInterest = processInterest data = Data(Name("/Security/V2/ValidatorFixture/Sub1/Sub2/Data")) self._fixture._keyChain.sign(data, SigningInfo(self._fixture._subIdentity)) self.validateExpectFailure(data, "Signed by a malformed certificate") self.assertEqual(1, len(self._fixture._face._sentInterests))
def _onInterest(self, prefix, interest, face, interestFilterId, filter): """ Send back a Chat Data Packet which contains the user's message. """ sequenceNo = int(interest.getName()[-1].toEscapedString()) gotContent = False content = None for i in range(len(self._messageCache) - 1, -1, -1): message = self._messageCache[i] if message.sequenceNo == sequenceNo: # Use setattr because "from" is a reserved keyword. # For now we have one message only... content = json.dumps({ 'names': [message.name.toUri()], 'timestamp': int(round(message.time / 1000.0)) }) gotContent = True break if gotContent: # TODO: Check if this works in Python 3. data = Data(interest.getName()) data.setContent(content) data.getMetaInfo().setFreshnessPeriod( self._namespaceMessageFreshnessPeriod) self._keyChain.sign(data, self._certificateName) try: face.putData(data) except Exception as ex: logging.getLogger(__name__).error( "Error in transport.send: %s", str(ex)) return
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())
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)
def test_malformed_certificate(self): # Copy the default certificate. malformedCertificate = Data( self._fixture._subIdentity.getDefaultKey().getDefaultCertificate()) malformedCertificate.getMetaInfo().setType(ContentType.BLOB) self._fixture._keyChain.sign(malformedCertificate, SigningInfo(self._fixture._identity)) # It has the wrong content type and a missing ValidityPeriod. try: CertificateV2(malformedCertificate).wireEncode() self.fail("Did not throw the expected exception") except CertificateV2.Error: pass else: self.fail("Did not throw the expected exception") originalProcessInterest = self._fixture._face._processInterest def processInterest(interest, onData, onTimeout, onNetworkNack): if interest.getName().isPrefixOf(malformedCertificate.getName()): onData(interest, malformedCertificate) else: originalProcessInterest.processInterest( interest, onData, onTimeout, onNetworkNack) self._fixture._face._processInterest = processInterest data = Data(Name("/Security/V2/ValidatorFixture/Sub1/Sub2/Data")) self._fixture._keyChain.sign(data, SigningInfo(self._fixture._subIdentity)) self.validateExpectFailure(data, "Signed by a malformed certificate") self.assertEqual(1, len(self._fixture._face._sentInterests))
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"
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 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)
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 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 createFreshData(self): freshData = Data(Name("/ndn/abc")) freshData.setContent("SUCCESS!") freshData.getMetaInfo().setFreshnessPeriod(5000.0) freshData.getMetaInfo().setFinalBlockId(Name("/%00%09")[0]) # Initialize the storage. return freshData
def createFreshData(self): freshData = Data(Name("/ndn/abc")) freshData.setContent("SUCCESS!") freshData.getMetaInfo().setFreshnessPeriod(5000.0) freshData.getMetaInfo().setFinalBlockID(Name("/%00%09")[0]) # Initialize the storage. return freshData
def createData(self, namePrefix, timestamp, payload, certName): data = Data(Name(self._namespace).append(namePrefix).append(str(int(float(timestamp))))) data.setContent(payload) self._keyChain.sign(data, certName) data.getMetaInfo().setFreshnessPeriod(self.DEFAULT_DATA_LIFETIME) if __debug__: print(data.getName().toUri()) return data
def publishData(self, key, key_ts, payload, timestamp): data = Data(Name(self.prefix).append(bytearray(timestamp))) iv = Random.new().read(AES.block_size) encryptor = AES.new(key, AES.MODE_CBC, iv) data.setContent(bytearray(key_ts + iv + encryptor.encrypt(pad(json.dumps(payload))))) data.getMetaInfo().setFreshnessPeriod(5000) self.keychain.sign(data, self.cert_name) self.publisher.put(data)
def createData(self, namePrefix, timestamp, payload, certName): data = Data( Name(self._namespace).append(namePrefix).append(str(timestamp))) data.setContent(payload) self._keyChain.sign(data, certName) data.getMetaInfo().setFreshnessPeriod(self.DEFAULT_DATA_LIFETIME) if __debug__: print(data.getName().toUri()) return data
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"
def reply_(self, interest, response): if type(response) is Response: data = Data(interest.getName().appendTimestamp( self.microsecondTimestamp_())) data.setContent(json.dumps(response.payload_)) data.getMetaInfo().setFreshnessPeriod(100) self.keyChain_.sign(data) self.face_.putData(data) else: raise "Returned type is not Response"
def contentCacheAddEntityData(self, name, entityInfo): content = self._serializer.serialize(entityInfo) data = Data(Name(name)) data.setContent(content) data.getMetaInfo().setFreshnessPeriod(self._entityDataFreshnessPeriod) self._keyChain.sign(data, self._certificateName) self._memoryContentCache.add(data) print "added entity to cache: " + data.getName().toUri() + "; " + data.getContent().toRawStr()
def onEntityDataNotFound(self, prefix, interest, face, interestFilterId, filter): name = interest.getName().toUri() if name in self._hostedObjects: content = self._serializer.serialize(self._hostedObjects[name]) data = Data(Name(name)) data.setContent(content) data.getMetaInfo().setFreshnessPeriod(self._entityDataFreshnessPeriod) self._keyChain.sign(data, self._certificateName) self._face.putData(data) return
def set_returndata(self, interest, returndatacontent): interestName = interest.getName() data = Data(interestName) data.setContent( returndatacontent) #suppose the returndatacontent is string 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() ) #need to cheek if it works here. return (data)
def test_sign_verify_data(self): freshData = Data(Name("/ndn/abc")) freshData.setContent("SUCCESS!") freshData.getMetaInfo().setFreshnessPeriod(5000.0) freshData.getMetaInfo().setFinalBlockId(Name("/%00%09")[0]) self.h.signData(freshInterest, self.raw_key_name) result = self.h.verifyInterest(freshInterest) self.assertEqual(result, True, 'verifiedInterest does not match original interest')
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()
def unknownCommandResponse(self, interest): """ Called when the node receives an interest where the handler is unknown or unimplemented. :return: the Data packet to return in case of unhandled interests. Return None to ignore and let the interest timeout or be handled by another node. :rtype: pyndn.Data """ responseData = Data(Name(interest.getName()).append("unknown")) responseData.setContent("Unknown command name") responseData.getMetaInfo().setFreshnessPeriod(1000) # expire soon return responseData
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()
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()
def contentCacheAddSyncData(self, dataName): sortedKeys = sorted(self._objects.keys()) content = "" for key in sortedKeys: content += key + "\n" content.strip() data = Data(Name(dataName)) data.setContent(content) data.getMetaInfo().setFreshnessPeriod(self._syncDataFreshnessPeriod) self._keyChain.sign(data, self._certificateName) # adding this data to memoryContentCache should satisfy the pending interest self._memoryContentCache.add(data)
def publishMetadata(self): # For now, hardcoded sensor list on gateway's end data = Data( Name(self._namespace).append("_meta").append( str(int(time.time() * 1000.0)))) data.setContent(json.dumps(self._sensorList)) data.getMetaInfo().setFreshnessPeriod(self._defaultFreshnessPeriod) self._keyChain.sign(data) self._cache.add(data) print("Metadata " + data.getName().toUri() + " added for sensor list: " + str(self._sensorList)) self.startRepoInsertion(data) return
def 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")
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())
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()
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())
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"))
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)
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 produce(self): # Produce the bounding box print "ready to produce" maxLong = -3600 minLong = 3600 maxLat = -3600 minLat = 3600 if len(self.rawData) == 0: print "No raw data as producer input" for item in self.rawData: print item if item["lng"] > maxLong: maxLong = item["lng"] if item["lng"] < minLong: minLong = item["lng"] if item["lat"] > maxLat: maxLat = item["lat"] if item["lat"] < minLat: minLat = item["lat"] result = json.dumps({ "maxlng": maxLong, "minlng": minLong, "maxlat": maxLat, "minlat": minLat, "size": len(self.rawData) }) if self.encrypted: # TODO: replace fixed timestamp for now for produced data, createContentKey as needed testTime1 = Schedule.fromIsoString("20160320T080000") self.producer.createContentKey(testTime1) self.producer.produce(testTime1, result) else: # Arbitrary produced data lifetime data = Data(Name(self.identityName).append("20160320T080000")) data.getMetaInfo().setFreshnessPeriod(400000) data.setContent(result) # If the interest's still within lifetime, this will satisfy the interest self.memoryContentCache.add(data) print "Produced data with name " + data.getName().toUri()
def _handleCertificateRequest(self, interest): """ Extracts a public key name and key bits from a command interest name component. Generates a certificate if the request is verifiable. This expects an HMAC signed interest. """ message = CertificateRequestMessage() commandParamsTlv = interest.getName().get(self.prefix.size() + 1) ProtobufTlv.decode(message, commandParamsTlv.getValue()) signature = HmacHelper.extractInterestSignature(interest) deviceSerial = str( signature.getKeyLocator().getKeyName().get(-1).getValue()) response = Data(interest.getName()) certData = None hmac = None try: hmac = self._hmacDevices[deviceSerial] if hmac.verifyInterest(interest): certData = self._createCertificateFromRequest(message) # remove this hmac; another request will require a new pin self._hmacDevices.pop(deviceSerial) except KeyError: self.log.warn( 'Received certificate request for device with no registered key' ) except SecurityException as e: self.log.warn('Could not create device certificate: ' + str(e)) else: self.log.info( 'Creating certificate for device {}'.format(deviceSerial)) if certData is not None: response.setContent(certData.wireEncode()) response.getMetaInfo().setFreshnessPeriod( 10000) # should be good even longer else: response.setContent("Denied") if hmac is not None: hmac.signData(response) self.sendData(response, False)
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"))
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
def publishData(self, idx): # Translation of the video URL has finished by the time of the publishData call; # if not, we set translated to "publish"; this is data race free since translateUrl and publishData are scheduled in the same thread if self._events[idx]["translated"] != "none": # Order published events sequence numbers by start times in destination data = Data(Name(self._namePrefixString + str(self._currentIdx))) data.setContent(json.dumps(self._events[idx])) data.getMetaInfo().setFreshnessPeriod(self._dataLifetime) self._keyChain.sign(data, self._certificateName) self._memoryContentCache.add(data) self._currentIdx += 1 if __debug__: eventId = str(self._events[idx]["event_id"]) channel = str(self._events[idx]["channel"]) srcUrl = str(self._events[idx]["src_url"]) clipName = str(self._events[idx]["clipName"]) ytPresent = str(self._events[idx]["ytPresent"]) clipStartTime = str(self._events[idx]["dst_start_time"]) clipEndTime = str(self._events[idx]["dst_end_time"]) print( str(time.time()) + " Added event [" + eventId + "-" + channel + "|" + clipName + " YT:" + ytPresent + " " + srcUrl[0:30] + "... " + clipStartTime + "-" + clipEndTime + "] (" + data.getName().toUri() + ")" ) else: self._events[idx]["translated"] = "publish"
def publishData(self): timestamp = time.time() 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 = {'cpu_usage':cpu_use, 'users':users, 'processes':nProcesses, 'memory_usage':memUse, 'swap_usage':swapUse} dataOut = Data(Name(self._dataPrefix).appendVersion(int(timestamp))) dataOut.setContent(json.dumps(info)) dataOut.getMetaInfo().setFreshnessPeriod(10000) self.signData(dataOut) self._dataCache.add(dataOut) # repeat every 5 seconds self.loop.call_later(5, self.publishData)
def onBtleData(self, data): # expect data format like "0.2,0.1,0.3" content = data.getContent().toRawStr() print "got data: " + data.getName().toUri() + " : " + content if self._security: # Hmac verify the data we receive pass pyr = content.split(',') if len(pyr) >= 3: resultingContent = "{\"p\":" + pyr[0] + ",\"y\":" + pyr[1] + ",\"r\":" + pyr[2] + "}" timestamp = time.time() * 1000 dataOut = Data(Name(self._dataPrefix).appendVersion(int(timestamp))) dataOut.setContent(resultingContent) dataOut.getMetaInfo().setFreshnessPeriod(10000) self._keyChain.sign(dataOut, self._certificateName) self._dataCache.add(dataOut) print "data added: " + dataOut.getName().toUri()
def publishData(self): timestamp = time.time() 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 = {'cpu_usage':cpu_use, 'users':users, 'processes':nProcesses, 'memory_usage':memUse, 'swap_usage':swapUse} dataOut = Data(Name(self._dataPrefix).appendVersion(int(timestamp))) dataOut.setContent(json.dumps(info)) dataOut.getMetaInfo().setFreshnessPeriod(10000) self._keyChain.sign(dataOut, self._certificateName) self._dataCache.add(dataOut) print "data added: " + dataOut.getName().toUri() # repeat every 5 seconds self._face.callLater(5000, self.publishData)
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"))
def calculateAggregation(self, dataType, aggregationType, childrenList, startTime, interval, publishingPrefix, repeat = False): doCalc = True dataList = [] # TODO: an intermediate node cannot produce raw data for now if len(childrenList.keys()) != 0: for childName in childrenList.keys(): dataDictKey = self.getDataDictKey(startTime, (startTime + interval), childName) if dataDictKey in self._dataQueue[dataType + aggregationType]._dataDict: data = self._dataQueue[dataType + aggregationType]._dataDict[dataDictKey] dataList.append(float(data.getContent().toRawStr())) else: #print('Child ' + childName + ' has not replied yet') doCalc = False break else: for inst in self._dataQueue[dataType]._dataDict.keys(): if int(inst) >= startTime and int(inst) < startTime + interval: dataList.append(self._dataQueue[dataType]._dataDict[inst]) if doCalc: content = self._aggregation.getAggregation(aggregationType, dataList) if content: publishData = Data(Name(publishingPrefix).append(str(startTime)).append(str(startTime + interval))) publishData.setContent(str(content)) publishData.getMetaInfo().setFreshnessPeriod(DEFAULT_DATA_LIFETIME) self._keyChain.sign(publishData, self._certificateName) self._memoryContentCache.add(publishData) for childName in childrenList.keys(): dataDictKey = self.getDataDictKey(startTime, (startTime + interval), childName) if dataDictKey in self._dataQueue[dataType + aggregationType]._dataDict: del self._dataQueue[dataType + aggregationType]._dataDict[dataDictKey] if __debug__: print("Produced: " + publishData.getName().toUri() + "; " + publishData.getContent().toRawStr()) # repetition of this function only happens for raw data producer, otherwise calculateAggregation is called by each onData if repeat: self._loop.call_later(interval, self.calculateAggregation, dataType, aggregationType, childrenList, startTime + interval, interval, publishingPrefix, repeat) return
def _handleCertificateRequest(self, interest, transport): """ Extracts a public key name and key bits from a command interest name component. Generates a certificate if the request is verifiable. This expects an HMAC signed interest. """ message = CertificateRequestMessage() commandParamsTlv = interest.getName().get(self.prefix.size()+1) ProtobufTlv.decode(message, commandParamsTlv.getValue()) signature = HmacHelper.extractInterestSignature(interest) deviceSerial = str(signature.getKeyLocator().getKeyName().get(-1).getValue()) response = Data(interest.getName()) certData = None hmac = None try: hmac = self._hmacDevices[deviceSerial] if hmac.verifyInterest(interest): certData = self._createCertificateFromRequest(message) # remove this hmac; another request will require a new pin self._hmacDevices.pop(deviceSerial) except KeyError: self.log.warn('Received certificate request for device with no registered key') except SecurityException: self.log.warn('Could not create device certificate') else: self.log.info('Creating certificate for device {}'.format(deviceSerial)) if certData is not None: response.setContent(certData.wireEncode()) response.getMetaInfo().setFreshnessPeriod(10000) # should be good even longer else: response.setContent("Denied") if hmac is not None: hmac.signData(response) self.sendData(response, transport, False)