示例#1
0
文件: node.py 项目: MAHIS/PyNDN2
    def onReceivedElement(self, element):
        """
        This is called by the transport's ElementReader to process an
        entire received Data or Interest element.

        :param element: The bytes of the incoming element.
        :type element: An array type with int elements
        """
        # First, decode as Interest or Data.
        interest = None
        data = None
        decoder = TlvDecoder(element)
        if decoder.peekType(Tlv.Interest, len(element)):
            interest = Interest()
            interest.wireDecode(element, TlvWireFormat.get())
        elif decoder.peekType(Tlv.Data, len(element)):
            data = Data()
            data.wireDecode(element, TlvWireFormat.get())

        # Now process as Interest or Data.
        if interest != None:
            # Call all interest filter callbacks which match.
            for i in range(len(self._interestFilterTable)):
                entry = self._interestFilterTable[i]
                if entry.getFilter().doesMatch(interest.getName()):
                    includeFilter = True
                    # Use getcallargs to test if onInterest accepts 5 args.
                    try:
                        inspect.getcallargs(entry.getOnInterest(),
                          None, None, None, None, None)
                    except TypeError:
                        # Assume onInterest is old-style with 4 arguments.
                        includeFilter = False

                    if includeFilter:
                        try:
                            entry.getOnInterest()(
                              entry.getFilter().getPrefix(), interest,
                              entry.getFace(), entry.getInterestFilterId(),
                              entry.getFilter())
                        except:
                            logging.exception("Error in onInterest")
                    else:
                        # Old-style onInterest without the filter argument. We
                        # still pass a Face instead of Transport since Face also
                        # has a send method.
                        try:
                            entry.getOnInterest()(
                              entry.getFilter().getPrefix(), interest,
                              entry.getFace(), entry.getInterestFilterId())
                        except:
                            logging.exception("Error in onInterest")
        elif data != None:
            pendingInterests = self._extractEntriesForExpressedInterest(
              data.getName())
            for pendingInterest in pendingInterests:
                try:
                    pendingInterest.getOnData()(pendingInterest.getInterest(), data)
                except:
                    logging.exception("Error in onData")
示例#2
0
    def decodeInterest(self, interest, input):
        """
        Decode input as an NDN-TLV interest and set the fields of the interest
        object.

        :param Interest interest: The Interest object whose fields are updated.
        :param input: The array with the bytes to decode.
        :type input: An array type with int elements
        :return: A Tuple of (signedPortionBeginOffset, signedPortionEndOffset)
          where signedPortionBeginOffset is the offset in the encoding of
          the beginning of the signed portion, and signedPortionEndOffset is
          the offset in the encoding of the end of the signed portion. The
          signed portion starts from the first name component and ends just
          before the final name component (which is assumed to be a signature
          for a signed interest).
        :rtype: (int, int)
        """
        decoder = TlvDecoder(input)

        endOffset = decoder.readNestedTlvsStart(Tlv.Interest)
        offsets = self._decodeName(interest.getName(), decoder)
        if decoder.peekType(Tlv.Selectors, endOffset):
            self._decodeSelectors(interest, decoder)
        # Require a Nonce, but don't force it to be 4 bytes.
        nonce = Blob(decoder.readBlobTlv(Tlv.Nonce))
        interest.setInterestLifetimeMilliseconds(
           decoder.readOptionalNonNegativeIntegerTlvAsFloat
           (Tlv.InterestLifetime, endOffset))

        if decoder.peekType(Tlv.Data, endOffset):
            # Get the bytes of the Link TLV.
            linkBeginOffset = decoder.getOffset()
            linkEndOffset = decoder.readNestedTlvsStart(Tlv.Data)
            decoder.seek(linkEndOffset)

            interest.setLinkWireEncoding(
              Blob(decoder.getSlice(linkBeginOffset, linkEndOffset), True), self)
        else:
            interest.unsetLink()
        interest.setSelectedDelegationIndex(
          decoder.readOptionalNonNegativeIntegerTlv(
            Tlv.SelectedDelegation, endOffset))
        if (interest.getSelectedDelegationIndex() != None and
            interest.getSelectedDelegationIndex() >= 0 and not interest.hasLink()):
            raise RuntimeError(
              "Interest has a selected delegation, but no link object")

        # Set the nonce last because setting other interest fields clears it.
        interest.setNonce(nonce)

        decoder.finishNestedTlvs(endOffset)
        return offsets
    def wireDecode(self, wire):
        self.m_hasName = False
        self.m_hasStartBlockId = False
        self.m_hasEndBlockId = False
        self.m_hasProcessId = False
        self.m_hasMaxInterestNum = False
        self.m_hasWatchTimeout = False
        self.m_hasInterestLifetime = False

        #self.m_wire = wire

        decoder = TlvDecoder(wire)

        endOffset = decoder.readNestedTlvsStart(repoTlv.RepoCommandParameter)

        # Name
        if (decoder.peekType(Tlv.Name)):
            self.m_hasName = True
            Tlv0_1WireFormat._decodeName(self.m_name, decoder)

        # Selectors
        if (decoder.peekType(Tlv.Selectors)):
            Tlv0_1WireFormat._decodeSelectors(self.m_selector, decoder)
            self.m_selectors.wireDecode(*val)

        # StartBlockId
        if (decoder.peekType(repoTlv.StartBlockId)):
            self.m_hasStartBlockId = True
            self.m_startBlockId = decoder.readNonNegativeIntegerTlv(
                repoTlv.StartBlockId)

        # EndBlockId
        if (decoder.peekType(repoTlv.EndBlockId)):
            self.m_hasEndBlockId = True
            self.m_endBlockId = decoder.readNonNegativeIntegerTlv(
                repoTlv.EndBlockId)

        # ProcessId
        if (decoder.peekType(repoTlv.ProcessId)):
            self.m_hasProcessId = True
            self.m_processId = decoder.readNonNegativeInteger(
                repoTlv.ProcessId)

        # MaxInterestNum
        if (decoder.peekType(repoTlv.MaxInterestNum)):
            self.m_hasMaxInterestNum = True
            self.m_maxInterestNum = decoder.readNonNegativeInteger(
                repoTlv.MaxInterestNum)

        # WatchTimeout
        if (decoder.peekType(repoTlv.WatchTimeout)):
            self.m_hasWatchTimeout = True
            self.m_watchTimeout = milliseconds(
                decoder.readNonNegativeInteger(repoTlv.WatchTimeout))

        # InterestLifeTime
        if (decoder.peekType(Tlv.InterestLifetime)):
            self.m_hasInterestLifetime = True
            self.m_interestLifetime = milliseconds(
                decoder.readNonNegativeInteger(Tlv.InterestLifetime))
