Exemple #1
0
    def test_setters(self):
        certificate = CertificateV2()
        certificate.setName(
          Name("/ndn/site1/KEY/ksk-1416425377094/0123/%FD%00%00%01I%C9%8B"))
        certificate.getMetaInfo().setFreshnessPeriod(3600 * 1000.0)
        certificate.setContent(Blob(PUBLIC_KEY, False))
        certificate.setSignature(self.generateFakeSignature())

        self.assertEqual(
          Name("/ndn/site1/KEY/ksk-1416425377094/0123/%FD%00%00%01I%C9%8B"),
          certificate.getName())
        self.assertEqual(Name("/ndn/site1/KEY/ksk-1416425377094"),
          certificate.getKeyName())
        self.assertEqual(Name("/ndn/site1"), certificate.getIdentity())
        self.assertEqual(Name.Component("0123"), certificate.getIssuerId())
        self.assertEqual(Name.Component("ksk-1416425377094"),
          certificate.getKeyId())
        self.assertEqual(Name("/ndn/site1/KEY/ksk-2516425377094"),
          KeyLocator.getFromSignature(certificate.getSignature()).getKeyName())
        self.assertEqual(fromIsoString("20141111T050000"),
          certificate.getValidityPeriod().getNotBefore(), 0)
        self.assertEqual(fromIsoString("20141111T060000"),
          certificate.getValidityPeriod().getNotAfter(), 0)

        try:
          certificate.getPublicKey()
        except:
          self.fail("Error in getPublicKey");
Exemple #2
0
    def test_constructor(self):
        certificate = CertificateV2()
        certificate.wireDecode(Blob(CERT, False))

        self.assertEqual(
          Name("/ndn/site1/KEY/ksk-1416425377094/0123/%FD%00%00%01I%C9%8B"),
          certificate.getName())
        self.assertEqual(Name("/ndn/site1/KEY/ksk-1416425377094"),
          certificate.getKeyName())
        self.assertEqual(Name("/ndn/site1"), certificate.getIdentity())
        self.assertEqual(Name.Component("0123"), certificate.getIssuerId())
        self.assertEqual(Name.Component("ksk-1416425377094"),
          certificate.getKeyId())
        self.assertEqual(Name("/ndn/site1/KEY/ksk-2516425377094"),
          KeyLocator.getFromSignature(certificate.getSignature()).getKeyName())
        self.assertEqual(fromIsoString("20150814T223739"),
          certificate.getValidityPeriod().getNotBefore(), 0)
        self.assertEqual(fromIsoString("20150818T223738"),
          certificate.getValidityPeriod().getNotAfter(), 0)

        try:
          certificate.getPublicKey()
        except:
          self.fail("Error in getPublicKey");

        data = Data()
        data.wireDecode(Blob(CERT, False))
        certificate2 = CertificateV2(data)
        self.assertEqual(certificate.getName(), certificate2.getName())
        self.assertTrue(certificate.getPublicKey().equals(certificate2.getPublicKey()))
Exemple #3
0
    def onPlayingCommand(self, prefix, interest, transport, prefixId):

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

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

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

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

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

            #self._getFiles.append(g)

        d = Data(interest.getName())
        d.setContent("start to play: " + songName + "\n")
        encodedData = d.wireEncode()
        transport.send(encodedData.toBuffer())
Exemple #4
0
    def signInterest(self, interest, keyName=None, wireFormat=None):
        # Adds the nonce and timestamp here, because there is no
        # 'makeCommandInterest' call for this yet
        nonceValue = bytearray(8)
        for i in range(8):
            nonceValue[i] = self.random.randint(0, 0xff)
        timestampValue = bytearray(8)
        ts = int(timestamp() * 1000)
        for i in range(8):
            byte = ts & 0xff
            timestampValue[-(i + 1)] = byte
            ts = ts >> 8

        if wireFormat is None:
            wireFormat = WireFormat.getDefaultWireFormat()

        s = HmacWithSha256Signature()
        s.getKeyLocator().setType(KeyLocatorType.KEYNAME)
        s.getKeyLocator().setKeyName(keyName)

        interestName = interest.getName()
        interestName.append(nonceValue).append(timestampValue)
        interestName.append(wireFormat.encodeSignatureInfo(s))
        interestName.append(Name.Component())

        encoding = interest.wireEncode(wireFormat)
        signer = hmac.new(self.key, encoding.toSignedBuffer(), sha256)

        s.setSignature(Blob(signer.digest()))
        interest.setName(
            interestName.getPrefix(-1).append(
                wireFormat.encodeSignatureValue(s)))
