Example #1
0
        def onData(self, interest, responseData):
            """
            We received the response.
            """
            # Decode responseData.getContent() and check for a success code.
            controlResponse = ControlResponse()
            try:
                controlResponse.wireDecode(responseData.getContent(),
                                           TlvWireFormat.get())
            except ValueError as ex:
                logging.getLogger(__name__).info(
                    "Register prefix failed: Error decoding the NFD response: %s",
                    str(ex))
                try:
                    self._onRegisterFailed(self._prefix)
                except:
                    logging.exception("Error in onRegisterFailed")
                return

            # Status code 200 is "OK".
            if controlResponse.getStatusCode() != 200:
                logging.getLogger(__name__).info(
                    "Register prefix failed: Expected NFD status code 200, got: %d",
                    controlResponse.getStatusCode())
                try:
                    self._onRegisterFailed(self._prefix)
                except:
                    logging.exception("Error in onRegisterFailed")
                return

            # Success, so we can add to the registered prefix table.
            if self._registeredPrefixId != 0:
                interestFilterId = 0
                if self._onInterest != None:
                    # registerPrefix was called with the "combined" form that includes
                    # the callback, so add an InterestFilterEntry.
                    interestFilterId = self._parent.getNextEntryId()
                    self._parent.setInterestFilter(
                        interestFilterId, InterestFilter(self._prefix),
                        self._onInterest, self._face)

                if not self._parent._registeredPrefixTable.add(
                        self._registeredPrefixId, self._prefix,
                        interestFilterId):
                    # removeRegisteredPrefix was already called with the registeredPrefixId.
                    if interestFilterId > 0:
                        # Remove the related interest filter we just added.
                        self._parent.unsetInterestFilter(interestFilterId)

                    return

            logging.getLogger(__name__).info(
                "Register prefix succeeded with the NFD forwarder for prefix %s",
                self._prefix.toUri())
            if self._onRegisterSuccess != None:
                try:
                    self._onRegisterSuccess(self._prefix,
                                            self._registeredPrefixId)
                except:
                    logging.exception("Error in onRegisterSuccess")
Example #2
0
    def setInterestFilter(self, filterOrPrefix, onInterest):
        """
        Add an entry to the local interest filter table to call the onInterest
        callback for a matching incoming Interest. This method only modifies the
        library's local callback table and does not register the prefix with the
        forwarder. It will always succeed. To register a prefix with the
        forwarder, use registerPrefix. There are two forms of setInterestFilter.
        The first form uses the exact given InterestFilter:
        setInterestFilter(filter, onInterest).
        The second form creates an InterestFilter from the given prefix Name:
        setInterestFilter(prefix, onInterest).

        :param InterestFilter filter: The InterestFilter with a prefix and
          optional regex filter used to match the name of an incoming Interest.
          This makes a copy of filter.
        :param Name prefix: The Name prefix used to match the name of an
          incoming Interest.
        :param onInterest: When an Interest is received which matches the filter,
          this calls onInterest(prefix, interest, face, interestFilterId, filter).
        :type onInterest: function object
        :return: The interest filter ID which can be used with unsetInterestFilter.
        :rtype: int
        """
        interestFilterId = self._node.getNextEntryId()

        # If filterOrPrefix is already an InterestFilter, the InterestFilter
        # constructor will make a copy as required by Node.setInterestFilter.
        filterCopy = InterestFilter(filterOrPrefix)

        self._node.setInterestFilter(
          interestFilterId, filterCopy, onInterest, self)

        return interestFilterId
Example #3
0
    def _nfdRegisterPrefix(
      self, registeredPrefixId, prefix, onInterest, onRegisterFailed, flags,
      commandKeyChain, commandCertificateName, face):
        """
        Do the work of registerPrefix to register with NFD.

        :param int registeredPrefixId: The getNextEntryId() which registerPrefix
          got so it could return it to the caller. If this is 0, then don't add
          to _registeredPrefixTable (assuming it has already been done).
        """
        if commandKeyChain == None:
            raise RuntimeError(
              "registerPrefix: The command KeyChain has not been set. You must call setCommandSigningInfo.")
        if commandCertificateName.size() == 0:
            raise RuntimeError(
              "registerPrefix: The command certificate name has not been set. You must call setCommandSigningInfo.")

        controlParameters = ControlParameters()
        controlParameters.setName(prefix)
        controlParameters.setForwardingFlags(flags)

        commandInterest = Interest()
        if self.isLocal():
            commandInterest.setName(Name("/localhost/nfd/rib/register"))
            # The interest is answered by the local host, so set a short timeout.
            commandInterest.setInterestLifetimeMilliseconds(2000.0)
        else:
            commandInterest.setName(Name("/localhop/nfd/rib/register"))
            # The host is remote, so set a longer timeout.
            commandInterest.setInterestLifetimeMilliseconds(4000.0)
        # NFD only accepts TlvWireFormat packets.
        commandInterest.getName().append(controlParameters.wireEncode(TlvWireFormat.get()))
        self.makeCommandInterest(
          commandInterest, commandKeyChain, commandCertificateName,
          TlvWireFormat.get())

        if registeredPrefixId != 0:
            interestFilterId = 0
            if onInterest != None:
                # registerPrefix was called with the "combined" form that includes
                # the callback, so add an InterestFilterEntry.
                interestFilterId = self.getNextEntryId()
                self.setInterestFilter(
                  interestFilterId, InterestFilter(prefix), onInterest, face)

            self._registeredPrefixTable.append(Node._RegisteredPrefix(
              registeredPrefixId, prefix, interestFilterId))

        # Send the registration interest.
        response = Node._RegisterResponse(
          self, prefix, onInterest, onRegisterFailed, flags,
          TlvWireFormat.get(), True, face)
        self.expressInterest(
          self.getNextEntryId(), commandInterest, response.onData,
          response.onTimeout, TlvWireFormat.get(), face)