示例#4
0
    def decodeInterest(self, interest, input):
        """
        Decode input as an NDN-TLV interest and set the fields of the interest 
        object.  
        
        :param Interest interest: The Interest object whose fields are updated.
        :param input: The array with the bytes to decode.
        :type input: An array type with int elements
        :return: A Tuple of (signedPortionBeginOffset, signedPortionEndOffset) 
          where signedPortionBeginOffset is the offset in the encoding of 
          the beginning of the signed portion, and signedPortionEndOffset is
          the offset in the encoding of the end of the signed portion. The 
          signed portion starts from the first name component and ends just 
          before the final name component (which is assumed to be a signature 
          for a signed interest).
        :rtype: (int, int)
        """
        decoder = TlvDecoder(input)

        endOffset = decoder.readNestedTlvsStart(Tlv.Interest)
        self._decodeName(interest.getName(), decoder)
        if decoder.peekType(Tlv.Selectors, endOffset):
            self._decodeSelectors(interest, decoder)
        # Require a Nonce, but don't force it to be 4 bytes.
        nonce = Blob(decoder.readBlobTlv(Tlv.Nonce))
        interest.setScope(decoder.readOptionalNonNegativeIntegerTlv(
          Tlv.Scope, endOffset))
        interest.setInterestLifetimeMilliseconds(
           decoder.readOptionalNonNegativeIntegerTlvAsFloat
           (Tlv.InterestLifetime, endOffset))

        # Set the nonce last because setting other interest fields clears it.
        interest.setNonce(nonce)

        decoder.finishNestedTlvs(endOffset)
示例#5
0
    def onReceivedElement(self, element):
        """
        This is called by the transport's ElementReader to process an
        entire received Data or Interest element.
        :param element: The bytes of the incoming element.
        :type element: An array type with int elements
        """

        lpPacket = None
        if element[0] == Tlv.LpPacket_LpPacket:
            # Decode the LpPacket and replace element with the fragment.
            lpPacket = LpPacket()
            # Set copy False so that the fragment is a slice which will be
            # copied below. The header fields are all integers and don't need to
            # be copied.
            TlvWireFormat.get().decodeLpPacket(lpPacket, element, False)
            element = lpPacket.getFragmentWireEncoding().buf()

        # First, decode as Interest or Data.
        data = None
        decoder = TlvDecoder(element)
        if decoder.peekType(Tlv.Data, len(element)):
            data = Data()
            data.wireDecode(element, TlvWireFormat.get())

            if lpPacket != None:
                data.setLpPacket(lpPacket)

        # Now process as Interest or Data.
        if data != None:
            if self._onBtleData:
                self._onBtleData(data)
示例#6
0
    def onReceivedElement(self, element):
        """
        This is called by the transport's ElementReader to process an
        entire received Data or Interest element.
        :param element: The bytes of the incoming element.
        :type element: An array type with int elements
        """

        lpPacket = None
        if element[0] == Tlv.LpPacket_LpPacket:
            # Decode the LpPacket and replace element with the fragment.
            lpPacket = LpPacket()
            # Set copy False so that the fragment is a slice which will be
            # copied below. The header fields are all integers and don't need to
            # be copied.
            TlvWireFormat.get().decodeLpPacket(lpPacket, element, False)
            element = lpPacket.getFragmentWireEncoding().buf()

        # First, decode as Interest or Data.
        data = None
        decoder = TlvDecoder(element)
        if decoder.peekType(Tlv.Data, len(element)):
            data = Data()
            data.wireDecode(element, TlvWireFormat.get())

            if lpPacket != None:
                data.setLpPacket(lpPacket)

        # Now process as Interest or Data.
        if data != None:
            if self._onBtleData:
                self._onBtleData(data)
