def processInterest(interest, onData, onTimeout, onNetworkNack): try: # Create another key for the same identity and sign it properly. parentKey = self._fixture._keyChain.createKey( self._fixture._subIdentity) requestedKey = self._fixture._subIdentity.getKey(interest.getName()) # Copy the Name. certificateName = Name(requestedKey.getName()) certificateName.append("looper").appendVersion(1) certificate = CertificateV2() certificate.setName(certificateName) # Set the MetaInfo. certificate.getMetaInfo().setType(ContentType.KEY) # Set the freshness period to one hour. certificate.getMetaInfo().setFreshnessPeriod(3600 * 1000.0) # Set the content. certificate.setContent(requestedKey.getPublicKey()) # Set SigningInfo. params = SigningInfo(parentKey) # Validity period from 10 days before to 10 days after now. now = Common.getNowMilliseconds() params.setValidityPeriod(ValidityPeriod( now - 10 * 24 * 3600 * 1000.0, now + 10 * 24 * 3600 * 1000.0)) self._fixture._keyChain.sign(certificate, params) onData(interest, certificate) except Exception as ex: self.fail("Error in InfiniteCertificateChain: " + repr(ex))
def addCertificate(self, key, issuerId): """ Add a self-signed certificate made from the key and issuer ID. :param PibKey key: The key for the certificate. :param str issuerId: The issuer ID name component for the certificate name. :return: The new certificate. :rtype: CertificateV2 """ certificateName = Name(key.getName()) certificateName.append(issuerId).appendVersion(3) certificate = CertificateV2() certificate.setName(certificateName) # Set the MetaInfo. certificate.getMetaInfo().setType(ContentType.KEY) # One hour. certificate.getMetaInfo().setFreshnessPeriod(3600 * 1000.0) # Set the content. certificate.setContent(key.getPublicKey()) params = SigningInfo(key) # Validity period of 10 days. now = Common.getNowMilliseconds() params.setValidityPeriod( ValidityPeriod(now, now + 10 * 24 * 3600 * 1000.0)) self._keyChain.sign(certificate, params) return certificate
def processInterest(interest, onData, onTimeout, onNetworkNack): try: # Create another key for the same identity and sign it properly. parentKey = self._fixture._keyChain.createKey( self._fixture._subIdentity) requestedKey = self._fixture._subIdentity.getKey( interest.getName()) # Copy the Name. certificateName = Name(requestedKey.getName()) certificateName.append("looper").appendVersion(1) certificate = CertificateV2() certificate.setName(certificateName) # Set the MetaInfo. certificate.getMetaInfo().setType(ContentType.KEY) # Set the freshness period to one hour. certificate.getMetaInfo().setFreshnessPeriod(3600 * 1000.0) # Set the content. certificate.setContent(requestedKey.getPublicKey()) # Set SigningInfo. params = SigningInfo(parentKey) # Validity period from 10 days before to 10 days after now. now = Common.getNowMilliseconds() params.setValidityPeriod( ValidityPeriod(now - 10 * 24 * 3600 * 1000.0, now + 10 * 24 * 3600 * 1000.0)) self._fixture._keyChain.sign(certificate, params) onData(interest, certificate) except Exception as ex: self.fail("Error in InfiniteCertificateChain: " + repr(ex))
def addCertificate(self, key, issuerId): """ Add a self-signed certificate made from the key and issuer ID. :param PibKey key: The key for the certificate. :param str issuerId: The issuer ID name component for the certificate name. :return: The new certificate. :rtype: CertificateV2 """ certificateName = Name(key.getName()) certificateName.append(issuerId).appendVersion(3) certificate = CertificateV2() certificate.setName(certificateName) # Set the MetaInfo. certificate.getMetaInfo().setType(ContentType.KEY) # One hour. certificate.getMetaInfo().setFreshnessPeriod(3600 * 1000.0) # Set the content. certificate.setContent(key.getPublicKey()) params = SigningInfo(key) # Validity period of 10 days. now = Common.getNowMilliseconds() params.setValidityPeriod( ValidityPeriod(now, now + 10 * 24 * 3600 * 1000.0)) self._keyChain.sign(certificate, params) return certificate
def main(): # Silence the warning from Interest wire encode. Interest.setDefaultCanBePrefix(True) # The default Face will connect using a Unix socket, or to "localhost". face = Face() counter = Counter() if sys.version_info[0] <= 2: word = raw_input("Enter a word to echo: ") else: word = input("Enter a word to echo: ") name = Name("/testecho") name.append(word) dump("Express name ", name.toUri()) face.expressInterest(name, counter.onData, counter.onTimeout) while counter._callbackCount < 1: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01) face.shutdown()
def _updateCapabilities(self): """ Send the controller a list of our commands. """ fullCommandName = Name( self._policyManager.getTrustRootIdentity()).append( 'updateCapabilities') capabilitiesMessage = UpdateCapabilitiesCommandMessage() for command in self._commands: commandName = Name(self.prefix).append(Name(command.suffix)) capability = capabilitiesMessage.capabilities.add() for i in range(commandName.size()): capability.commandPrefix.components.append( str(commandName.get(i).getValue())) for kw in command.keywords: capability.keywords.append(kw) capability.needsSignature = command.isSigned encodedCapabilities = ProtobufTlv.encode(capabilitiesMessage) fullCommandName.append(encodedCapabilities) interest = Interest(fullCommandName) interest.setInterestLifetimeMilliseconds(5000) self.face.makeCommandInterest(interest) signature = self._policyManager._extractSignature(interest) self.log.info("Sending capabilities to controller") self.face.expressInterest(interest, self._onCapabilitiesAck, self._onCapabilitiesTimeout) # update twice a minute self.loop.call_later(30, self._updateCapabilities)
def main(): face = Face() current_nbr = 1 max_nbr = 10 PGI = 5 f = open('measurements/app_measurments.txt','a') f.seek(0) f.truncate() cow = 0 v = 0 counter = Counter(f, face) while current_nbr <= max_nbr: name = Name("farm1/cows") name.append("1") name.append("mvmnt") name.appendSegment(v) interest = Interest(name) counter._callbackCount = 0 f.write('\n'+str(datetime.now().strftime('%X.%f'))) face.expressInterest(interest, counter.onData, counter.onTimeout) while counter._callbackCount < 1 : face.processEvents() time.sleep(0.01) time.sleep(PGI) current_nbr+=1 v+=1 face.shutdown() f.close()
def testNameAppendAndExtract(self): size = 10 iblt = InvertibleBloomLookupTable(size) prefix = Name("/test/memphis").appendNumber(1).toUri() newHash = Common.murmurHash3Blob(11, prefix) iblt.insert(newHash) expectedEncoding = [ 0x78, 0xda, 0x63, 0x64, 0x60, 0x60, 0xd8, 0x55, 0xb5, 0xfc, 0x5b, 0xb2, 0xef, 0xe2, 0x6c, 0x06, 0x0a, 0x00, 0x23, 0x1d, 0xcd, 0x01, 0x00, 0x65, 0x29, 0x0d, 0xb1 ] ibltName = Name("sync") encodedIblt = iblt.encode() self.assertTrue(encodedIblt.equals(Blob(expectedEncoding))) ibltName.append(encodedIblt) received = InvertibleBloomLookupTable(size) received.initialize(ibltName.get(-1).getValue()) self.assertTrue(iblt.equals(received)) receivedDifferentSize = InvertibleBloomLookupTable(20) try: receivedDifferentSize.initialize(ibltName.get(-1).getValue()) self.fail("Did not throw the expected exception") except RuntimeError: pass else: self.fail("Did not throw the expected exception")
def _updateCapabilities(self): """ Send the controller a list of our commands. """ fullCommandName = Name(self._policyManager.getTrustRootIdentity() ).append('updateCapabilities') capabilitiesMessage = UpdateCapabilitiesCommandMessage() for command in self._commands: commandName = Name(self.prefix).append(Name(command.suffix)) capability = capabilitiesMessage.capabilities.add() for i in range(commandName.size()): capability.commandPrefix.components.append( str(commandName.get(i).getValue())) for kw in command.keywords: capability.keywords.append(kw) capability.needsSignature = command.isSigned encodedCapabilities = ProtobufTlv.encode(capabilitiesMessage) fullCommandName.append(encodedCapabilities) interest = Interest(fullCommandName) interest.setInterestLifetimeMilliseconds(5000) self.face.makeCommandInterest(interest) signature = self._policyManager._extractSignature(interest) self.log.info("Sending capabilities to controller") self.face.expressInterest(interest, self._onCapabilitiesAck, self._onCapabilitiesTimeout) # update twice a minute self.loop.call_later(30, self._updateCapabilities)
def make_command(self, module, verb, **kwargs): name = Name('/localhost/nfd').append(module).append(verb) # Command Parameters cmd_param = ControlCommandMessage() if 'name' in kwargs: name_param = kwargs['name'] for compo in name_param: cmd_param.control_parameters.name.component.append(compo.getValue().toBytes()) if 'strategy' in kwargs: name_param = kwargs['strategy'] for compo in name_param: cmd_param.control_parameters.strategy.name.component.append(compo.getValue().toBytes()) for key in ['uri', 'local_uri']: if key in kwargs: setattr(cmd_param.control_parameters, key, kwargs[key].encode('utf-8')) for key in ['face_id', 'origin', 'cost', 'capacity', 'count', 'base_cong_mark', 'def_cong_thres', 'mtu', 'flags', 'mask', 'exp_period']: if key in kwargs: setattr(cmd_param.control_parameters, key, kwargs[key]) param_blob = ProtobufTlv.encode(cmd_param) name.append(Name.Component(param_blob)) # Command Interest Components ret = Interest(name) ret.canBePrefix = True self.face.makeCommandInterest(ret) return ret
def decode_name(name) -> str: """ Convert a Protobuf Name to uri """ ret = Name() for comp in name.component: ret.append(comp) return ret.toUri()
def handleExpressInterest(interest, onData, onTimeout, onNetworkNack): expressInterestCallCount[0] += 1 interestName = Name(interest.getName()) interestName.append(timeMarker) self.assertTrue(interestName in self.encryptionKeys) onData(interest, self.encryptionKeys[interestName]) return 0
def handleExpressInterest(interest, onData, onTimeout): expressInterestCallCount[0] += 1 interestName = Name(interest.getName()) interestName.append(timeMarker) self.assertTrue(interestName in self.encryptionKeys) onData(interest, self.encryptionKeys[interestName]) return 0
def main(): if len(sys.argv) < 2: print("usage: python3 client-app.py {good/bad}") quit() #Interest.setDefaultCanBePrefix(True) with open("shared/system-info.json") as f: user_data = json.load(f) face = Face() counter = Counter() name = Name("/ndn-ss/austin") req_name = "/example/test" sym_key = base64.b64decode(user_data['austin']['sym_key']) iv, ct, tag = sym_encrypt(sym_key, req_name) enc_req_name = base64.b64encode(iv).decode('ascii') name.append(enc_req_name) enc_req_name = base64.b64encode(ct).decode('ascii') name.append(enc_req_name) enc_req_name = base64.b64encode(tag).decode('ascii') name.append(enc_req_name) priv_key = user_data['austin']['priv_key'] priv_key = base64.b64decode(priv_key) priv_key = load_priv_key(priv_key) sig =\ base64.b64encode(priv_key.sign(bytes("austin",'utf-8'))).decode('ascii') bad_sig =\ base64.b64encode(priv_key.sign(bytes("abstin",'utf-8'))).decode('ascii') i = Interest() i.setMustBeFresh(True) i.setInterestLifetimeMilliseconds(0) #face.expressInterest(name,counter.onData,counter.onTimeout) if sys.argv[1] == "good": name.append(sig) face.expressInterest(name, i, counter.onData, counter.onTimeout) elif sys.argv[1] == "bad": name.append(bad_sig) face.expressInterest(name, i, counter.onData, counter.onTimeout) else: print("c") while counter.rec == 1: face.processEvents() time.sleep(0.1) face.expressInterest(name, i, counter.onData, counter.onTimeout)
def pingFace(srcFace, dstPrefix, iterNumber): print("Will ping from", srcFace, dstPrefix, "iterNumber:", iterNumber) face = faces[srcFace] name = Name(dstPrefix) name.append(Name(srcFace)) name.appendSequenceNumber(iterNumber) #print("name:", name) interest = Interest(name) face.expressInterest(interest, onData, onTimeout, onNack)
def createEncryptionKey(self, eKeyName, timeMarker): params = RsaKeyParams() eKeyName = Name(eKeyName) eKeyName.append(timeMarker) dKeyBlob = RsaAlgorithm.generateKey(params).getKeyBits() eKeyBlob = RsaAlgorithm.deriveEncryptKey(dKeyBlob).getKeyBits() self.decryptionKeys[eKeyName] = dKeyBlob keyData = Data(eKeyName) keyData.setContent(eKeyBlob) self.keyChain.sign(keyData, self.certificateName) self.encryptionKeys[eKeyName] = keyData
def createEncryptionKey(self, eKeyName, timeMarker): params = RsaKeyParams() eKeyName = Name(eKeyName) eKeyName.append(timeMarker) dKeyBlob = RsaAlgorithm.generateKey(params).getKeyBits() eKeyBlob = RsaAlgorithm.deriveEncryptKey(dKeyBlob).getKeyBits() self.decryptionKeys[eKeyName] = dKeyBlob keyData = Data(eKeyName) keyData.setContent(eKeyBlob) self.keyChain.sign(keyData, self.certificateName) self.encryptionKeys[eKeyName] = keyData
async def fetch_video_bytechunk(face: Face, cur_time: int): """ Fetch a video chunk named cur_time """ def after_fetched(data: Data): nonlocal recv_window, b_array, seq_to_bytes_unordered if not isinstance(data, Data): return try: seq = int(str(data.getName()).split('/')[-1]) except ValueError: logging.warning('Sequence number decoding error') return # Temporarily store out-of-order packets if seq <= recv_window: return elif seq == recv_window + 1: b_array.extend(data.getContent().toBytes()) # logging.warning('saved packet: seq {}'.format(seq)) recv_window += 1 while recv_window + 1 in seq_to_bytes_unordered: b_array.extend(seq_to_bytes_unordered[recv_window + 1]) seq_to_bytes_unordered.pop(recv_window + 1) # logging.warning('saved packet: seq {}'.format(recv_window + 1)) recv_window += 1 else: logging.info('Received out of order packet: seq {}'.format(seq)) seq_to_bytes_unordered[seq] = data.getContent().toBytes() recv_window = -1 b_array = bytearray() seq_to_bytes_unordered = dict() # Temporarily save out-of-order packets semaphore = asyncio.Semaphore(100) name = Name(VIDEO_STREAM_NAME) name.append(str(cur_time)) await fetch_segmented_data(face, name, start_block_id=0, end_block_id=None, semaphore=semaphore, after_fetched=after_fetched) if len(b_array) == 0: print('no data back') else: print('fetched video {}, {} bytes'.format(str(cur_time), len(b_array))) return b_array
def test_published_kdks(self): for user in self._fixture._userIdentities: kdkName = Name("/access/policy/identity/NAC/dataset/KDK") kdkName.append( self._fixture._nacIdentity.getDefaultKey().getName().get(-1)).append( "ENCRYPTED-BY").append( user.getDefaultKey().getName()) self._fixture._face.receive( Interest(kdkName).setCanBePrefix(True).setMustBeFresh(True)) self.assertTrue( self._fixture._face._sentData[0].getName().equals(kdkName), "Sent Data does not have the KDK name " + kdkName.toUri()) self._fixture._face._sentData = []
def test_typed_name_component(self): otherTypeCode = 99 uri = "/ndn/" + str(otherTypeCode) + "=value" name = Name() name.append("ndn").append("value", ComponentType.OTHER_CODE, otherTypeCode) self.assertEqual(uri, name.toUri()) nameFromUri = Name(uri) self.assertEqual("value", str(nameFromUri.get(1).getValue())) self.assertEqual(otherTypeCode, nameFromUri.get(1).getOtherTypeCode()) decodedName = Name() decodedName.wireDecode(name.wireEncode()) self.assertEqual("value", str(decodedName.get(1).getValue())) self.assertEqual(otherTypeCode, decodedName.get(1).getOtherTypeCode())
def test_append(self): # could possibly split this into different tests uri = "/localhost/user/folders/files/%00%0F" name = Name(uri) name2 = Name("/localhost").append(Name("/user/folders/")) self.assertEqual( len(name2), 3, 'Name constructed by appending names has ' + str(len(name2)) + ' components instead of 3') self.assertTrue(name2[2].getValue() == Blob("folders"), 'Name constructed with append has wrong suffix') name2 = name2.append("files") self.assertEqual( len(name2), 4, 'Name constructed by appending string has ' + str(len(name2)) + ' components instead of 4') name2 = name2.appendSegment(15) self.assertTrue( name2[4].getValue() == Blob(bytearray([0x00, 0x0F])), 'Name constructed by appending segment has wrong segment value') self.assertTrue( name2 == name, 'Name constructed with append is not equal to URI constructed name' ) self.assertEqual(name2.toUri(), name.toUri(), 'Name constructed with append has wrong URI')
def test_typed_name_component(self): otherTypeCode = 99 uri = "/ndn/" + str(otherTypeCode) + "=value" name = Name() name.append("ndn").append("value", ComponentType.OTHER_CODE, otherTypeCode) self.assertEqual(uri, name.toUri()) nameFromUri = Name(uri) self.assertEqual("value", str(nameFromUri.get(1).getValue())) self.assertEqual(otherTypeCode, nameFromUri.get(1).getOtherTypeCode()) decodedName = Name() decodedName.wireDecode(name.wireEncode()) self.assertEqual("value", str(decodedName.get(1).getValue())) self.assertEqual(otherTypeCode, decodedName.get(1).getOtherTypeCode())
def sendRepoInsertCommand(self, dataName): self.log.debug('Sending insert command for {}'.format(dataName)) commandMessage = RepoCommandParameterMessage() command = commandMessage.command for component in dataName: command.name.components.append(str(component.getValue())) command.start_block_id = command.end_block_id = 0 commandComponent = ProtobufTlv.encode(commandMessage) interestName = Name(self.repoPrefix).append('insert') interestName.append(commandComponent) interest = Interest(interestName) interest.setInterestLifetimeMilliseconds(4000) self.face.makeCommandInterest(interest) self.face.expressInterest(interest, self.onDataReceived, self.onTimeout)
def _updateDeviceCapabilities(self, interest): """ Take the received capabilities update interest and update our directory listings. """ # we assume the sender is the one who signed the interest... signature = self._policyManager._extractSignature(interest) certificateName = signature.getKeyLocator().getKeyName() senderIdentity = IdentityCertificate.certificateNameToPublicKeyName( certificateName).getPrefix(-1) self.log.info('Updating capabilities for {}'.format( senderIdentity.toUri())) # get the params from the interest name messageComponent = interest.getName().get(self.prefix.size() + 1) message = UpdateCapabilitiesCommandMessage() ProtobufTlv.decode(message, messageComponent.getValue()) # we remove all the old capabilities for the sender tempDirectory = defaultdict(list) for keyword in self._directory: tempDirectory[keyword] = [ cap for cap in self._directory[keyword] if not senderIdentity.match(Name(cap['name'])) ] # then we add the ones from the message for capability in message.capabilities: capabilityPrefix = Name() for component in capability.commandPrefix.components: capabilityPrefix.append(component) commandUri = capabilityPrefix.toUri() if not senderIdentity.match(capabilityPrefix): self.log.error( "Node {} tried to register another prefix: {} - ignoring update" .format(senderIdentity.toUri(), commandUri)) else: for keyword in capability.keywords: allUris = [info['name'] for info in tempDirectory[keyword]] if capabilityPrefix not in allUris: listing = { 'signed': capability.needsSignature, 'name': commandUri } tempDirectory[keyword].append(listing) self._directory = tempDirectory
def expressBootstrapInterest(self): #generate bootstrap name /home/controller/bootstrap/<device-parameters> bootstrapName = Name(self._bootstrapPrefix) deviceParameters = {} deviceParameters["category"] = self._deviceProfile.getCategory() deviceParameters["serialNumber"] = self. _deviceProfile.getSerialNumber() deviceParameters["type"] = self._deviceProfile.getType() bootstrapName.append(json.dumps(deviceParameters)) bootstrapInterest = Interest(bootstrapName) bootstrapInterest.setInterestLifetimeMilliseconds(3000) self._accessControlManager.signInterestWithHMACKey(bootstrapInterest,self._bootstrapKey) dump("Express bootstrap interest : ",bootstrapInterest.toUri()) self.face.expressInterest(bootstrapInterest, self.onBootstrapData, self.onBootstrapTimeout)
def test_operate_rsa_decryption_key(self): # Test construction. database = Sqlite3ConsumerDb(self.databaseFilePath) # Generate key blobs. (encryptionKeyBlob, decryptionKeyBlob) = generateRsaKeys() keyName = Name( "/alice/health/samples/activity/steps/D-KEY/20150928080000/20150928090000!") keyName.append(Name("FOR/test/member/KEY/123!")) database.addKey(keyName, decryptionKeyBlob) resultBlob = database.getKey(keyName) self.assertTrue(decryptionKeyBlob.equals(resultBlob)) database.deleteKey(keyName) resultBlob = database.getKey(keyName) self.assertEqual(0, resultBlob.size())
async def process_delete(self, interest: Interest): """ Process segmented delete command. """ try: parameter = self.decode_cmd_param_blob(interest) except RuntimeError as exc: logging.info('Parameter interest blob decode failed') return name = Name() for compo in parameter.repo_command_parameter.name.component: name.append(compo) start_block_id = parameter.repo_command_parameter.start_block_id start_block_id = start_block_id if start_block_id else 0 end_block_id = parameter.repo_command_parameter.end_block_id logging.info( 'Delete handle processing delete command: {}, {}, {}'.format( str(name), start_block_id, end_block_id)) # Reply to client with status code 100 process_id = random.randint(0, 0x7fffffff) self.m_processes[process_id] = RepoCommandResponseMessage() self.m_processes[process_id].repo_command_response.status_code = 100 self.m_processes[ process_id].repo_command_response.process_id = process_id self.m_processes[process_id].repo_command_response.delete_num = 0 self.reply_to_cmd(interest, self.m_processes[process_id]) # Perform delete delete_num = self.perform_delete(str(name), start_block_id, end_block_id) # TODO: because DB ops are blocking, there's no "300" state self.m_processes[process_id].repo_command_response.status_code = 200 self.m_processes[ process_id].repo_command_response.delete_num = delete_num self.reply_to_cmd(interest, self.m_processes[process_id]) # Delete process state after some time await self.delete_process(process_id)
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)
def on_command(self, _prefix, interest, _face, _interest_filter_id, _filter_obj): # type: (Name, Interest, Face, int, InterestFilter) -> None parameter_msg = SegmentParameterMessage() try: ProtobufTlv.decode(parameter_msg, interest.name[-1].getValue()) except ValueError: self.nodata_reply(interest.name, RET_MALFORMED_COMMAND) return parameter = parameter_msg.segment_parameter prefix = Name() for compo in parameter.name.component: prefix.append(compo.decode("utf-8")) # Check operations for op in parameter.operations.components: model_name = op.model.decode("utf-8") if model_name not in self.operations_set: self.nodata_reply(interest.name, RET_NOT_SUPPORTED) return # Fetch frames for frame_id in range(parameter.start_frame, parameter.end_frame + 1): frame_name = Name(prefix).append(str(frame_id)) for op in parameter.operations.components: model_name = op.model.decode("utf-8") data_name = Name(frame_name).append(model_name) logging.info("Request processed: %s", data_name) status = ResultStatus(prefix.toUri(), model_name, Common.getNowMilliseconds()) status.status = STATUS_FETCHING status.estimated_time = status.proecess_start_time + 10.0 self.save_status(data_name, status) # Check data existence and trigger fetching process for frame_id in range(parameter.start_frame, parameter.end_frame + 1): frame_name = Name(prefix).append(str(frame_id)) if self.storage.exists(frame_name): self.on_payload(frame_name) else: self.fetcher.fetch_data(frame_name) self.nodata_reply(interest.name, RET_OK, 10.0)
class Consumer(object): def __init__(self, prefix): self.prefix = Name(prefix) self.outstanding = dict() self.isDone = False self.face = Face() #event loop, running forever in this application def run(self): try: self._sendNextInterest( self.prefix.append(pyndn.Name.Component.fromSequenceNumber(1))) # self._sendNextInterest(self.prefix) while not self.isDone: self.face.processEvents() time.sleep(0.01) except RuntimeError as e: print("ERROR: %s" % e) def _sendNextInterest(self, name): interest = Interest(name) uri = name.toUri() interest.setInterestLifetimeMilliseconds(4000 * 100) interest.setMustBeFresh(False) if uri not in self.outstanding: self.outstanding[uri] = 1 self.face.expressInterest(interest, self._onData, self._onTimeout) print("Sent Interest for %s" % uri) def _onData(self, interest, data): payload = data.getContent() name = data.getName() print("Received data: ", payload.toRawStr()) del self.outstanding[name.toUri()] self.isDone = True def _onTimeout(self, interest): name = interest.getName() uri = name.toUri() print("TIMEOUT #%d: %s" % (self.outstanding[uri], uri)) self.outstanding[uri] += 1 if self.outstanding[uri] <= 3: self._sendNextInterest(name) else: self.isDone = True
def testEqual(self): size = 10 iblt1 = InvertibleBloomLookupTable(size) iblt2 = InvertibleBloomLookupTable(size) self.assertTrue(iblt1.equals(iblt2)) prefix = Name("/test/memphis").appendNumber(1).toUri() newHash = Common.murmurHash3Blob(11, prefix) iblt1.insert(newHash) iblt2.insert(newHash) self.assertTrue(iblt1.equals(iblt2)) ibfName1 = Name("/sync") ibfName2 = Name("/sync") ibfName1.append(iblt1.encode()) ibfName2.append(iblt2.encode()) self.assertTrue(ibfName1.equals(ibfName2))
def test_operate_rsa_decryption_key(self): # Test construction. database = Sqlite3ConsumerDb(self.databaseFilePath) # Generate key blobs. (encryptionKeyBlob, decryptionKeyBlob) = generateRsaKeys() keyName = Name( "/alice/health/samples/activity/steps/D-KEY/20150928080000/20150928090000!" ) keyName.append(Name("FOR/test/member/KEY/123!")) database.addKey(keyName, decryptionKeyBlob) resultBlob = database.getKey(keyName) self.assertTrue(decryptionKeyBlob.equals(resultBlob)) database.deleteKey(keyName) resultBlob = database.getKey(keyName) self.assertEqual(0, resultBlob.size())
def _addDeviceToNetwork(self, deviceSerial, newDeviceSuffix, pin): h = HmacHelper(pin) self._hmacDevices[deviceSerial] = h d = DeviceConfigurationMessage() for source, dest in [(self.networkPrefix, d.configuration.networkPrefix), (self.deviceSuffix, d.configuration.controllerName), (newDeviceSuffix, d.configuration.deviceSuffix)]: for i in range(source.size()): component = source.get(i) dest.components.append(component.getValue().toRawStr()) interestName = Name('/localhop/configure').append(Name(deviceSerial)) encodedParams = ProtobufTlv.encode(d) interestName.append(encodedParams) interest = Interest(interestName) h.signInterest(interest) self.face.expressInterest(interest, self._deviceAdditionResponse, self._deviceAdditionTimedOut)
def test_content_key_timeout(self): prefix = Name("/prefix") suffix = Name("/suffix") expectedInterest = Name(prefix) expectedInterest.append(Encryptor.NAME_COMPONENT_READ) expectedInterest.append(suffix) expectedInterest.append(Encryptor.NAME_COMPONENT_E_KEY) testTime = Schedule.fromIsoString("20150101T100001") timeoutCount = [0] # Prepare a TestFace to instantly answer calls to expressInterest. class TestFace(object): def __init__(self, handleExpressInterest): self.handleExpressInterest = handleExpressInterest def expressInterest(self, interest, onData, onTimeout): return self.handleExpressInterest(interest, onData, onTimeout) def handleExpressInterest(interest, onData, onTimeout): self.assertEqual(expectedInterest, interest.getName()) timeoutCount[0] += 1 onTimeout(interest) return 0 face = TestFace(handleExpressInterest) # Verify that if no response is received, the producer appropriately times # out. The result vector should not contain elements that have timed out. testDb = Sqlite3ProducerDb(self.databaseFilePath) producer = Producer(prefix, suffix, face, self.keyChain, testDb) def onEncryptedKeys(result): self.assertEqual(4, timeoutCount[0]) self.assertEqual(0, len(result)) producer.createContentKey(testTime, onEncryptedKeys)
def main(): # The default Face will connect using a Unix socket, or to "localhost". face = Face() counter = Counter() if sys.version_info[0] <= 2: word = raw_input("Enter a video name: ") else: word = input("Enter a video name: ") name = Name("/kebapp/video/") name.append(word) dump("Express name ", name.toUri()) face.expressInterest(name, counter.onData, counter.onTimeout) while counter._callbackCount < 1: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01) face.shutdown()
def createCheckInterest(self, fullName, checkNum): insertionName = Name(self.repoPrefix).append('insert check') commandParams = RepoCommandParameterMessage() interestName = Name(fullName) commandParams.repo_command_parameter.process_id = checkNum for i in range(interestName.size()): commandParams.repo_command_parameter.name.component.append(str(interestName.get(i).getValue())) commandName = insertionName.append(ProtobufTlv.encode(commandParams)) interest = Interest(commandName) return interest
def createCheckInterest(fullName, checkNum): insertionName = Name("/repotest/repo/insert check") commandParams = RepoCommandParameterMessage() interestName = Name(fullName) commandParams.repo_command_parameter.process_id = checkNum for i in range(interestName.size()): commandParams.repo_command_parameter.name.component.append(interestName.get(i).toEscapedString()) commandName = insertionName.append(ProtobufTlv.encode(commandParams)) interest = Interest(commandName) return interest
def _updateDeviceCapabilities(self, interest): """ Take the received capabilities update interest and update our directory listings. """ # we assume the sender is the one who signed the interest... signature = self._policyManager._extractSignature(interest) certificateName = signature.getKeyLocator().getKeyName() senderIdentity = IdentityCertificate.certificateNameToPublicKeyName(certificateName).getPrefix(-1) self.log.info('Updating capabilities for {}'.format(senderIdentity.toUri())) # get the params from the interest name messageComponent = interest.getName().get(self.prefix.size()+1) message = UpdateCapabilitiesCommandMessage() ProtobufTlv.decode(message, messageComponent.getValue()) # we remove all the old capabilities for the sender tempDirectory = defaultdict(list) for keyword in self._directory: tempDirectory[keyword] = [cap for cap in self._directory[keyword] if not senderIdentity.match(Name(cap['name']))] # then we add the ones from the message for capability in message.capabilities: capabilityPrefix = Name() for component in capability.commandPrefix.components: capabilityPrefix.append(component) commandUri = capabilityPrefix.toUri() if not senderIdentity.match(capabilityPrefix): self.log.error("Node {} tried to register another prefix: {} - ignoring update".format( senderIdentity.toUri(),commandUri)) else: for keyword in capability.keywords: allUris = [info['name'] for info in tempDirectory[keyword]] if capabilityPrefix not in allUris: listing = {'signed':capability.needsSignature, 'name':commandUri} tempDirectory[keyword].append(listing) self._directory= tempDirectory
def test_append(self): # could possibly split this into different tests uri = "/localhost/user/folders/files/%00%0F" name = Name(uri) name2 = Name("/localhost").append(Name("/user/folders/")) self.assertEqual(len(name2), 3, 'Name constructed by appending names has ' + str(len(name2)) + ' components instead of 3') self.assertTrue(name2[2].getValue() == Blob("folders"), 'Name constructed with append has wrong suffix') name2 = name2.append("files") self.assertEqual(len(name2), 4, 'Name constructed by appending string has ' + str(len(name2)) + ' components instead of 4') name2 = name2.appendSegment(15) self.assertTrue(name2[4].getValue() == Blob(bytearray([0x00, 0x0F])), 'Name constructed by appending segment has wrong segment value') self.assertTrue(name2 == name, 'Name constructed with append is not equal to URI constructed name') self.assertEqual(name2.toUri(), name.toUri(), 'Name constructed with append has wrong URI')
def createLightingCommand(self, color): interestName = Name(self.lightPrefix).append('setRGB') print "interest prefix", self.lightPrefix, type(self.lightPrefix) commandParams = LightCommandMessage() messageColor = commandParams.command.pattern.colors.add() messageColor.r = color[0] messageColor.g = color[1] messageColor.b = color[2] commandName = interestName.append(ProtobufTlv.encode(commandParams)) interest = Interest(commandName) return interest
def createCommandInterest(prefix="/testlight/setRGB", color=(255,0,128)): interestName = Name(prefix) commandParams = LightCommandMessage() messageColor = commandParams.command.pattern.colors.add() messageColor.r = color[0] messageColor.g = color[1] messageColor.b = color[2] commandName = interestName.append(ProtobufTlv.encode(commandParams)) interest = Interest(commandName) interest.setInterestLifetimeMilliseconds(2000) return interest
def _addDeviceToNetwork(self, deviceSerial, newDeviceSuffix, pin): h = HmacHelper(pin) self._hmacDevices[deviceSerial] = h d = DeviceConfigurationMessage() for source, dest in [ (self.networkPrefix, d.configuration.networkPrefix), (self.deviceSuffix, d.configuration.controllerName), (newDeviceSuffix, d.configuration.deviceSuffix) ]: for i in range(source.size()): component = source.get(i) dest.components.append(component.getValue().toRawStr()) interestName = Name('/home/configure').append(Name(deviceSerial)) encodedParams = ProtobufTlv.encode(d) interestName.append(encodedParams) interest = Interest(interestName) h.signInterest(interest) self.face.expressInterest(interest, self._deviceAdditionResponse, self._deviceAdditionTimedOut)
def test_register_prefix_response(self): # gotta sign it (WAT) prefixName = Name("/unittest") self.face_in.setCommandSigningInfo( self.keyChain, self.keyChain.getDefaultCertificateName()) failedCallback = Mock() interestCallback = Mock(side_effect=self.onInterestEffect) self.face_in.registerPrefix(prefixName, interestCallback, failedCallback) server = gevent.spawn(self.face_process_events, self.face_in, [interestCallback, failedCallback], 'h') gevent.sleep(1) # give the 'server' time to register the interest # express an interest on another face dataCallback = Mock() timeoutCallback = Mock() # now express an interest on this new face, and see if onInterest is called interestName = prefixName.append("hello") self.face_out.expressInterest(interestName, dataCallback, timeoutCallback) client = gevent.spawn(self.face_process_events, self.face_out, [dataCallback, timeoutCallback], 'c') gevent.joinall([server, client], timeout=10) self.assertEqual(failedCallback.call_count, 0, 'Failed to register prefix at all') self.assertEqual( interestCallback.call_count, 1, 'Expected 1 onInterest callback, got ' + str(interestCallback.call_count)) self.assertEqual( dataCallback.call_count, 1, 'Expected 1 onData callback, got ' + str(dataCallback.call_count)) onDataArgs = dataCallback.call_args[0] # check the message content data = onDataArgs[1] expectedBlob = Blob(bytearray("SUCCESS")) self.assertTrue( expectedBlob.equals(data.getContent()), 'Data received on face does not match expected format')
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 createInsertInterest(fullName): # we have to do the versioning when we poke the repo interestName = Name(fullName) logger.debug('Creating insert interest for: '+interestName.toUri()) insertionName = Name("/repotest/repo/insert") commandParams = RepoCommandParameterMessage() for i in range(interestName.size()): commandParams.repo_command_parameter.name.component.append(interestName.get(i).toEscapedString()) commandParams.repo_command_parameter.start_block_id = 0 commandParams.repo_command_parameter.end_block_id = 0 commandName = insertionName.append(ProtobufTlv.encode(commandParams)) interest = Interest(commandName) return interest
def test_producer_with_link(self): prefix = Name("/prefix") suffix = Name("/suffix") expectedInterest = Name(prefix) expectedInterest.append(Encryptor.NAME_COMPONENT_READ) expectedInterest.append(suffix) expectedInterest.append(Encryptor.NAME_COMPONENT_E_KEY) testTime = Schedule.fromIsoString("20150101T100001") timeoutCount = [0] # Prepare a TestFace to instantly answer calls to expressInterest. class TestFace(object): def __init__(self, handleExpressInterest): self.handleExpressInterest = handleExpressInterest def expressInterest(self, interest, onData, onTimeout, onNetworkNack): return self.handleExpressInterest(interest, onData, onTimeout, onNetworkNack) def handleExpressInterest(interest, onData, onTimeout, onNetworkNack): self.assertEqual(expectedInterest, interest.getName()) self.assertEqual(3, interest.getLink().getDelegations().size()) timeoutCount[0] += 1 onTimeout(interest) return 0 face = TestFace(handleExpressInterest) # Verify that if no response is received, the producer appropriately times # out. The result vector should not contain elements that have timed out. link = Link() link.addDelegation(10, Name("/test1")) link.addDelegation(20, Name("/test2")) link.addDelegation(100, Name("/test3")) self.keyChain.sign(link, self.certificateName) testDb = Sqlite3ProducerDb(self.databaseFilePath) producer = Producer(prefix, suffix, face, self.keyChain, testDb, 3, link) def onEncryptedKeys(result): self.assertEqual(4, timeoutCount[0]) self.assertEqual(0, len(result)) producer.createContentKey(testTime, onEncryptedKeys)
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 createInsertInterest(self, fullName): ''' For poking the repo ''' # we have to do the versioning before we poke the repo interestName = Name(fullName) logger.debug('Creating insert interest for: '+interestName.toUri()) insertionName = Name(self.repoPrefix).append('insert') commandParams = RepoCommandParameterMessage() for i in range(interestName.size()): commandParams.repo_command_parameter.name.component.append(interestName.get(i).getValue().toRawStr()) commandParams.repo_command_parameter.start_block_id = 0 commandParams.repo_command_parameter.end_block_id = 0 commandName = insertionName.append(ProtobufTlv.encode(commandParams)) interest = Interest(commandName) interest.setInterestLifetimeMilliseconds(2000) return interest
def test_register_prefix_response(self): # gotta sign it (WAT) prefixName = Name("/test") self.face_in.setCommandSigningInfo(self.keyChain, self.keyChain.getDefaultCertificateName()) failedCallback = Mock() interestCallback = Mock(side_effect=self.onInterestEffect) self.face_in.registerPrefix(prefixName, interestCallback, failedCallback) server = gevent.spawn(self.face_process_events, self.face_in, [interestCallback, failedCallback], 'h') time.sleep(1) # give the 'server' time to register the interest # express an interest on another face dataCallback = Mock() timeoutCallback = Mock() # now express an interest on this new face, and see if onInterest is called interestName = prefixName.append("hello") self.face_out.expressInterest(interestName, dataCallback, timeoutCallback) client = gevent.spawn(self.face_process_events, self.face_out, [dataCallback, timeoutCallback], 'c') gevent.joinall([server, client], timeout=10) self.assertEqual(failedCallback.call_count, 0, 'Failed to register prefix at all') self.assertEqual(interestCallback.call_count, 1, 'Expected 1 onInterest callback, got '+str(interestCallback.call_count)) self.assertEqual(dataCallback.call_count, 1, 'Expected 1 onData callback, got '+str(dataCallback.call_count)) onDataArgs = dataCallback.call_args[0] # check the message content data = onDataArgs[1] expectedBlob = Blob(bytearray("SUCCESS")) self.assertTrue(expectedBlob == data.getContent(), 'Data received on face does not match expected format')
def handleExpressInterest(interest, onData, onTimeout, onNetworkNack): self.assertEqual(expectedInterest, interest.getName()) gotInterestName = False for i in range(3): interestName = Name(interest.getName()) if i == 0: interestName.append(timeMarkerFirstHop) elif i == 1: interestName.append(timeMarkerSecondHop) elif i == 2: interestName.append(timeMarkerThirdHop) # matchesName will check the Exclude. if interest.matchesName(interestName): gotInterestName = True requestCount[0] += 1 break if gotInterestName: onData(interest, self.encryptionKeys[interestName]) return 0
def handleExpressInterest(interest, onData, onTimeout): self.assertEqual(expectedInterest, interest.getName()) gotInterestName = False for i in range(3): interestName = Name(interest.getName()) if i == 0: interestName.append(timeMarkerFirstHop) elif i == 1: interestName.append(timeMarkerSecondHop) elif i == 2: interestName.append(timeMarkerThirdHop) # matchesName will check the Exclude. if interest.matchesName(interestName): gotInterestName = True requestCount[0] += 1 break if gotInterestName: onData(interest, self.encryptionKeys[interestName]) return 0
def onBootstrapInterest(self, prefix, interest, transport, registeredPrefixId): if ( self._accessControlManager.verifyInterestWithHMACKey(interest, self._bootstrapKey) ): dump("Verified") interestName = interest.getName() deviceParameters = json.loads(interestName.get(3).getValue().toRawStr()) #create new identity for device #deviceNewIdentity = Name("home") deviceNewIdentity = Name("UA-cs-718") deviceNewIdentity.append(deviceParameters["category"]) deviceNewIdentity.append(deviceParameters["type"]) deviceNewIdentity.append(deviceParameters["serialNumber"]) seedSequence = 0 configurationTokenSequence = 0 seed = HMACKey(0,0,"seed","seedName") if (deviceNewIdentity.toUri() in self._deviceDict.keys()): dump("The device is already registered. No need to add again.") else: dump("Adding the new device...") self._newDevice["seed"] = seed #generate configuration token configurationTokenName = self._identity+"/"+str(configurationTokenSequence) configurationTokenKey = hmac.new(seed.getKey(), configurationTokenName, sha256).digest() configurationToken = HMACKey(configurationTokenSequence,0,configurationTokenKey,configurationTokenName) self._newDevice["configurationToken"] = configurationToken #generate content #TODO seed encryption content = {} content["deviceNewIdentity"] = deviceNewIdentity.toUri() content["controllerIdentity"] = self._identity content["seed"] = seed.getKey() content["seedSequence"] = seedSequence content["configurationTokenSequence"] = configurationTokenSequence #get public key of controller pKeyName = self._identityManager.getDefaultKeyNameForIdentity(self._identityManager.getDefaultIdentity()) pKey = self._identityManager.getPublicKey(pKeyName) pKeyInfo = content["controllerPublicKey"] = {} pKeyInfo["keyName"] = pKeyName.toUri() pKeyInfo["keyType"] = pKey.getKeyType() pKeyInfo["publicKeyDer"] = pKey.getKeyDer().toRawStr() dump("Sent content : ",content) #generate data package data = Data(interestName) data.setContent(json.dumps(content,encoding="latin-1")) self._accessControlManager.signDataWithHMACKey(data,self._bootstrapKey) self.sendData(data,transport,sign=False) #request for device profile #self.expressProfileRequest(deviceNewIdentity) else: self.log.info("Bootstrap interest not verified")
def test_content_asymmetric_encrypt_large(self): for input in encryptorRsaTestInputs: largeContent = Blob(bytearray([ 0x73, 0x5a, 0xbd, 0x47, 0x0c, 0xfe, 0xf8, 0x7d, 0x2e, 0x17, 0xaa, 0x11, 0x6f, 0x23, 0xc5, 0x10, 0x23, 0x36, 0x88, 0xc4, 0x2a, 0x0f, 0x9a, 0x72, 0x54, 0x31, 0xa8, 0xb3, 0x51, 0x18, 0x9f, 0x0e, 0x1b, 0x93, 0x62, 0xd9, 0xc4, 0xf5, 0xf4, 0x3d, 0x61, 0x9a, 0xca, 0x05, 0x65, 0x6b, 0xc6, 0x41, 0xf9, 0xd5, 0x1c, 0x67, 0xc1, 0xd0, 0xd5, 0x6f, 0x7b, 0x70, 0xb8, 0x8f, 0xdb, 0x19, 0x68, 0x7c, 0xe0, 0x2d, 0x04, 0x49, 0xa9, 0xa2, 0x77, 0x4e, 0xfc, 0x60, 0x0d, 0x7c, 0x1b, 0x93, 0x6c, 0xd2, 0x61, 0xc4, 0x6b, 0x01, 0xe9, 0x12, 0x28, 0x6d, 0xf5, 0x78, 0xe9, 0x99, 0x0b, 0x9c, 0x4f, 0x90, 0x34, 0x3e, 0x06, 0x92, 0x57, 0xe3, 0x7a, 0x8f, 0x13, 0xc7, 0xf3, 0xfe, 0xf0, 0xe2, 0x59, 0x48, 0x15, 0xb9, 0xdb, 0x77, 0x07, 0x1d, 0x6d, 0xb5, 0x65, 0x17, 0xdf, 0x76, 0x6f, 0xb5, 0x43, 0xde, 0x71, 0xac, 0xf1, 0x22, 0xbf, 0xb2, 0xe5, 0xd9, 0x22, 0xf1, 0x67, 0x76, 0x71, 0x0c, 0xff, 0x99, 0x7b, 0x94, 0x9b, 0x24, 0x20, 0x80, 0xe3, 0xcc, 0x06, 0x4a, 0xed, 0xdf, 0xec, 0x50, 0xd5, 0x87, 0x3d, 0xa0, 0x7d, 0x9c, 0xe5, 0x13, 0x10, 0x98, 0x14, 0xc3, 0x90, 0x10, 0xd9, 0x25, 0x9a, 0x59, 0xe9, 0x37, 0x26, 0xfd, 0x87, 0xd7, 0xf4, 0xf9, 0x11, 0x91, 0xad, 0x5c, 0x00, 0x95, 0xf5, 0x2b, 0x37, 0xf7, 0x4e, 0xb4, 0x4b, 0x42, 0x7c, 0xb3, 0xad, 0xd6, 0x33, 0x5f, 0x0b, 0x84, 0x57, 0x7f, 0xa7, 0x07, 0x73, 0x37, 0x4b, 0xab, 0x2e, 0xfb, 0xfe, 0x1e, 0xcb, 0xb6, 0x4a, 0xc1, 0x21, 0x5f, 0xec, 0x92, 0xb7, 0xac, 0x97, 0x75, 0x20, 0xc9, 0xd8, 0x9e, 0x93, 0xd5, 0x12, 0x7a, 0x64, 0xb9, 0x4c, 0xed, 0x49, 0x87, 0x44, 0x5b, 0x4f, 0x90, 0x34, 0x3e, 0x06, 0x92, 0x57, 0xe3, 0x7a, 0x8f, 0x13, 0xc7, 0xf3, 0xfe, 0xf0, 0xe2, 0x59, 0x48, 0x15, 0xb9, 0xdb, 0x77, 0x07, 0x1d, 0x6d, 0xb5, 0x65, 0x17, 0xdf, 0x76, 0x6f, 0xb5, 0x43, 0xde, 0x71, 0xac, 0xf1, 0x22, 0xbf, 0xb2, 0xe5, 0xd9 ]), False) data = Data() rsaParams = RsaKeyParams(1024) keyName = Name("test") decryptKey = RsaAlgorithm.generateKey(rsaParams) encryptKey = RsaAlgorithm.deriveEncryptKey(decryptKey.getKeyBits()) eKey = encryptKey.getKeyBits() dKey = decryptKey.getKeyBits() encryptParams = EncryptParams(input.type) Encryptor.encryptData(data, largeContent, keyName, eKey, encryptParams) self.assertTrue(data.getName().equals(Name("/FOR").append(keyName)), input.testName) largeDataContent = data.getContent() # largeDataContent is a sequence of the two EncryptedContent. encryptedNonce = EncryptedContent() encryptedNonce.wireDecode(largeDataContent) self.assertTrue(keyName.equals(encryptedNonce.getKeyLocator().getKeyName()), input.testName) self.assertEqual(encryptedNonce.getInitialVector().size(), 0, input.testName) self.assertEqual(encryptedNonce.getAlgorithmType(), input.type, input.testName) # Use the size of encryptedNonce to find the start of encryptedPayload. payloadContent = largeDataContent.buf()[encryptedNonce.wireEncode().size():] encryptedPayload = EncryptedContent() encryptedPayload.wireDecode(payloadContent) nonceKeyName = Name(keyName) nonceKeyName.append("nonce") self.assertTrue(nonceKeyName.equals(encryptedPayload.getKeyLocator().getKeyName()), input.testName) self.assertEqual(encryptedPayload.getInitialVector().size(), 16, input.testName) self.assertEqual(encryptedPayload.getAlgorithmType(), EncryptAlgorithmType.AesCbc, input.testName) self.assertEqual( largeDataContent.size(), encryptedNonce.wireEncode().size() + encryptedPayload.wireEncode().size(), input.testName) blobNonce = encryptedNonce.getPayload() nonce = RsaAlgorithm.decrypt(dKey, blobNonce, encryptParams) encryptParams.setAlgorithmType(EncryptAlgorithmType.AesCbc) encryptParams.setInitialVector(encryptedPayload.getInitialVector()) bufferPayload = encryptedPayload.getPayload() largePayload = AesAlgorithm.decrypt(nonce, bufferPayload, encryptParams) self.assertTrue(largeContent.equals(largePayload), input.testName)
class SongHandler: def __init__(self): self._device = "PC1" self._playPrefix = Name("/ndn/edu/ucla/remap/music/play") self.prefix = self._playPrefix.append(self._device) self._face = None self._loop = None self.thread = None self._keyChain = KeyChain() self._certificateName = self._keyChain.getDefaultCertificateName() self._repoCommandPrefix = "/example/repo/1" self.song = "" self.ftxt = "" self.ffreq = "" self.songList = "" self.mp = MusicPlayer() self.config = RawConfigParser() self.config.read('config.cfg') self.s = LightMessenger(self.config) self.q = Queue.Queue() def start(self): self._loop = asyncio.get_event_loop() self._face = ThreadsafeFace(self._loop,"") self._face.setCommandSigningInfo(self._keyChain, self._certificateName) self._face.registerPrefix(self.prefix, self.onPlayingCommand, self.onRegisterFailed) print "after register prefix" try: self._loop.run_forever() except KeyboardInterrupt: sys.exit() finally: self.stop() def stop(self): self._loop.close() self._face.shutdown() sys.exit(1) def playFunction(self): txt = open(self.ftxt) print "open txt successfully",self.ftxt #collect the onset duration osDur = [0.0] freq = [] data = [float(line.split()[0])for line in txt] for i in data: osDur.append(i) txt.close() txt = open(self.ffreq) print "open txt successfully",self.ffreq data = [float(line.split()[1])for line in txt] print "dasfdaaaa" for j in data: freq.append(j) avefq = int(sum(freq)/len(freq)) print avefq txt.close() g=(avefq-100)/10 r=avefq/30 b=(100-avefq)/10 startingColors = [int((15+r)/1.5),int((10+g)/1.5), int((10+b)/1.5)] for i in range(0,3): if startingColors[i]<0: startingColors[i]=6 #startingColors = [5,5,5] self.q.put(self.song+str("-music.mp3") ) print "MusicPlayer.isPlaying",MusicPlayer.isPlaying if not MusicPlayer.isPlaying: self.thread.start() #MusicPlayer.isPlaying = True self.s.start(osDur,startingColors) def getOnset(self): print "getonset" otxt = self.song+str("-o") print otxt g = GetFile(self._repoCommandPrefix, otxt, self._face, self.getFreq) g.oStream = open(self.song+str("-os.txt"),'wb') g.start() def getFreq(self): print "getfreq" ftxt = self.song+str("-f") g = GetFile(self._repoCommandPrefix, ftxt, self._face, self.playFunction) g.oStream = open(self.song+str("-freq.txt"),'wb') g.start() def signData(self, data): data.setSignature(Sha256WithRsaSignature()) 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 onRegisterFailed(self, prefix): self.log.error("Could not register " + prefix.toUri()) self.stop()
def createSongCommand(self,command): interestName = Name(self.listPrefix).append(self.device) interestName = interestName.append(command) interest = Interest(interestName) interest.setInterestLifetimeMilliseconds(4000) return interest
def test_parameters_sha256_digest(self): name = Name() digest = bytearray([ 0x28, 0xba, 0xd4, 0xb5, 0x27, 0x5b, 0xd3, 0x92, 0xdb, 0xb6, 0x70, 0xc7, 0x5c, 0xf0, 0xb6, 0x6f, 0x13, 0xf7, 0x94, 0x2b, 0x21, 0xe8, 0x0f, 0x55, 0xc0, 0xe8, 0x6b, 0x37, 0x47, 0x53, 0xa5, 0x48, 0x00, 0x00 ]) name.appendParametersSha256Digest(digest[0:32]) name.appendParametersSha256Digest(digest[0:32]) self.assertEqual(name.get(0), name.get(1)) gotError = True try: name.appendParametersSha256Digest(digest[0:34]) gotError = False except: pass if not gotError: self.fail("Expected error in appendParametersSha256Digest") gotError = True try: name.appendParametersSha256Digest(digest[0:30]) gotError = False except: pass if not gotError: self.fail("Expected error in appendParametersSha256Digest") # Add name.get(2) as a generic component. name.append(digest[0:32]) self.assertTrue(name.get(0).compare(name.get(2)) < 0) self.assertEqual(name.get(0).getValue(), name.get(2).getValue()) # Add name.get(3) as a generic component whose first byte is greater. name.append(digest[1:32]) self.assertTrue(name.get(0).compare(name.get(3)) < 0) self.assertEqual( name.get(0).toEscapedString(), "params-sha256=" + "28bad4b5275bd392dbb670c75cf0b66f13f7942b21e80f55c0e86b374753a548") self.assertEqual(name.get(0).isParametersSha256Digest(), True) self.assertEqual(name.get(2).isParametersSha256Digest(), False) gotError = True try: Name("/hello/params-sha256=hmm") gotError = False except: pass if not gotError: self.fail("Expected error in new Name from URI") # Check canonical URI encoding (lower case). name2 = Name( "/hello/params-sha256=" + "28bad4b5275bd392dbb670c75cf0b66f13f7942b21e80f55c0e86b374753a548") self.assertEqual(name.get(0), name2.get(1)) # Check that it will accept a hex value in upper case too. name2 = Name( "/hello/params-sha256=" + "28BAD4B5275BD392DBB670C75CF0B66F13F7942B21E80F55C0E86B374753A548") self.assertEqual(name.get(0), name2.get(1))
class SongHandler: def __init__(self): self._device = "PC1" self._playPrefix = Name("/ndn/edu/ucla/remap/music/play") self.prefix = self._playPrefix.append(self._device) self._face = None self._loop = None self._keyChain = KeyChain() self._certificateName = self._keyChain.getDefaultCertificateName() self._repoCommandPrefix = "/example/repo/1" self.mp = MusicPlayer() #self._getFiles = [] def start(self): self._loop = asyncio.get_event_loop() self._face = ThreadsafeFace(self._loop,"") self._face.setCommandSigningInfo(self._keyChain, self._certificateName) self._face.registerPrefix(self.prefix, self.onPlayingCommand, self.onRegisterFailed) try: self._loop.run_forever() except KeyboardInterrupt: sys.exit() finally: self.stop() def stop(self): self._loop.close() self._face.shutdown() sys.exit(1) def getOnset(self, musicName): otxt = musicName + str("-o") print otxt g = GetFile(self._repoCommandPrefix, otxt, self._face, self.getFreq, musicName) g.oStream = open(musicName + str("-os.txt"), 'wb') g.start() #self._getFiles.append(g) def getFreq(self, musicName): ftxt = musicName + str("-f") print musicName, " get Freq called" g = GetFile(self._repoCommandPrefix, ftxt, self._face, self.mp.play_music, musicName, False) g.oStream = open(musicName + str("-freq.txt"),'wb') g.start() #self._getFiles.append(g) def signData(self, data): data.setSignature(Sha256WithRsaSignature()) 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()) def onRegisterFailed(self, prefix): self.log.error("Could not register " + prefix.toUri()) self.stop()
def test_register_prefix_response(self): prefixName = Name("/test") self.face_in.setCommandSigningInfo(self.keyChain, self.keyChain.getDefaultCertificateName()) interestCallbackCount = [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()) failedCallback = Mock() self.face_in.registerPrefix(prefixName, onInterest, failedCallback) # Give the 'server' time to register the interest. time.sleep(1) # express an interest on another face dataCallback = Mock() timeoutCallback = Mock() # now express an interest on this new face, and see if onInterest is called # Add the timestamp so it is unique and we don't get a cached response. interestName = prefixName.append("hello" + repr(time.time())) self.face_out.expressInterest(interestName, dataCallback, timeoutCallback) # Process events for the in and out faces. timeout = 10000 startTime = getNowMilliseconds() while True: if getNowMilliseconds() - startTime >= timeout: break self.face_in.processEvents() self.face_out.processEvents() done = True if interestCallbackCount[0] == 0 and failedCallback.call_count == 0: # Still processing face_in. done = False if dataCallback.call_count == 0 and timeoutCallback.call_count == 0: # Still processing face_out. done = False if done: break time.sleep(0.01) self.assertEqual(failedCallback.call_count, 0, 'Failed to register prefix at all') self.assertEqual(interestCallbackCount[0], 1, 'Expected 1 onInterest callback, got '+str(interestCallbackCount[0])) self.assertEqual(dataCallback.call_count, 1, 'Expected 1 onData callback, got '+str(dataCallback.call_count)) onDataArgs = dataCallback.call_args[0] # check the message content data = onDataArgs[1] expectedBlob = Blob("SUCCESS") self.assertTrue(expectedBlob == data.getContent(), 'Data received on face does not match expected format')