Exemple #5
0
    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
Exemple #6
0
    def __init__(self, prefix="/ndn/edu/ucla/remap/music/list"):

        logging.basicConfig()
        '''#这些log是干嘛的myIP="192.168.1.1",lightIP="192.168.1.50",
        self.log = logging.getLogger("RegisterSongList")
        self.log.setLevel(logging.DEBUG)
        sh = logging.StreamHandler()
        sh.setLevel(logging.DEBUG)
        self.log.addHandler(sh)
        fh = logging.FileHandler("RegisterSongList.log")
        fh.setLevel(logging.INFO)
        self.log.addHandler(fh)'''
        self.device = "PC3"
        self.deviceComponent = Name.Component(self.device)
        self.excludeDevice = None
        #self.songList = originalList

        #security?
        self.prefix = Name(prefix)
        self.changePrefix = Name("/ndn/edu/ucla/remap/music/storage")
        self.keychain = KeyChain()
        self.certificateName = self.keychain.getDefaultCertificateName()

        self.address = ""
        self._isStopped = True
Exemple #7
0
    async def send_cmd_interest(self):
        event_loop = asyncio.get_event_loop()
        face_task = event_loop.create_task(self.face_loop())

        parameter = RepoCommandParameterMessage()
        for compo in self.prefix:
            parameter.repo_command_parameter.name.component.append(compo.getValue().toBytes())
        parameter.repo_command_parameter.start_block_id = self.latest_tp
        parameter.repo_command_parameter.end_block_id = parameter.repo_command_parameter.start_block_id
        param_blob = ProtobufTlv.encode(parameter)

        # Prepare cmd interest
        name = Name(self.repo_name).append("insert").append(Name.Component(param_blob))
        interest = Interest(name)
        interest.canBePrefix = True
        self.face.makeCommandInterest(interest)

        logging.info("Express interest: {}".format(interest.getName()))
        ret = await fetch_data_packet(self.face, interest)

        if not isinstance(ret, Data):
            logging.warning("Insertion failed")
        else:
            # Parse response
            response = RepoCommandResponseMessage()
            try:
                ProtobufTlv.decode(response, ret.content)
                logging.info('Insertion command accepted: status code {}'
                             .format(response.repo_command_response.status_code))
            except RuntimeError as exc:
                logging.warning('Response decoding failed', exc)
    async def _check(self, method: str, repo_name: str, process_id: int) -> RepoCommandResponseMessage:
        """
        Return parsed insert check response message.
        """
        parameter = RepoCommandParameterMessage()
        parameter.repo_command_parameter.process_id = process_id
        param_blob = ProtobufTlv.encode(parameter)

        name = Name(repo_name).append(method + ' check').append(Name.Component(param_blob))
        interest = Interest(name)
        interest.canBePrefix = True
        interest.setInterestLifetimeMilliseconds(1000)
        self.face.makeCommandInterest(interest)

        logging.info('Send ' + method + 'check interest')
        ret = await fetch_data_packet(self.face, interest)

        if not isinstance(ret, Data):
            logging.warning('Check error')
            return None
        try:
            response = self.decode_cmd_response_blob(ret)
        except RuntimeError as exc:
            logging.warning('Response blob decoding failed')
            return None
        return response