示例#7
0
    def decodeInterest(self, interest, input):
        """
        Decode input as an NDN-TLV interest and set the fields of the interest 
        object.  
        
        :param Interest interest: The Interest object whose fields are updated.
        :param input: The array with the bytes to decode.
        :type input: An array type with int elements
        :return: A Tuple of (signedPortionBeginOffset, signedPortionEndOffset) 
          where signedPortionBeginOffset is the offset in the encoding of 
          the beginning of the signed portion, and signedPortionEndOffset is
          the offset in the encoding of the end of the signed portion. The 
          signed portion starts from the first name component and ends just 
          before the final name component (which is assumed to be a signature 
          for a signed interest).
        :rtype: (int, int)
        """
        decoder = TlvDecoder(input)

        endOffset = decoder.readNestedTlvsStart(Tlv.Interest)
        self._decodeName(interest.getName(), decoder)
        if decoder.peekType(Tlv.Selectors, endOffset):
            self._decodeSelectors(interest, decoder)
        # Require a Nonce, but don't force it to be 4 bytes.
        nonce = Blob(decoder.readBlobTlv(Tlv.Nonce))
        interest.setScope(
            decoder.readOptionalNonNegativeIntegerTlv(Tlv.Scope, endOffset))
        interest.setInterestLifetimeMilliseconds(
            decoder.readOptionalNonNegativeIntegerTlvAsFloat(
                Tlv.InterestLifetime, endOffset))

        # Set the nonce last because setting other interest fields clears it.
        interest.setNonce(nonce)

        decoder.finishNestedTlvs(endOffset)
示例#8
0
    def decodeInterest(self, interest, input):
        """
        Decode input as an NDN-TLV interest and set the fields of the interest
        object.

        :param Interest interest: The Interest object whose fields are updated.
        :param input: The array with the bytes to decode.
        :type input: An array type with int elements
        """
        decoder = TlvDecoder(input)

        endOffset = decoder.readNestedTlvsStart(Tlv.Interest)
        self._decodeName(interest.getName(), decoder)
        if decoder.peekType(Tlv.Selectors, endOffset):
            self._decodeSelectors(interest, decoder)
        # Require a Nonce, but don't force it to be 4 bytes.
        nonce = Blob(decoder.readBlobTlv(Tlv.Nonce))
        interest.setScope(decoder.readOptionalNonNegativeIntegerTlv(
          Tlv.Scope, endOffset))
        interest.setInterestLifetimeMilliseconds(
           decoder.readOptionalNonNegativeIntegerTlvAsFloat
           (Tlv.InterestLifetime, endOffset))

        # Set the nonce last because setting other interest fields clears it.
        interest.setNonce(nonce)

        decoder.finishNestedTlvs(endOffset)
