示例#1
0
def main():
    if len(sys.argv) <= 2:
        print(f'Usage: {sys.argv[0]} <name> <file>')
        exit(0)
    logging.basicConfig(format='[{asctime}]{levelname}:{message}',
                        datefmt='%Y-%m-%d %H:%M:%S',
                        level=logging.INFO,
                        style='{')

    app = NDNApp()
    name = Name.normalize(sys.argv[1])
    name.append(Component.from_version(timestamp()))

    with open(sys.argv[2], 'rb') as f:
        data = f.read()
        seg_cnt = (len(data) + SEGMENT_SIZE - 1) // SEGMENT_SIZE
        packets = [app.prepare_data(name + [Component.from_segment(i)],
                                    data[i*SEGMENT_SIZE:(i+1)*SEGMENT_SIZE],
                                    freshness_period=10000,
                                    final_block_id=Component.from_segment(seg_cnt - 1))
                   for i in range(seg_cnt)]
    print(f'Created {seg_cnt} chunks under name {Name.to_str(name)}')

    @app.route(name)
    def on_interest(int_name, _int_param, _app_param):
        if Component.get_type(int_name[-1]) == Component.TYPE_SEGMENT:
            seg_no = Component.to_number(int_name[-1])
        else:
            seg_no = 0
        if seg_no < seg_cnt:
            app.put_raw_packet(packets[seg_no])

    app.run_forever()
示例#2
0
async def main():
    try:
        timestamp = utils.timestamp()
        name = enc.Name.from_str('/example/testApp/randomData') + [
            enc.Component.from_timestamp(timestamp)
        ]
        print(
            f'Sending Interest {enc.Name.to_str(name)}, {enc.InterestParam(must_be_fresh=True, lifetime=6000)}'
        )
        # TODO: Write a better validator
        data_name, content, pkt_context = await app.express(
            name,
            validator=appv2.pass_all,
            must_be_fresh=True,
            can_be_prefix=False,
            lifetime=6000)

        print(f'Received Data Name: {enc.Name.to_str(data_name)}')
        print(pkt_context['meta_info'])
        print(bytes(content) if content else None)
    except types.InterestNack as e:
        print(f'Nacked with reason={e.reason}')
    except types.InterestTimeout:
        print(f'Timeout')
    except types.InterestCanceled:
        print(f'Canceled')
    except types.ValidationFailure:
        print(f'Data failed to validate')
    finally:
        app.shutdown()
示例#3
0
文件: handler.py 项目: zjkmxy/git_ndn
    def ref_list(self, name: FormalName, _param: InterestParam, _app_param: typing.Optional[BinaryStr]):
        ref_heads = self.repo.get_ref_heads()
        result = '\n'.join(f'{head.hex()} {ref}' for ref, head in ref_heads.items())
        result += '\n'
        logging.debug(f'On ref-list: {repr(result)}')

        data_name = name + [Component.from_timestamp(timestamp())]
        self.app.put_data(data_name, result.encode(), freshness_period=1000)
示例#4
0
 def on_interest(name, param, _app_param):
     print(f'>> I: {Name.to_str(name)}, {param}')
     content = "world!".encode()
     data_name = name + [Component.from_version(timestamp())]
     app.put_data(data_name, content=content, freshness_period=10000)
     print(f'<< D: {Name.to_str(data_name)}')
     print(f'Content: {content.decode()}')
     print('')
示例#5
0
 def on_interest(name, param, _app_param):
     print(f'>> I: {Name.to_str(name)}, {param}')
     content = "world!".encode()
     data_name = name + [Component.from_version(timestamp())]
     sign_cert_name = checker.suggest(data_name, app.keychain)
     print(f'        Suggested signing cert: {Name.to_str(sign_cert_name)}')
     app.put_data(data_name, content=content, freshness_period=10000, cert=sign_cert_name)
     print(f'<< D: {Name.to_str(data_name)}')
     print(f'Content: {content.decode()}')
     print('')