Exemple #9
0
def requestInsert(face, repoCommandPrefix, fetchName, onInsertStarted, onFailed,
      startBlockId = None, endBlockId = None):
    """
    Send a command interest for the repo to fetch the given fetchName and insert
    it in the repo.
    Since this calls expressInterest, your application must call face.processEvents.

    :param Face face: The Face used to call makeCommandInterest and expressInterest.
    :param Name repoCommandPrefix: The repo command prefix.
    :param Name fetchName: The name to fetch. If startBlockId and endBlockId are
      supplied, then the repo will request multiple segments by appending the
      range of block IDs (segment numbers).
    :param onInsertStarted: When the request insert command successfully returns,
      this calls onInsertStarted().
    :type onInsertStarted: function object
    :param onFailed: If the command fails for any reason, this prints an error
      and calls onFailed().
    :type onFailed: function object
    :param int startBlockId: (optional) The starting block ID (segment number)
      to fetch.
    :param int endBlockId: (optional) The end block ID (segment number)
      to fetch.
    """
    # repo_command_parameter_pb2 was produced by protoc.
    parameter = repo_command_parameter_pb2.RepoCommandParameterMessage()
    # Add the Name.
    for i in range(fetchName.size()):
        parameter.repo_command_parameter.name.component.append(
          fetchName[i].getValue().toBytes())
    # Add startBlockId and endBlockId if supplied.
    if startBlockId != None:
        parameter.repo_command_parameter.start_block_id = startBlockId
    if endBlockId != None:
        parameter.repo_command_parameter.end_block_id = endBlockId

    # Create the command interest.
    interest = Interest(Name(repoCommandPrefix).append("insert")
      .append(Name.Component(ProtobufTlv.encode(parameter))))
    face.makeCommandInterest(interest)

    # Send the command interest and get the response or timeout.
    def onData(interest, data):
        # repo_command_response_pb2 was produced by protoc.
        response = repo_command_response_pb2.RepoCommandResponseMessage()
        try:
            ProtobufTlv.decode(response, data.content)
        except:
            dump("Cannot decode the repo command response")
            onFailed()

        if response.repo_command_response.status_code == 100:
            onInsertStarted()
        else:
            dump("Got repo command error code", response.repo_command_response.status_code)
            onFailed()
    def onTimeout(interest):
        dump("Insert repo command timeout")
        onFailed()
    face.expressInterest(interest, onData, onTimeout)
Exemple #10
0
    def test_looped_certificate_chain(self):
        identity1 = self._fixture.addIdentity(Name("/loop"))
        key1 = self._fixture._keyChain.createKey(
            identity1, RsaKeyParams(Name.Component("key1")))
        key2 = self._fixture._keyChain.createKey(
            identity1, RsaKeyParams(Name.Component("key2")))
        key3 = self._fixture._keyChain.createKey(
            identity1, RsaKeyParams(Name.Component("key3")))

        self.makeCertificate(key1, key2)
        self.makeCertificate(key2, key3)
        self.makeCertificate(key3, key1)

        data = Data(Name("/loop/Data"))
        self._fixture._keyChain.sign(data, SigningInfo(key1))
        self.validateExpectFailure(
            data, "Should fail since the certificate chain loops")
        self.assertEqual(3, len(self._fixture._face._sentInterests))
Exemple #11
0
 def load_status(self, name):
     """Load status from database"""
     # Get exact prefix to data
     if name[-1] == Name.Component("_meta") or name[-1].isSegment():
         name = name[:-1]
     ret = self.storage.get(Name(STATUS_PREFIX).append(name))
     if ret is not None:
         return ResultStatus.from_bytes(ret)
     else:
         return None
Exemple #12
0
 def onDeviceResponse(interest, data):
     updatedInterest = Interest(interest)
     deviceSerial = str(data.getContent())
     if len(deviceSerial) > 0:
         foundDevices.append(deviceSerial)
         updatedInterest.getExclude().appendComponent(
             Name.Component(deviceSerial))
     # else ignore the malformed response
     self.face.expressInterest(updatedInterest, onDeviceResponse,
                               onDeviceTimeout)
def setNameComponent(interest, index, component):
    """
    :param Interest interest:
    :param int index:
    :param component:
    :type component: Blob or Name.Component or value for Blob constructor
    """
    name = interest.getName().getPrefix(index)
    name.append(Name.Component(component))
    name.append(interest.getName().getSubName(name.size()))
    interest.setName(name)