示例#9
0
    def decodeControlResponse(self, controlResponse, input):
        """
        Decode input as an NDN-TLV ControlResponse and set the fields of the
        controlResponse object.

        :param ControlResponse controlResponse: The ControlResponse object
          whose fields are updated.
        :param input: The array with the bytes to decode.
        :type input: An array type with int elements
        """
        controlResponse.clear()

        decoder = TlvDecoder(input)
        endOffset = decoder.readNestedTlvsStart(
          Tlv.NfdCommand_ControlResponse)

        # decode face ID
        controlResponse.setStatusCode(decoder.readNonNegativeIntegerTlv
            (Tlv.NfdCommand_StatusCode))
        statusText = Blob(
          decoder.readBlobTlv(Tlv.NfdCommand_StatusText), False)
        controlResponse.setStatusText(str(statusText))

        # Decode the body.
        if decoder.peekType(Tlv.ControlParameters_ControlParameters, endOffset):
            controlResponse.setBodyAsControlParameters(ControlParameters())
            # Decode into the existing ControlParameters to avoid copying.
            self._decodeControlParameters(
              controlResponse.getBodyAsControlParameters(), decoder)

        decoder.finishNestedTlvs(endOffset)
    def wireDecode(self, wire):
        self.m_hasName = False
        self.m_hasStartBlockId = False
        self.m_hasEndBlockId = False
        self.m_hasProcessId = False
        self.m_hasMaxInterestNum = False
        self.m_hasWatchTimeout = False
        self.m_hasInterestLifetime = False

        #self.m_wire = wire
        
        decoder = TlvDecoder(wire)

        endOffset = decoder.readNestedTlvsStart(repoTlv.RepoCommandParameter)
  
        # Name
        if (decoder.peekType(Tlv.Name)):
            self.m_hasName = True
            Tlv0_1WireFormat._decodeName(self.m_name, decoder)

        # Selectors
        if (decoder.peekType(Tlv.Selectors)):
            Tlv0_1WireFormat._decodeSelectors(self.m_selector, decoder)
            self.m_selectors.wireDecode(*val)
      
        # StartBlockId
        if (decoder.peekType(repoTlv.StartBlockId)):
            self.m_hasStartBlockId = True
            self.m_startBlockId = decoder.readNonNegativeIntegerTlv(repoTlv.StartBlockId)
  
        # EndBlockId
        if (decoder.peekType(repoTlv.EndBlockId)):
            self.m_hasEndBlockId = True
            self.m_endBlockId = decoder.readNonNegativeIntegerTlv(repoTlv.EndBlockId)

        # ProcessId
        if (decoder.peekType(repoTlv.ProcessId)):
            self.m_hasProcessId = True
            self.m_processId = decoder.readNonNegativeInteger(repoTlv.ProcessId)

        # MaxInterestNum
        if (decoder.peekType(repoTlv.MaxInterestNum)):
            self.m_hasMaxInterestNum = True
            self.m_maxInterestNum = decoder.readNonNegativeInteger(repoTlv.MaxInterestNum)

        # WatchTimeout
        if (decoder.peekType(repoTlv.WatchTimeout)):
            self.m_hasWatchTimeout = True
            self.m_watchTimeout = milliseconds(decoder.readNonNegativeInteger(repoTlv.WatchTimeout))

        # InterestLifeTime
        if (decoder.peekType(Tlv.InterestLifetime)):
            self.m_hasInterestLifetime = True
            self.m_interestLifetime = milliseconds(decoder.readNonNegativeInteger(Tlv.InterestLifetime))
示例#11
0
    def onReceivedElement(self, element):
        """
        This is called by the transport's ElementReader to process an
        entire received Data or Interest element.
        
        :param element: The bytes of the incoming element.
        :type element: An array type with int elements
        """
        # The type codes for TLV Interest and Data packets are chosen to not
        #   conflict with the first byte of a binary XML packet, so we canjust
        #   look at the first byte.
        if not (element[0] == Tlv.Interest or element[0] == Tlv.Data):
            # Ignore non-TLV elements.
            return

        # First, decode as Interest or Data.
        interest = None
        data = None
        decoder = TlvDecoder(element)
        if decoder.peekType(Tlv.Interest, len(element)):
            interest = Interest()
            interest.wireDecode(element, TlvWireFormat.get())
        elif decoder.peekType(Tlv.Data, len(element)):
            data = Data()
            data.wireDecode(element, TlvWireFormat.get())

        # Now process as Interest or Data.
        if interest != None:
            entry = self._getEntryForRegisteredPrefix(interest.getName())
            if entry != None:
                entry.getOnInterest()(entry.getPrefix(), interest,
                                      self._transport,
                                      entry.getRegisteredPrefixId())
        elif data != None:
            pendingInterests = self._extractEntriesForExpressedInterest(
                data.getName())
            for pendingInterest in pendingInterests:
                pendingInterest.getOnData()(pendingInterest.getInterest(),
                                            data)
示例#12
0
    def onReceivedElement(self, element):
        """
        This is called by the transport's ElementReader to process an
        entire received Data or Interest element.

        :param element: The bytes of the incoming element.
        :type element: An array type with int elements
        """
        # The type codes for TLV Interest and Data packets are chosen to not
        #   conflict with the first byte of a binary XML packet, so we canjust
        #   look at the first byte.
        if not (element[0] == Tlv.Interest or element[0] == Tlv.Data):
            # Ignore non-TLV elements.
            return

        # First, decode as Interest or Data.
        interest = None
        data = None
        decoder = TlvDecoder(element)
        if decoder.peekType(Tlv.Interest, len(element)):
            interest = Interest()
            interest.wireDecode(element, TlvWireFormat.get())
        elif decoder.peekType(Tlv.Data, len(element)):
            data = Data()
            data.wireDecode(element, TlvWireFormat.get())

        # Now process as Interest or Data.
        if interest != None:
            entry = self._getEntryForRegisteredPrefix(interest.getName())
            if entry != None:
                entry.getOnInterest()(
                  entry.getPrefix(), interest, self._transport,
                  entry.getRegisteredPrefixId())
        elif data != None:
            pendingInterests = self._extractEntriesForExpressedInterest(
              data.getName())
            for pendingInterest in pendingInterests:
                pendingInterest.getOnData()(pendingInterest.getInterest(), data)