示例#6
0
    async def use_service(self, service: str, is_cmd: str, name_or_cmd: str,
                          param: str):
        """
        Use NDN-LITE service
            cmd interest name: /home/SERVICE/CMD/room/device-id/command
            notification interest name: /home/SERVICE/NOTIFY/CMD/room/device-id/command
            data fetching name: /home/SERVICE/DATA/room/device-id
        :param service: full service name, in the format of /home/SERVICE/room/device-id
        :param is_cmd: whether to send a command to the service
        :param name_or_cmd: the command id (if is_command is true) or the content-id (if is_cmd is false)
        :param param: content payload or command parameters
        :return: a dict object containing the state
        """
        service_name = Name.from_str(service)
        service_id = service_name[1][2]
        logging.debug(f'Use service: {str(service_id)}')
        encryption_key = None
        for service_meta in self.service_list.service_meta_items:
            if service_meta.service_id == service_id:
                encryption_key = service_meta.encryption_key
        if is_cmd == 'true':
            logging.debug(
                F'******Command publish timestamp: {int(round(time.time() * 1000))}'
            )
            service_name.insert(2, 'CMD')
            service_name = service_name + Name.from_str(name_or_cmd)
            service_name.append(Component.from_timestamp(timestamp()))
            notification_name = service_name[:]
            notification_name.insert(2, 'NOTIFY')

            need_register = False
            need_unregister = False
            if self.newly_pub_command is None:
                need_register = True
            elif Name.to_str(self.newly_pub_command[:3]) != Name.to_str(
                    service_name[:3]):
                need_register = True
                need_unregister = True

            if need_unregister:
                success = await self.app.unregister(self.newly_pub_command[:3])
                if not success:
                    logging.debug(
                        'cannot unregister prefix for command publish')

            self.newly_pub_command = service_name
            self.newly_pub_payload = param.encode()
            logging.debug(f'New pub info: {param}')
            logging.debug('Encryption Key: ')
            logging.debug(bytes(encryption_key))
            logging.debug('Plaintext: ')
            logging.debug(self.newly_pub_payload)
            # AES encryption
            iv = urandom(16)
            cipher = AES.new(bytes(encryption_key), AES.MODE_CBC, iv)
            ct_bytes = cipher.encrypt(pad(self.newly_pub_payload, 16))
            content_tlv = CipherBlock()
            content_tlv.iv = iv
            content_tlv.cipher = ct_bytes
            self.newly_pub_payload = content_tlv.encode()

            logging.info(
                F'Publish new content Data packet {Name.to_str(self.newly_pub_command)}'
            )

            if need_register:

                def on_service_fetch(name: FormalName,
                                     int_param: InterestParam,
                                     app_param: Optional[BinaryStr]):
                    logging.debug(
                        'received Interest to fetch newly published command')
                    self.app.put_data(self.newly_pub_command,
                                      self.newly_pub_payload,
                                      freshness_period=3000,
                                      identity=self.system_prefix)
                    return

                success = await self.app.register(service_name[:3],
                                                  on_service_fetch)
                if not success:
                    logging.debug('cannot register prefix for command publish')

            coroutine = self.app.express_interest(notification_name,
                                                  must_be_fresh=True,
                                                  can_be_prefix=True,
                                                  identity=self.system_prefix)
            ret = {
                'name': Name.to_str(service_name),
                'response_type': 'CommandPublished'
            }
        else:
            service_name.insert(2, 'DATA')
            service_name = service_name + Name.from_str(name_or_cmd)
            time1 = time.time()
            ret = await self.express_interest(service_name, None, True, True,
                                              False)
            time2 = time.time()
            logging.debug(
                F'******Data Fetching Round Trip Time: {time2 - time1}s******')
            if ret['response_type'] == 'Data':
                content = ret['content']
                content = CipherBlock.parse(content)
                iv = bytes(content.iv)
                cipher = AES.new(bytes(encryption_key), AES.MODE_CBC, iv)
                payload = cipher.decrypt(bytes(content.cipher))

                time2 = time.time()
                logging.debug(
                    F'******Data Fetching Finish Time: {time2 - time1}s******')

                payload = unpad(payload, 16)
                ret['content'] = payload.decode()
        return ret