Exemple #14
0
    async def run(self, repo_name: str, prefix: str, start_block_id: int,
                  end_block_id: int):
        """
        Send a delete command to remove all the data within [start_block_id, end_block_id].
        """
        # Send command interest
        prefix = Name(prefix)
        parameter = RepoCommandParameterMessage()
        for compo in prefix:
            parameter.repo_command_parameter.name.component.append(
                compo.getValue().toBytes())
        parameter.repo_command_parameter.start_block_id = start_block_id
        parameter.repo_command_parameter.end_block_id = end_block_id
        param_blob = ProtobufTlv.encode(parameter)

        name = Name(repo_name).append('delete').append(
            Name.Component(param_blob))
        interest = Interest(name)
        self.face.makeCommandInterest(interest)

        logging.info('Send delete command interest')
        ret = await fetch_data_packet(self.face, interest)

        # Parse response
        if not isinstance(ret, Data):
            logging.warning('Delete error')
            return
        response = RepoCommandResponseMessage()
        try:
            ProtobufTlv.decode(response, ret.content)
        except RuntimeError as exc:
            logging.warning('Response decoding failed', exc)
        process_id = response.repo_command_response.process_id
        status_code = response.repo_command_response.status_code

        logging.info('Delete process {} accepted, status {}'.format(
            process_id, status_code))

        # Use delete check command to probe if delete process is completed
        checker = CommandChecker(self.face, self.keychain)
        while True:
            response = await checker.check_delete(repo_name, process_id)
            if response.repo_command_response.status_code == 300:
                await asyncio.sleep(1)
            elif response.repo_command_response.status_code == 200:
                logging.info(
                    'Delete process {} status: {}, delete_num: {}'.format(
                        process_id, response.repo_command_response.status_code,
                        response.repo_command_response.delete_num))
                break
            else:
                # Shouldn't get here
                assert (False)
Exemple #15
0
    async def insert_segmented_file(self):
        event_loop = asyncio.get_event_loop()
        face_task = event_loop.create_task(self.face_loop())

        parameter = RepoCommandParameterMessage()
        for compo in self.name_at_repo:
            parameter.repo_command_parameter.name.component.append(
                compo.getValue().toBytes())
        parameter.repo_command_parameter.start_block_id = 0
        parameter.repo_command_parameter.end_block_id = self.n_packets - 1
        param_blob = ProtobufTlv.encode(parameter)

        # Prepare cmd interest
        name = Name(self.repo_name).append('insert').append(
            Name.Component(param_blob))
        interest = Interest(name)
        self.face.makeCommandInterest(interest)

        logging.info('Send insert command interest')
        ret = await fetch_data_packet(self.face, interest)

        if not isinstance(ret, Data):
            logging.warning('Insert failed')
            return

        response = RepoCommandResponseMessage()
        try:
            ProtobufTlv.decode(response, ret.content)
        except RuntimeError as exc:
            logging.warning('Response decoding failed', exc)
        process_id = response.repo_command_response.process_id
        status_code = response.repo_command_response.status_code
        logging.info('Insertion process {} accepted: status code {}'.format(
            process_id, status_code))

        # Use insert check command to probe if insert process is completed
        checker = CommandChecker(self.face, self.keychain)
        while True:
            response = await checker.check_insert(self.repo_name, process_id)
            if response is None or response.repo_command_response.status_code == 300:
                await asyncio.sleep(1)
            elif response.repo_command_response.status_code == 200:
                logging.info(
                    'Insert process {} status: {}, insert_num: {}'.format(
                        process_id, response.repo_command_response.status_code,
                        response.repo_command_response.insert_num))
                break
            else:
                # Shouldn't get here
                assert (False)
        self.running = False
        await face_task