示例#13
0
    def decodeForwardingEntry(self, forwardingEntry, input):
        """
        Decode input as an forwardingEntry and set the fields of the
        forwardingEntry object.

        :param forwardingEntry: The ForwardingEntry object whose fields are
          updated.
        :type forwardingEntry: ForwardingEntry
        :param input: The array with the bytes to decode.
        :type input: An array type with int elements
        """
        decoder = TlvDecoder(input)

        endOffset = decoder.readNestedTlvsStart(Tlv.ForwardingEntry)

        actionBytes = decoder.readOptionalBlobTlv(Tlv.Action, endOffset)
        if actionBytes != None:
            # Convert bytes to a str.
            forwardingEntry.setAction("".join(map(chr, actionBytes)))
        else:
            forwardingEntry.setAction(None)

        if decoder.peekType(Tlv.Name, endOffset):
            self._decodeName(forwardingEntry.getPrefix(), decoder)
        else:
            forwardingEntry.getPrefix().clear()

        forwardingEntry.setFaceId(
            decoder.readOptionalNonNegativeIntegerTlv(Tlv.FaceID, endOffset))

        forwardingEntryFlags = decoder.readOptionalNonNegativeIntegerTlv(
            Tlv.ForwardingFlags, endOffset)
        if forwardingEntryFlags != None:
            forwardingEntry.getForwardingFlags().setForwardingEntryFlags(
                forwardingEntryFlags)
        else:
            # This sets the default flags.
            forwardingEntry.setForwardingFlags(ForwardingFlags())

        forwardingEntry.setFreshnessPeriod(
            decoder.readOptionalNonNegativeIntegerTlvAsFloat(
                Tlv.FreshnessPeriod, endOffset))

        decoder.finishNestedTlvs(endOffset)
示例#14
0
    def decodeForwardingEntry(self, forwardingEntry, input):
        """
        Decode input as an forwardingEntry and set the fields of the
        forwardingEntry object.

        :param forwardingEntry: The ForwardingEntry object whose fields are
          updated.
        :type forwardingEntry: ForwardingEntry
        :param input: The array with the bytes to decode.
        :type input: An array type with int elements
        """
        decoder = TlvDecoder(input)

        endOffset = decoder.readNestedTlvsStart(Tlv.ForwardingEntry)

        actionBytes = decoder.readOptionalBlobTlv(Tlv.Action, endOffset)
        if actionBytes != None:
            # Convert bytes to a str.
            forwardingEntry.setAction("".join(map(chr, actionBytes)))
        else:
            forwardingEntry.setAction(None)

        if decoder.peekType(Tlv.Name, endOffset):
            self._decodeName(forwardingEntry.getPrefix(), decoder)
        else:
            forwardingEntry.getPrefix().clear()

        forwardingEntry.setFaceId(
          decoder.readOptionalNonNegativeIntegerTlv(Tlv.FaceID, endOffset))

        forwardingEntryFlags = decoder.readOptionalNonNegativeIntegerTlv(
          Tlv.ForwardingFlags, endOffset)
        if forwardingEntryFlags != None:
            forwardingEntry.getForwardingFlags().setForwardingEntryFlags(
              forwardingEntryFlags)
        else:
            # This sets the default flags.
            forwardingEntry.setForwardingFlags(ForwardingFlags())

        forwardingEntry.setFreshnessPeriod(
          decoder.readOptionalNonNegativeIntegerTlvAsFloat(
            Tlv.FreshnessPeriod, endOffset))

        decoder.finishNestedTlvs(endOffset)