Example #4
0
    def setInterestFilter(self, filterOrPrefix, onInterest):
        """
        Override to use the event loop given to the constructor to schedule
        setInterestFilter to be called in a thread-safe manner. See
        Face.setInterestFilter for calling details.
        """
        interestFilterId = self._node.getNextEntryId()

        # If filterOrPrefix is already an InterestFilter, the InterestFilter
        # constructor will make a copy as required by Node.setInterestFilter.
        # We make a copy so that the caller can change the original object while
        # call_soon_threadsafe is waiting to process.
        filterCopy = InterestFilter(filterOrPrefix)

        self._loop.call_soon_threadsafe(self._node.setInterestFilter,
                                        interestFilterId, filterCopy,
                                        onInterest, self)

        return interestFilterId
Example #5
0
    def setInterestFilter(self, interestFilterId, filterCopy, onInterest,
                          face):
        """
        Add an entry to the local interest filter table to call the onInterest
        callback for a matching incoming Interest. This method only modifies the
        library's local callback table and does not register the prefix with the
        forwarder. It will always succeed. To register a prefix with the
        forwarder, use registerPrefix.

        :param int interestFilterId: The getNextEntryId() for the interest
          filter ID which Face got so it could return it to the caller.
        :param InterestFilter filterCopy: The InterestFilter with a prefix and
          optional regex filter used to match the name of an incoming Interest,
          which is NOT copied for this internal Node method. The Face
          setInterestFilter is responsible for making a copy for Node to use.
        :param onInterest: When an Interest is received which matches the filter,
          this calls onInterest(prefix, interest, face, interestFilterId, filter).
        :type onInterest: function object
        :param Face face: The face which is passed to the onInterest callback.
        """
        self._interestFilterTable.setInterestFilter(interestFilterId,
                                                    InterestFilter(filterCopy),
                                                    onInterest, face)
Example #6
0
    def _registerPrefixHelper(
      self, registeredPrefixId, prefix, onInterest, onRegisterFailed, flags,
      wireFormat, face):
        """
        Do the work of registerPrefix to register with NDNx once we have an
        _ndndId.

        :param int registeredPrefixId: The getNextEntryId() which registerPrefix
          got so it could return it to the caller. If this is 0, then don't add
          to _registeredPrefixTable (assuming it has already been done).
        """
        if not WireFormat.ENABLE_NDNX:
            # We can get here if the command signing info is set, but running NDNx.
            raise RuntimeError(
              "registerPrefix with NDNx is deprecated. To enable while you upgrade your code to use NFD, set WireFormat.ENABLE_NDNX = True")

        # Create a ForwardingEntry.
        # Note: ndnd ignores any freshness that is larger than 3600 seconds and
        #   sets 300 seconds instead. To register "forever", (=2000000000 sec),
        #   the freshness period must be omitted.
        forwardingEntry = ForwardingEntry()
        forwardingEntry.setAction("selfreg")
        forwardingEntry.setPrefix(prefix)
        forwardingEntry.setForwardingFlags(flags)
        content = forwardingEntry.wireEncode(wireFormat)

        # Set the ForwardingEntry as the content of a Data packet and sign.
        data = Data()
        data.setContent(content)
        # Set the name to a random value so that each request is unique.
        nonce = bytearray(4)
        for i in range(len(nonce)):
            nonce[i] = _systemRandom.randint(0, 0xff)
        data.getName().append(nonce)
        # The ndnd ignores the signature, so set to blank values.
        data.getSignature().getKeyLocator().setType(
          KeyLocatorType.KEY_LOCATOR_DIGEST)
        data.getSignature().getKeyLocator().setKeyData(
          Blob(bytearray(32), False))
        data.getSignature().setSignature(Blob(bytearray(128), False))
        encodedData = data.wireEncode(wireFormat)

        # Create an interest where the name has the encoded Data packet.
        interestName = Name().append("ndnx").append(self._ndndId).append(
          "selfreg").append(encodedData)

        interest = Interest(interestName)
        interest.setInterestLifetimeMilliseconds(4000.0)
        interest.setScope(1)

        if registeredPrefixId != 0:
            interestFilterId = 0
            if onInterest != None:
                # registerPrefix was called with the "combined" form that includes
                # the callback, so add an InterestFilterEntry.
                interestFilterId = self.getNextEntryId()
                self.setInterestFilter(
                  interestFilterId, InterestFilter(prefix), onInterest, face)

            self._registeredPrefixTable.append(Node._RegisteredPrefix(
              registeredPrefixId, prefix, interestFilterId))

        # Send the registration interest.
        response = Node._RegisterResponse(
          self, prefix, onInterest, onRegisterFailed, flags, wireFormat, False,
          face)
        self.expressInterest(
          self.getNextEntryId(), interest, response.onData, response.onTimeout,
          wireFormat, face)