Exemple #16
0
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    if sys.version_info[0] <= 2:
        userName = raw_input("Enter your user name (e.g. \"a\" or \"b\"): ")
    else:
        userName = input("Enter your user name (e.g. \"a\" or \"b\"): ")
    if userName == "":
        dump("You must enter a user name")
        return

    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    # Use the system default key chain and certificate name to sign.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    applicationPrefix = Namespace(Name("/test/app"), keyChain)
    applicationPrefix.setFace(face,
      lambda prefix: dump("Register failed for prefix", prefix))
    applicationPrefix.enableSync()

    userPrefix = applicationPrefix[Name.Component(userName)]

    def onStateChanged(nameSpace, changedNamespace, state, callbackId):
        if (state == NamespaceState.NAME_EXISTS and
             not userPrefix.name.isPrefixOf(changedNamespace.name)):
            dump("Received", changedNamespace.name.toUri())

    applicationPrefix.addOnStateChanged(onStateChanged)

    publishIntervalMs = 1000.0
    component = Name("/%00").get(0)

    # Loop, producing a new name every publishIntervalMs milliseconds (and also
    # calling processEvents()).
    previousPublishMs = 0.0
    while True:
        now = Common.getNowMilliseconds()
        if now >= previousPublishMs + publishIntervalMs:
            # If userName is "a", this makes /test/app/a/%00, /test/app/a/%01, etc.
            newNamespace = userPrefix[component]
            dump("Publish", newNamespace.name.toUri())
            component = component.getSuccessor()

            previousPublishMs = now

        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Exemple #17
0
    def getChild(self, nameOrComponent):
        """
        Get a child (or descendant), creating it if needed. This is equivalent
        to namespace[component]. If a child is created, this calls callbacks as
        described by addOnNameAdded (but does not call the callbacks when
        creating intermediate nodes).

        :param nameOrComponent: If this is a Name, find or create the descendant
          node with the name (which must have this node's name as a prefix).
          Otherwise, this is the name component of the immediate child.
        :type nameOrComponent: Name or Name.Component or value for the
          Name.Component constructor
        :return: The child Namespace object. If nameOrComponent is a Name which
          equals the name of this Namespace, then just return this Namespace.
        :rtype: Namespace
        :raises RuntimeError: If the name of this Namespace node is not a prefix
          of the given Name.
        """
        if isinstance(nameOrComponent, Name):
            descendantName = nameOrComponent
            if not self._name.isPrefixOf(descendantName):
                raise RuntimeError(
                    "The name of this node is not a prefix of the descendant name"
                )

            # Find or create the child node whose name equals the descendantName.
            # We know descendantNamespace is a prefix, so we can just go by
            # component count instead of a full compare.
            descendantNamespace = self
            while descendantNamespace._name.size() < descendantName.size():
                nextComponent = descendantName[
                    descendantNamespace._name.size()]
                if nextComponent in descendantNamespace._children:
                    descendantNamespace = descendantNamespace._children[
                        nextComponent]
                else:
                    # Only fire the callbacks for the leaf node.
                    isLeaf = (descendantNamespace._name.size() ==
                              descendantName.size() - 1)
                    descendantNamespace = descendantNamespace._createChild(
                        nextComponent, isLeaf)

            return descendantNamespace
        else:
            component = nameOrComponent
            if not isinstance(component, Name.Component):
                component = Name.Component(component)

            if component in self._children:
                return self._children[component]
            else:
                return self._createChild(component, True)
Exemple #18
0
    def hasChild(self, component):
        """
        Check if this node in the namespace has the given child.

        :param component: The name component of the child.
        :type component: Name.Component or value for the Name.Component constructor
        :return: True if this has a child with the name component.
        :rtype: bool
        """
        if not isinstance(component, Name.Component):
            component = Name.Component(component)

        return component in self._children