示例#15
0
文件: node.py 项目: skoulouzis/PyNDN2
    def onReceivedElement(self, element):
        """
        This is called by the transport's ElementReader to process an
        entire received Data or Interest element.

        :param element: The bytes of the incoming element.
        :type element: An array type with int elements
        """

        lpPacket = None
        if element[0] == Tlv.LpPacket_LpPacket:
            # Decode the LpPacket and replace element with the fragment.
            lpPacket = LpPacket()
            # Set copy False so that the fragment is a slice which will be
            # copied below. The header fields are all integers and don't need to
            # be copied.
            TlvWireFormat.get().decodeLpPacket(lpPacket, element, False)
            element = lpPacket.getFragmentWireEncoding().buf()

        # First, decode as Interest or Data.
        interest = None
        data = None
        decoder = TlvDecoder(element)
        if decoder.peekType(Tlv.Interest, len(element)):
            interest = Interest()
            interest.wireDecode(element, TlvWireFormat.get())

            if lpPacket != None:
                interest.setLpPacket(lpPacket)
        elif decoder.peekType(Tlv.Data, len(element)):
            data = Data()
            data.wireDecode(element, TlvWireFormat.get())

            if lpPacket != None:
                data.setLpPacket(lpPacket)

        if lpPacket != None:
            # We have decoded the fragment, so remove the wire encoding to save
            #   memory.
            lpPacket.setFragmentWireEncoding(Blob())

            networkNack = NetworkNack.getFirstHeader(lpPacket)
            if networkNack != None:
                if interest == None:
                    # We got a Nack but not for an Interest, so drop the packet.
                    return

                pendingInterests = []
                self._pendingInterestTable.extractEntriesForNackInterest(
                    interest, pendingInterests)
                for pendingInterest in pendingInterests:
                    try:
                        pendingInterest.getOnNetworkNack()(
                            pendingInterest.getInterest(), networkNack)
                    except:
                        logging.exception("Error in onNetworkNack")

                # We have processed the network Nack packet.
                return

        # Now process as Interest or Data.
        if interest != None:
            # Call all interest filter callbacks which match.
            matchedFilters = []
            self._interestFilterTable.getMatchedFilters(
                interest, matchedFilters)
            for i in range(len(matchedFilters)):
                entry = matchedFilters[i]
                includeFilter = True
                onInterestCall = entry.getOnInterest()
                # If onInterest is not a function nor a method assumes it is a
                # calleable object
                if (not inspect.isfunction(onInterestCall)
                        and not inspect.ismethod(onInterestCall)):
                    onInterestCall = onInterestCall.__call__
                # Use getcallargs to test if onInterest accepts 5 args.
                try:
                    inspect.getcallargs(onInterestCall, None, None, None, None,
                                        None)
                except TypeError:
                    # Assume onInterest is old-style with 4 arguments.
                    includeFilter = False

                if includeFilter:
                    try:
                        entry.getOnInterest()(entry.getFilter().getPrefix(),
                                              interest, entry.getFace(),
                                              entry.getInterestFilterId(),
                                              entry.getFilter())
                    except:
                        logging.exception("Error in onInterest")
                else:
                    # Old-style onInterest without the filter argument. We
                    # still pass a Face instead of Transport since Face also
                    # has a send method.
                    try:
                        entry.getOnInterest()(entry.getFilter().getPrefix(),
                                              interest, entry.getFace(),
                                              entry.getInterestFilterId())
                    except:
                        logging.exception("Error in onInterest")
        elif data != None:
            pendingInterests = []
            self._pendingInterestTable.extractEntriesForExpressedInterest(
                data, pendingInterests)
            for pendingInterest in pendingInterests:
                try:
                    pendingInterest.getOnData()(pendingInterest.getInterest(),
                                                data)
                except:
                    logging.exception("Error in onData")
示例#16
0
    def onReceivedElement(self, element):
        """
        This is called by the transport's ElementReader to process an
        entire received Data or Interest element.

        :param element: The bytes of the incoming element.
        :type element: An array type with int elements
        """

        lpPacket = None
        if element[0] == Tlv.LpPacket_LpPacket:
            # Decode the LpPacket and replace element with the fragment.
            lpPacket = LpPacket()
            # Set copy False so that the fragment is a slice which will be
            # copied below. The header fields are all integers and don't need to
            # be copied.
            TlvWireFormat.get().decodeLpPacket(lpPacket, element, False)
            element = lpPacket.getFragmentWireEncoding().buf()

        # First, decode as Interest or Data.
        interest = None
        data = None
        decoder = TlvDecoder(element)
        if decoder.peekType(Tlv.Interest, len(element)):
            interest = Interest()
            interest.wireDecode(element, TlvWireFormat.get())

            if lpPacket != None:
                interest.setLpPacket(lpPacket)
        elif decoder.peekType(Tlv.Data, len(element)):
            data = Data()
            data.wireDecode(element, TlvWireFormat.get())

            if lpPacket != None:
                data.setLpPacket(lpPacket)

        if lpPacket != None:
            # We have decoded the fragment, so remove the wire encoding to save
            #   memory.
            lpPacket.setFragmentWireEncoding(Blob())

            networkNack = NetworkNack.getFirstHeader(lpPacket)
            if networkNack != None:
                if interest == None:
                    # We got a Nack but not for an Interest, so drop the packet.
                    return

                pendingInterests = []
                self._pendingInterestTable.extractEntriesForNackInterest(
                  interest, pendingInterests)
                for pendingInterest in pendingInterests:
                    try:
                        pendingInterest.getOnNetworkNack()(
                          pendingInterest.getInterest(), networkNack)
                    except:
                        logging.exception("Error in onNetworkNack")

                # We have processed the network Nack packet.
                return

        # Now process as Interest or Data.
        if interest != None:
            # Call all interest filter callbacks which match.
            matchedFilters = []
            self._interestFilterTable.getMatchedFilters(interest, matchedFilters)
            for i in range(len(matchedFilters)):
                entry = matchedFilters[i]
                includeFilter = True
                onInterestCall = entry.getOnInterest()
                # If onInterest is not a function nor a method assumes it is a
                # calleable object
                if (not inspect.isfunction(onInterestCall) and
                    not inspect.ismethod(onInterestCall)):
                    onInterestCall = onInterestCall.__call__
                # Use getcallargs to test if onInterest accepts 5 args.
                try:
                    inspect.getcallargs(onInterestCall,
                      None, None, None, None, None)
                except TypeError:
                    # Assume onInterest is old-style with 4 arguments.
                    includeFilter = False

                if includeFilter:
                    try:
                        entry.getOnInterest()(
                          entry.getFilter().getPrefix(), interest,
                          entry.getFace(), entry.getInterestFilterId(),
                          entry.getFilter())
                    except:
                        logging.exception("Error in onInterest")
                else:
                    # Old-style onInterest without the filter argument. We
                    # still pass a Face instead of Transport since Face also
                    # has a send method.
                    try:
                        entry.getOnInterest()(
                          entry.getFilter().getPrefix(), interest,
                          entry.getFace(), entry.getInterestFilterId())
                    except:
                        logging.exception("Error in onInterest")
        elif data != None:
            pendingInterests = []
            self._pendingInterestTable.extractEntriesForExpressedInterest(
              data, pendingInterests)
            for pendingInterest in pendingInterests:
                try:
                    pendingInterest.getOnData()(pendingInterest.getInterest(), data)
                except:
                    logging.exception("Error in onData")
