def test_generic(): comp = b'\x08\x0andn-python' assert Component.get_type(comp) == Component.TYPE_GENERIC assert Component.to_str(comp) == 'ndn-python' assert Component.from_str('ndn-python') == comp assert Component.from_str('8=ndn-python') == comp comp = b"\x08\x07foo%bar" assert Component.to_str(comp) == "foo%25bar" assert Component.from_str('foo%25bar') == comp assert Component.from_str('8=foo%25bar') == comp comp = b'\x08\x04-._~' assert Component.to_str(comp) == "-._~" assert Component.from_str('-._~') == comp assert Component.from_str('8=-._~') == comp with pytest.raises(ValueError): Component.from_str(":/?#[]@") comp = Component.from_bytes(b':/?#[]@') assert Component.to_str(comp) == "%3A%2F%3F%23%5B%5D%40" assert Component.from_str("%3a%2f%3f%23%5b%5d%40") == comp with pytest.raises(ValueError): Component.from_str("/") assert Component.from_str('') == b'\x08\x00' assert Component.from_bytes(b'') == b'\x08\x00'
def test_other_types(): comp = b'\x09\x039\x3dA' assert Component.to_str(comp) == "9=9%3DA" assert Component.from_str('9%3DA') != comp assert Component.from_str('9=9%3DA') == comp comp = bytes.fromhex('FDFFFF00') assert Component.get_type(comp) == 0xffff assert Component.to_str(comp) == '65535=' comp = bytearray.fromhex('FD576501 2E') assert Component.get_type(comp) == 0x5765 assert Component.to_str(comp) == '22373=.'
def list_key_tree(self): """ Return the id-key-cert tree in a JSON like dict object. """ def get_key_type(key): key = bytes(key) try: RSA.import_key(key) return 'RSA' except ValueError: pass try: ECC.import_key(key) return 'ECC' except ValueError: pass return 'Unknown' sig_type_dic = { SignatureType.NOT_SIGNED: 'NotSigned', SignatureType.DIGEST_SHA256: 'DigestSha256', SignatureType.SHA256_WITH_RSA: 'SignatureSha256WithRsa', SignatureType.SHA256_WITH_ECDSA: 'SignatureSha256WithEcdsa', SignatureType.HMAC_WITH_SHA256: 'SignatureHmacWithSha256' } pib = self.app.keychain ret = {} for id_name, id_obj in pib.items(): cur_id = {'default': '*' if id_obj.is_default else ' ', 'keys': {}} for key_name, key_obj in id_obj.items(): cur_key = { 'default': '*' if key_obj.is_default else ' ', 'key_type': get_key_type(key_obj.key_bits), 'certs': {} } for cert_name, cert_obj in key_obj.items(): cert_v2 = parse_certificate(cert_obj.data) cur_cert = { 'default': '*' if cert_obj.is_default else ' ', 'not_before': bytes(cert_v2.signature_info.validity_period.not_before ).decode(), 'not_after': bytes(cert_v2.signature_info.validity_period.not_after ).decode(), 'issuer_id': Component.to_str(cert_v2.name[-2]), 'key_locator': Name.to_str(cert_v2.signature_info.key_locator.name), 'signature_type': sig_type_dic.get(cert_v2.signature_info.signature_type, 'Unknown') } cur_key['certs'][Name.to_str(cert_name)] = cur_cert cur_id['keys'][Name.to_str(key_name)] = cur_key ret[Name.to_str(id_name)] = cur_id return ret
def info_interest(name: FormalName, param: InterestParam, _app_param: Optional[BinaryStr]): print("Received interest for " + Name.to_str(name)) chunk = Component.to_str(name[-1]) if (chunk == 'file1'): app.put_data(name, content=json.dumps(file1_metadata).encode(), freshness_period=1) else: data = 'file1, chunk' + chunk app.put_data(name, content=data.encode() , freshness_period=100)
def sha256_tester(typ, uri_prefix): hex_text = '%28%ba%d4%b5%27%5b%d3%92%db%b6%70%c7%5c%f0%b6%6f%13%f7%94%2b%21%e8%0f%55%c0%e8%6b%37%47%53%a5%48' hex_lower = ''.join(hex_text.split('%')) hex_upper = hex_lower.upper() comp = Component.from_bytes(bytes.fromhex(hex_upper), typ=typ) assert Component.get_type(comp) == typ assert Component.to_str(comp) == uri_prefix + hex_lower assert Component.from_str(uri_prefix + hex_lower) == comp assert Component.from_str(uri_prefix + hex_upper) == comp
def test_invalid_type(): # 0-typed component is not checked in ndn-python assert Component.from_str("0=A") == b'\x00\x01A' with pytest.raises(struct.error): Component.from_str("-1=A") with pytest.raises(ValueError): Component.from_str("+=A") with pytest.raises(ValueError): Component.from_str("1=2=A") with pytest.raises(ValueError): Component.from_str("==A") with pytest.raises(ValueError): Component.from_str("%%") with pytest.raises(ValueError): Component.from_str("ABCD%EF%0") with pytest.raises(ValueError): Component.from_str("ABCD%GH") with pytest.raises(ValueError): Component.to_str(b'\x00\x01ABC') with pytest.raises(ValueError): Component.from_str('sha256digest=a04z')
async def _process_msg_interest(self, int_name, int_param, app_param): """ Async helper for ``_on_msg_interest()``. """ logging.debug(f'received msg interest: {Name.to_str(int_name)}') nonce = int(Component.to_str(int_name[-1])) # return data if corresponding nonce still exists if nonce in self.nonce_to_msg: self.app.put_data(int_name, self.nonce_to_msg[nonce]) logging.debug(f'reply msg with name {Name.to_str(int_name)}') else: logging.debug(f'no matching data with nonce {nonce} found')
def test_number(): assert Component.from_segment(13) == b'!\x01\r' assert Component.from_byte_offset(13) == b'\x22\x01\r' assert Component.from_sequence_num(13) == b'%\x01\r' assert Component.from_version(13) == b'#\x01\r' timeval = 15686790223318112 comp = Component.from_timestamp(timeval) assert Component.get_type(comp) == 36 assert Component.get_value(comp) == b'\x00\x37\xbb\x0d\x76\xed\x4c\x60' assert Component.to_number(comp) == timeval assert Component.to_str(Component.from_segment(13)) == 'seg=13' assert Component.to_str(Component.from_byte_offset(13)) == 'off=13' assert Component.to_str(Component.from_sequence_num(13)) == 'seq=13' assert Component.to_str(Component.from_version(13)) == 'v=13' assert Component.to_str( Component.from_timestamp(timeval)) == 't=15686790223318112' assert Component.from_str('seg=13') == b'!\x01\r' assert Component.from_str('off=13') == b'\x22\x01\r' assert Component.from_str('seq=13') == b'%\x01\r' assert Component.from_str('v=13') == b'#\x01\r' assert Component.from_str( 't=15686790223318112') == b'$\x08\x007\xbb\rv\xedL`'
def info_interest(name: FormalName, param: InterestParam, _app_param: Optional[BinaryStr]): print("Received interest for " + Name.to_str(name)) chunk = Component.to_str(name[-1]) data = 'File1/' + chunk app.put_data(name, content=data.encode(), freshness_period=100)
async def exec_ndn_ping(request): def decode_nack_reason(reason) -> str: codeset = { 0: 'NONE', 50: 'CONGESTION', 100: 'DUPLICATE', 150: 'NO_ROUTE' } if reason in codeset: return codeset[reason] else: return str(reason) def decode_content_type(content_type) -> str: codeset = ["BLOB", "LINK", "KEY", "NACK"] if content_type <= 3: return codeset[content_type] else: return str(content_type) def decode_signature_type(signature_type) -> str: codeset = [ "DIGEST_SHA256", "SHA256_WITH_RSA", "SHA256_WITH_ECDSA", "HMAC_WITH_SHA256" ] if signature_type <= 3: return codeset[signature_type] else: return str(content_type) signature_type = None async def validator(_, sig): nonlocal signature_type signature_type = sig.signature_info.signature_type return True nonlocal last_ping_data form = await request.post() name = form['name'] can_be_prefix = form['can_be_prefix'] == 'true' must_be_fresh = form['must_be_fresh'] == 'true' try: interest_lifetime = float(form['interest_lifetime']) * 1000.0 except ValueError: interest_lifetime = 4000.0 st_time = time.time() try: data_name, meta_info, data = await server.app.express_interest( name, validator=validator, lifetime=int(interest_lifetime), can_be_prefix=can_be_prefix, must_be_fresh=must_be_fresh) ed_time = time.time() response_time = '{:.3f}s'.format(ed_time - st_time) response_type = 'Data' name = Name.to_str(data_name) if meta_info.content_type is not None: content_type = decode_content_type(meta_info.content_type) else: content_type = "None" if meta_info.freshness_period is not None: freshness_period = "{:.3f}s".format( meta_info.freshness_period / 1000.0) else: freshness_period = "None" if meta_info.final_block_id is not None: final_block_id = Component.to_str(meta_info.final_block_id) else: final_block_id = "None" if signature_type: signature_type = decode_signature_type(signature_type) else: signature_type = "None" last_ping_data = bytes(data) return redirect('ndn_ping', request, response_time=response_time, response_type=response_type, name=name, content_type=content_type, freshness_period=freshness_period, final_block_id=final_block_id, signature_type=signature_type, download='/download/ping-data') except ValueError as e: logging.info("Illegal name") return redirect('ndn_ping', request, response_time='ERROR', response_type=str(e), name=name) except (InterestCanceled, ValidationFailure, NetworkError): logging.info("No response: ndn-peek") raise web.HTTPFound('/') except InterestNack as nack: ed_time = time.time() response_time = '{:.3f}s'.format(ed_time - st_time) response_type = 'NetworkNack' reason = decode_nack_reason(nack.reason) return redirect('ndn_ping', request, response_time=response_time, response_type=response_type, name=name, reason=reason) except InterestTimeout: ed_time = time.time() response_time = '{:.3f}s'.format(ed_time - st_time) response_type = 'Timeout' return redirect('ndn_ping', request, response_time=response_time, response_type=response_type, name=name)
def on_interest(name: FormalName, param: InterestParam, _app_param: Optional[BinaryStr]): print("Received interest") filename = Component.to_str(name[-1]) with open(filename + ".svf", 'r') as _file: content = _file.read() app.put_data(name, content=content.encode(), freshness_period=10000)