Exemple #19
0
    def onReadPir(self, interest):
        # try to find a matching pir
        pirInfo = next((pair[1] for pair in self._pirs.items()
                        if Name(pair[1]["device"]).match(interest.getName())),
                       None)

        if pirInfo is None:
            data = Data(interest.getName())
            data.setContent("MALFORMED COMMAND")
            data.getMetaInfo().setFreshnessPeriod(
                1000)  # 1 second, in milliseconds
            return data

        lastTime = pirInfo["lastTime"]
        lastValue = pirInfo["lastVal"]

        # If interest exclude doesn't match timestamp from last tx'ed data
        # then resend data
        if not interest.getExclude().matches(Name.Component(str(lastTime))):
            print "Received interest without exclude ACK:", interest.getExclude(
            ).toUri()
            print "\tprevious timestamp:", str(lastTime)

            data = Data(Name(interest.getName()).append(str(lastTime)))
            payload = {"pir": lastValue}
            content = json.dumps(payload)
            data.setContent(content)

            data.getMetaInfo().setFreshnessPeriod(
                1000)  # 1 second, in milliseconds

            print "Sent data:", data.getName().toUri(), "with content", content
            return data

        # otherwise, make new data
        currentValue = pirInfo["device"].read()
        timestamp = int(time.time() * 1000)  # in milliseconds
        pirInfo["lastTime"] = timestamp
        pirInfo["lastVal"] = currentValue

        data = Data(Name(interest.getName()).append(str(timestamp)))

        payload = {"pir": currentValue}
        content = json.dumps(payload)
        data.setContent(content)

        data.getMetaInfo().setFreshnessPeriod(
            1000)  # 1 second, in milliseconds

        print "Sent data:", data.getName().toUri(), "with content", content
        return data
Exemple #20
0
    def __init__(self, prefix="/ndn/edu/ucla/remap/music/list"):

        logging.basicConfig()
        self.device = "PC1"
        self.deviceComponent = Name.Component(self.device)
        self.excludeDevice = None

        self.prefix = Name(prefix)
        self.changePrefix = Name("/ndn/edu/ucla/remap/music/storage")
        self.keychain = KeyChain()
        self.certificateName = self.keychain.getDefaultCertificateName()

        self.address = ""
        self._isStopped = True
def stopRepoWatch(face, repoCommandPrefix, watchPrefix, onRepoWatchStopped,
                  onFailed):
    """
    Send a command interest for the repo to stop watching the given watchPrefix.
    Since this calls expressInterest, your application must call face.processEvents.

    :param Face face: The Face used to call makeCommandInterest and expressInterest.
    :param Name repoCommandPrefix: The repo command prefix.
    :param Name watchPrefix: The prefix that the repo will stop watching.
    :param onRepoWatchStopped: When the stop watch command successfully returns,
      this calls onRepoWatchStopped().
    :type onRepoWatchStopped: function object
    :param onFailed: If the command fails for any reason, this prints an error
      and calls onFailed().
    :type onFailed: function object
    """
    # repo_command_parameter_pb2 was produced by protoc.
    parameter = repo_command_parameter_pb2.RepoCommandParameterMessage()
    for i in range(watchPrefix.size()):
        parameter.repo_command_parameter.name.component.append(
            watchPrefix[i].getValue().toBytes())

    # Create the command interest.
    interest = Interest(
        Name(repoCommandPrefix).append("watch").append("stop").append(
            Name.Component(ProtobufTlv.encode(parameter))))
    face.makeCommandInterest(interest)

    # Send the command interest and get the response or timeout.
    def onData(interest, data):
        # repo_command_response_pb2 was produced by protoc.
        response = repo_command_response_pb2.RepoCommandResponseMessage()
        try:
            ProtobufTlv.decode(response, data.content)
        except:
            dump("Cannot decode the repo command response")
            onFailed()

        if response.repo_command_response.status_code == 101:
            onRepoWatchStopped()
        else:
            dump("Got repo command error code",
                 response.repo_command_response.status_code)
            onFailed()

    def onTimeout(interest):
        dump("Stop repo watch command timeout")
        onFailed()

    face.expressInterest(interest, onData, onTimeout)
    def initiateContentStoreInsertion(self, repoCommandPrefix, data):
        fetchName = data.getName()
        parameter = repo_command_parameter_pb2.RepoCommandParameterMessage()
        # Add the Name.
        for i in range(fetchName.size()):
            parameter.repo_command_parameter.name.component.append(
              fetchName[i].getValue().toBytes())

        # Create the command interest.
        interest = Interest(Name(repoCommandPrefix).append("insert")
          .append(Name.Component(ProtobufTlv.encode(parameter))))
        self.face.makeCommandInterest(interest)

        self.face.expressInterest(interest, self.onRepoData, self.onRepoTimeout)