示例#17
0
文件: node.py 项目: meng72/PyNDN2
    def onReceivedElement(self, element):
        """
        This is called by the transport's ElementReader to process an
        entire received Data or Interest element.

        :param element: The bytes of the incoming element.
        :type element: An array type with int elements
        """
        # The type codes for TLV Interest and Data packets are chosen to not
        #   conflict with the first byte of a binary XML packet, so we canjust
        #   look at the first byte.
        if not (element[0] == Tlv.Interest or element[0] == Tlv.Data):
            # Ignore non-TLV elements.
            # Assume it is Binary XML.
            if not WireFormat.ENABLE_NDNX:
                raise RuntimeError(
                  "BinaryXmlWireFormat (NDNx) is deprecated. To enable while you upgrade your network to use NDN-TLV, set WireFormat.ENABLE_NDNX = True")

            return

        # First, decode as Interest or Data.
        interest = None
        data = None
        decoder = TlvDecoder(element)
        if decoder.peekType(Tlv.Interest, len(element)):
            interest = Interest()
            interest.wireDecode(element, TlvWireFormat.get())
        elif decoder.peekType(Tlv.Data, len(element)):
            data = Data()
            data.wireDecode(element, TlvWireFormat.get())

        # Now process as Interest or Data.
        if interest != None:
            # Call all interest filter callbacks which match.
            for i in range(len(self._interestFilterTable)):
                entry = self._interestFilterTable[i]
                if entry.getFilter().doesMatch(interest.getName()):
                    includeFilter = True
                    # Use getcallargs to test if onInterest accepts 5 args.
                    try:
                        inspect.getcallargs(entry.getOnInterest(),
                          None, None, None, None, None)
                    except TypeError:
                        # Assume onInterest is old-style with 4 arguments.
                        includeFilter = False

                    if includeFilter:
                        entry.getOnInterest()(
                          entry.getFilter().getPrefix(), interest,
                          entry.getFace(), entry.getInterestFilterId(),
                          entry.getFilter())
                    else:
                        # Old-style onInterest without the filter argument. We
                        # still pass a Face instead of Transport since Face also
                        # has a send method.
                        entry.getOnInterest()(
                          entry.getFilter().getPrefix(), interest,
                          entry.getFace(), entry.getInterestFilterId())
        elif data != None:
            pendingInterests = self._extractEntriesForExpressedInterest(
              data.getName())
            for pendingInterest in pendingInterests:
                pendingInterest.getOnData()(pendingInterest.getInterest(), data)
示例#18
0
文件: node.py 项目: named-data/PyNDN2
    def onReceivedElement(self, element):
        """
        This is called by the transport's ElementReader to process an
        entire received Data or Interest element.

        :param element: The bytes of the incoming element.
        :type element: An array type with int elements
        """

        lpPacket = None
        if element[0] == Tlv.LpPacket_LpPacket:
            # Decode the LpPacket and replace element with the fragment.
            lpPacket = LpPacket()
            # Set copy False so that the fragment is a slice which will be
            # copied below. The header fields are all integers and don't need to
            # be copied.
            TlvWireFormat.get().decodeLpPacket(lpPacket, element, False)
            element = lpPacket.getFragmentWireEncoding().buf()

        # First, decode as Interest or Data.
        interest = None
        data = None
        decoder = TlvDecoder(element)
        if decoder.peekType(Tlv.Interest, len(element)):
            interest = Interest()
            interest.wireDecode(element, TlvWireFormat.get())

            if lpPacket != None:
                interest.setLpPacket(lpPacket)
        elif decoder.peekType(Tlv.Data, len(element)):
            data = Data()
            data.wireDecode(element, TlvWireFormat.get())

            if lpPacket != None:
                data.setLpPacket(lpPacket)

        if lpPacket != None:
            # We have decoded the fragment, so remove the wire encoding to save
            #   memory.
            lpPacket.setFragmentWireEncoding(Blob())

            networkNack = NetworkNack.getFirstHeader(lpPacket)
            if networkNack != None:
                if interest == None:
                    # We got a Nack but not for an Interest, so drop the packet.
                    return

                pendingInterests = []
                self._pendingInterestTable.extractEntriesForNackInterest(
                  interest, pendingInterests)
                for pendingInterest in pendingInterests:
                    try:
                        pendingInterest.getOnNetworkNack()(
                          pendingInterest.getInterest(), networkNack)
                    except:
                        logging.exception("Error in onNetworkNack")

                # We have processed the network Nack packet.
                return

        # Now process as Interest or Data.
        if interest != None:
            self._dispatchInterest(interest)
        elif data != None:
            self._satisfyPendingInterests(data)
示例#19
0
    def decodeControlParameters(self, controlParameters, input):
        """
        Decode input as an NDN-TLV ControlParameters and set the fields of the
        controlParameters object.

        :param ControlParameters controlParameters: The ControlParameters object
          whose fields are updated.
        :param input: The array with the bytes to decode.
        :type input: An array type with int elements
        """
        controlParameters.clear()

        decoder = TlvDecoder(input)
        endOffset = decoder.readNestedTlvsStart(
            Tlv.ControlParameters_ControlParameters)

        # decode name
        if decoder.peekType(Tlv.Name, endOffset):
            name = Name()
            self._decodeName(name, decoder)
            controlParameters.setName(name)

        # decode face ID
        controlParameters.setFaceId(
            decoder.readOptionalNonNegativeIntegerTlv(
                Tlv.ControlParameters_FaceId, endOffset))

        # decode URI
        if decoder.peekType(Tlv.ControlParameters_Uri, endOffset):
            uri = Blob(
                decoder.readOptionalBlobTlv(Tlv.ControlParameters_Uri,
                                            endOffset), False)
            controlParameters.setUri(str(uri))

        # decode integers
        controlParameters.setLocalControlFeature(
            decoder.readOptionalNonNegativeIntegerTlv(
                Tlv.ControlParameters_LocalControlFeature, endOffset))
        controlParameters.setOrigin(
            decoder.readOptionalNonNegativeIntegerTlv(
                Tlv.ControlParameters_Origin, endOffset))
        controlParameters.setCost(
            decoder.readOptionalNonNegativeIntegerTlv(
                Tlv.ControlParameters_Cost, endOffset))

        # set forwarding flags
        if decoder.peekType(Tlv.ControlParameters_Flags, endOffset):
            flags = ForwardingFlags()
            flags.setNfdForwardingFlags(
                decoder.readNonNegativeIntegerTlv(Tlv.ControlParameters_Flags))
            controlParameters.setForwardingFlags(flags)

        # decode strategy
        if decoder.peekType(Tlv.ControlParameters_Strategy, endOffset):
            strategyEndOffset = decoder.readNestedTlvsStart(
                Tlv.ControlParameters_Strategy)
            self._decodeName(controlParameters.getStrategy(), decoder)
            decoder.finishNestedTlvs(strategyEndOffset)

        # decode expiration period
        controlParameters.setExpirationPeriod(
            decoder.readOptionalNonNegativeIntegerTlv(
                Tlv.ControlParameters_ExpirationPeriod, endOffset))

        decoder.finishNestedTlvs(endOffset)
示例#20
0
    def onReceivedElement(self, element):
        """
        This is called by the transport's ElementReader to process an
        entire received Data or Interest element.

        :param element: The bytes of the incoming element.
        :type element: An array type with int elements
        """

        lpPacket = None
        if element[0] == Tlv.LpPacket_LpPacket:
            # Decode the LpPacket and replace element with the fragment.
            lpPacket = LpPacket()
            # Set copy False so that the fragment is a slice which will be
            # copied below. The header fields are all integers and don't need to
            # be copied.
            TlvWireFormat.get().decodeLpPacket(lpPacket, element, False)
            element = lpPacket.getFragmentWireEncoding().buf()

        # First, decode as Interest or Data.
        interest = None
        data = None
        decoder = TlvDecoder(element)
        if decoder.peekType(Tlv.Interest, len(element)):
            interest = Interest()
            interest.wireDecode(element, TlvWireFormat.get())

            if lpPacket != None:
                interest.setLpPacket(lpPacket)
        elif decoder.peekType(Tlv.Data, len(element)):
            data = Data()
            data.wireDecode(element, TlvWireFormat.get())

            if lpPacket != None:
                data.setLpPacket(lpPacket)

        if lpPacket != None:
            # We have decoded the fragment, so remove the wire encoding to save
            #   memory.
            lpPacket.setFragmentWireEncoding(Blob())

            networkNack = NetworkNack.getFirstHeader(lpPacket)
            if networkNack != None:
                if interest == None:
                    # We got a Nack but not for an Interest, so drop the packet.
                    return

                pendingInterests = []
                self._pendingInterestTable.extractEntriesForNackInterest(
                    interest, pendingInterests)
                for pendingInterest in pendingInterests:
                    try:
                        pendingInterest.getOnNetworkNack()(
                            pendingInterest.getInterest(), networkNack)
                    except:
                        logging.exception("Error in onNetworkNack")

                # We have processed the network Nack packet.
                return

        # Now process as Interest or Data.
        if interest != None:
            self._dispatchInterest(interest)
        elif data != None:
            self._satisfyPendingInterests(data)