Exemple #23
0
def requestInsert(face, repoCommandPrefix, fetchName, onInsertStarted,
                  onFailed):
    # Construct a RepoCommandParameterMessage using the structure in
    # repo_command_parameter_pb2 which was produced by protoc.
    parameter = repo_command_parameter_pb2.RepoCommandParameterMessage()
    # Add the Name.
    msgName = parameter.Name()

    # 1. pattern name
    msgName.Clear()
    msgName.component.append(PATTERN_NAME[0].getValue().toBytes())
    parameter.repo_command_parameter.name.component.append(
        ProtobufTlv.encode(msgName).toBytes())

    # 2. fetch prefix
    msgName.Clear()
    for compo in fetchName:
        msgName.component.append(compo.getValue().toBytes())
    parameter.repo_command_parameter.name.component.append(
        ProtobufTlv.encode(msgName).toBytes())

    # Create the command interest.
    interest = Interest(
        Name(repoCommandPrefix).append("pattern").append(
            Name.Component(ProtobufTlv.encode(parameter))))
    face.makeCommandInterest(interest)

    # Send the command interest and get the response or timeout.
    def onData(interest, data):
        # repo_command_response_pb2 was produced by protoc.
        response = repo_command_response_pb2.RepoCommandResponseMessage()
        try:
            ProtobufTlv.decode(response, data.content)
        except:
            dump("Cannot decode the repo command response")
            onFailed()

        if response.repo_command_response.status_code == 100:
            onInsertStarted()
        else:
            dump("Got repo command error code",
                 response.repo_command_response.status_code)
            onFailed()

    def onTimeout(interest):
        dump("Pattern repo command timeout")
        onFailed()

    face.expressInterest(interest, onData, onTimeout)
Exemple #24
0
    def test_encrypt_and_publish_ck(self):
        self._fixture._encryptor._kekData = None
        self.assertEqual(False,
                         self._fixture._encryptor._isKekRetrievalInProgress)
        self._fixture._encryptor.regenerateCk()
        # Unlike the ndn-group-encrypt unit tests, we don't check
        # isKekRetrievalInProgress_ true because we use a synchronous face which
        # finishes immediately.

        plainText = Blob("Data to encrypt")
        encryptedContent = self._fixture._encryptor.encrypt(plainText)

        ckPrefix = encryptedContent.getKeyLocatorName()
        self.assertTrue(
            Name("/some/ck/prefix/CK").equals(ckPrefix.getPrefix(-1)))

        self.assertTrue(encryptedContent.hasInitialVector())
        self.assertTrue(not encryptedContent.getPayload().equals(plainText))

        # Check that the KEK Interest has been sent.
        self.assertTrue(
            self._fixture._face._sentInterests[0].getName().getPrefix(
                6).equals(Name("/access/policy/identity/NAC/dataset/KEK")))

        kekData = self._fixture._face._sentData[0]
        self.assertTrue(kekData.getName().getPrefix(6).equals(
            Name("/access/policy/identity/NAC/dataset/KEK")))
        self.assertEqual(7, kekData.getName().size())

        self._fixture._face._sentData = []
        self._fixture._face._sentInterests = []

        self._fixture._face.receive(
            Interest(ckPrefix).setCanBePrefix(True).setMustBeFresh(True))

        ckName = self._fixture._face._sentData[0].getName()
        self.assertTrue(ckName.getPrefix(4).equals(Name("/some/ck/prefix/CK")))
        self.assertTrue(ckName.get(5).equals(Name.Component("ENCRYPTED-BY")))

        extractedKek = ckName.getSubName(6)
        self.assertTrue(extractedKek.equals(kekData.getName()))

        self.assertEqual(False,
                         self._fixture._encryptor._isKekRetrievalInProgress)
Exemple #25
0
    def sendingFile(self, file_path, interest, face, freshness):
        print "Sending File Function"
        interestName = interest.getName()
        interestNameSize = interestName.size()

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

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

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

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

        except ValueError as err:
            print "ERROR: %s" % err
Exemple #26
0
 async def query_face_id(self, uri):
     query_filter = FaceQueryFilterMessage()
     query_filter.face_query_filter.uri = uri.encode('utf-8')
     query_filter_msg = ProtobufTlv.encode(query_filter)
     name = Name("/localhost/nfd/faces/query").append(Name.Component(query_filter_msg))
     interest = Interest(name)
     interest.mustBeFresh = True
     interest.canBePrefix = True
     ret = await fetch_data_packet(self.face, interest)
     if not isinstance(ret, Data):
         return None
     msg = FaceStatusMessage()
     try:
         ProtobufTlv.decode(msg, ret.content)
     except RuntimeError as exc:
         logging.fatal("Decoding Error %s", exc)
         return None
     if len(msg.face_status) <= 0:
         return None
     return msg.face_status[0].face_id
Exemple #27
0
    def _onConfigurationReceived(self, prefix, interest, transport, prefixId):
        # the interest we get here is signed by HMAC, let's verify it
        self.tempPrefixId = prefixId  # didn't get it from register because of the event loop
        interestName = interest.getName()
        replyData = Data(interestName)
        if len(interestName) == len(prefix):
            # this is a discovery request. Check the exclude to see if we should
            # return our serial
            serial = self.getSerial()
            serialComponent = Name.Component(serial)
            if not interest.getExclude().matches(serialComponent):
                replyData.setContent(serial)
                self.sendData(replyData, transport,
                              False)  # no point in signing
        elif (self._hmacHandler.verifyInterest(interest)):
            # we have a match! decode the network parameters
            configComponent = interest.getName()[len(prefix) + 1]
            replyData.setContent('200')
            self._hmacHandler.signData(replyData, keyName=self.prefix)
            transport.send(replyData.wireEncode().buf())

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

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

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

            self._configureIdentity = Name(networkPrefix).append(
                self.deviceSuffix)
            self._sendCertificateRequest(self._configureIdentity)
    def startRepoInsertion(self, data):
        # For now we only insert raw data into repo
        parameter = repo_command_parameter_pb2.RepoCommandParameterMessage()
        # Add the Name.
        for i in range(data.getName().size()):
            parameter.repo_command_parameter.name.component.append(
                data.getName().get(i).toEscapedString())

        # Create the command interest.
        commandInterest = Interest(
            Name(repoCommandPrefix).append("insert").append(
                Name.Component(ProtobufTlv.encode(parameter))))
        self._face.makeCommandInterest(commandInterest)

        # Send the command interest and get the response or timeout.
        def onRepoCommandResponse(interest, data):
            # repo_command_response_pb2 was produced by protoc.
            response = repo_command_response_pb2.RepoCommandResponseMessage()
            try:
                ProtobufTlv.decode(response, data.content)
            except:
                print("Cannot decode the repo command response")

            if response.repo_command_response.status_code == 100:
                if __debug__:
                    print("Insertion started")
            else:
                print("Got repo command error code",
                      response.repo_command_response.status_code)

        def onRepoCommandTimeout(interest):
            if __debug__:
                print("Insert repo command timeout")

        self._face.expressInterest(commandInterest, onRepoCommandResponse,
                                   onRepoCommandTimeout)
Exemple #29
0
 def setUp(self):
     self.entree = Name.Component(u"entr\u00E9e")
     self.comp1 = Name.Component(bytearray([ord('.')] * 4))
     self.comp2 = Name.Component(bytearray([0x00, 0x01, 0x02, 0x03]))
     self.expectedURI = "/entr%C3%A9e/..../%00%01%02%03"
Exemple #30
0
 def test_unicode(self):
     comp1 = Name.Component(u"entr\u00E9e")
     expected = "entr%C3%A9e"
     self.assertEqual(comp1.toEscapedString(), expected)