Esempio n. 1
0
    def decodeData(self, data, input):
        """
        Decode input as an NDN-TLV data packet, set the fields in the data
        object, and return the signed offsets.

        :param Data data: The Data 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.
        :rtype: (int, int)
        """
        decoder = TlvDecoder(input)

        endOffset = decoder.readNestedTlvsStart(Tlv.Data)
        signedPortionBeginOffset = decoder.getOffset()

        self._decodeName(data.getName(), decoder)
        self._decodeMetaInfo(data.getMetaInfo(), decoder)
        data.setContent(Blob(decoder.readBlobTlv(Tlv.Content)))
        self._decodeSignatureInfo(data, decoder)

        signedPortionEndOffset = decoder.getOffset()
        data.getSignature().setSignature(
            Blob(decoder.readBlobTlv(Tlv.SignatureValue)))

        decoder.finishNestedTlvs(endOffset)
        return (signedPortionBeginOffset, signedPortionEndOffset)
Esempio n. 2
0
    def wireDecode(self, input):
        """
        Decode the input and update this Schedule object.

        :param input: The array with the bytes to decode.
        :type input: An array type with int elements
        :raises ValueError: For invalid encoding.
        """
        # If input is a blob, get its buf().
        decodeBuffer = input.buf() if isinstance(input, Blob) else input

        # For now, don't use WireFormat and hardcode to use TLV since the
        # encoding doesn't go out over the wire, only into the local SQL database.
        decoder = TlvDecoder(decodeBuffer)

        endOffset = decoder.readNestedTlvsStart(Tlv.Encrypt_Schedule)

        # Decode the whiteIntervalList.
        self._whiteIntervalList = []
        listEndOffset = decoder.readNestedTlvsStart(Tlv.Encrypt_WhiteIntervalList)
        while decoder.getOffset() < listEndOffset:
            Schedule._sortedSetAdd(
              self._whiteIntervalList, Schedule._decodeRepetitiveInterval(decoder))
        decoder.finishNestedTlvs(listEndOffset)

        # Decode the blackIntervalList.
        self._blackIntervalList = []
        listEndOffset = decoder.readNestedTlvsStart(Tlv.Encrypt_BlackIntervalList)
        while decoder.getOffset() < listEndOffset:
            Schedule._sortedSetAdd(
              self._blackIntervalList, Schedule._decodeRepetitiveInterval(decoder))
        decoder.finishNestedTlvs(listEndOffset)

        decoder.finishNestedTlvs(endOffset)
Esempio n. 3
0
    def wireDecode(self, input):
        """
        Decode the input and update this Schedule object.

        :param input: The array with the bytes to decode.
        :type input: An array type with int elements
        :raises ValueError: For invalid encoding.
        """
        # If input is a blob, get its buf().
        decodeBuffer = input.buf() if isinstance(input, Blob) else input

        # For now, don't use WireFormat and hardcode to use TLV since the
        # encoding doesn't go out over the wire, only into the local SQL database.
        decoder = TlvDecoder(decodeBuffer)

        endOffset = decoder.readNestedTlvsStart(Tlv.Encrypt_Schedule)

        # Decode the whiteIntervalList.
        self._whiteIntervalList = []
        listEndOffset = decoder.readNestedTlvsStart(Tlv.Encrypt_WhiteIntervalList)
        while decoder.getOffset() < listEndOffset:
            Schedule._sortedSetAdd(self._whiteIntervalList, Schedule._decodeRepetitiveInterval(decoder))
        decoder.finishNestedTlvs(listEndOffset)

        # Decode the blackIntervalList.
        self._blackIntervalList = []
        listEndOffset = decoder.readNestedTlvsStart(Tlv.Encrypt_BlackIntervalList)
        while decoder.getOffset() < listEndOffset:
            Schedule._sortedSetAdd(self._blackIntervalList, Schedule._decodeRepetitiveInterval(decoder))
        decoder.finishNestedTlvs(listEndOffset)

        decoder.finishNestedTlvs(endOffset)
Esempio n. 4
0
    def decodeData(self, data, input):
        """
        Decode input as an NDN-TLV data packet, set the fields in the data
        object, and return the signed offsets.

        :param Data data: The Data 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.
        :rtype: (int, int)
        """
        decoder = TlvDecoder(input)

        endOffset = decoder.readNestedTlvsStart(Tlv.Data)
        signedPortionBeginOffset = decoder.getOffset()

        self._decodeName(data.getName(), decoder)
        self._decodeMetaInfo(data.getMetaInfo(), decoder)
        data.setContent(Blob(decoder.readBlobTlv(Tlv.Content)))
        self._decodeSignatureInfo(data, decoder)

        signedPortionEndOffset = decoder.getOffset()
        # TODO: The library needs to handle other signature types than
        #   SignatureSha256WithRsa.
        data.getSignature().setSignature(Blob(decoder.readBlobTlv(Tlv.SignatureValue)))

        decoder.finishNestedTlvs(endOffset)
        return (signedPortionBeginOffset, signedPortionEndOffset)
Esempio n. 5
0
    def wireDecode(self, input):
        """
        Decode the input as an NDN-TLV SafeBag and update this object.

        :param input: The array with the bytes to decode.
        :type input: A Blob or an array type with int elements
        """
        if isinstance(input, Blob):
          input = input.buf()

        # Decode directly as TLV. We don't support the WireFormat abstraction
        # because this isn't meant to go directly on the wire.
        decoder = TlvDecoder(input)
        endOffset = decoder.readNestedTlvsStart(Tlv.SafeBag_SafeBag)

        # Get the bytes of the certificate and decode.
        certificateBeginOffset = decoder.getOffset()
        certificateEndOffset = decoder.readNestedTlvsStart(Tlv.Data)
        decoder.seek(certificateEndOffset)
        self._certificate = Data()
        self._certificate.wireDecode(
          decoder.getSlice(certificateBeginOffset, certificateEndOffset),
          TlvWireFormat.get())

        self._privateKeyBag = Blob(
          decoder.readBlobTlv(Tlv.SafeBag_EncryptedKeyBag), True)

        decoder.finishNestedTlvs(endOffset)
Esempio n. 6
0
    def decodeDelegationSet(self, delegationSet, input):
        """
        Decode input as a DelegationSet in NDN-TLV and set the fields of the
        delegationSet object. Note that the sequence of Delegation does not have
        an outer TLV type and length because it is intended to use the type and
        length of a Data packet's Content. This ignores any elements after the
        sequence of Delegation.

        :param DelegationSet delegationSet: The DelegationSet 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 = len(input)

        delegationSet.clear()
        while decoder.getOffset() < endOffset:
            decoder.readTypeAndLength(Tlv.Link_Delegation)
            preference = decoder.readNonNegativeIntegerTlv(Tlv.Link_Preference)
            name = Name()
            Tlv0_1_1WireFormat._decodeName(name, decoder)

            # Add unsorted to preserve the order so that Interest selected
            # delegation index will work.
            delegationSet.addUnsorted(preference, name)
Esempio n. 7
0
    def wireDecode(self, input):
        """
        Decode the input as an NDN-TLV SafeBag and update this object.

        :param input: The array with the bytes to decode.
        :type input: A Blob or an array type with int elements
        """
        if isinstance(input, Blob):
            input = input.buf()

        # Decode directly as TLV. We don't support the WireFormat abstraction
        # because this isn't meant to go directly on the wire.
        decoder = TlvDecoder(input)
        endOffset = decoder.readNestedTlvsStart(Tlv.SafeBag_SafeBag)

        # Get the bytes of the certificate and decode.
        certificateBeginOffset = decoder.getOffset()
        certificateEndOffset = decoder.readNestedTlvsStart(Tlv.Data)
        decoder.seek(certificateEndOffset)
        self._certificate = Data()
        self._certificate.wireDecode(
            decoder.getSlice(certificateBeginOffset, certificateEndOffset),
            TlvWireFormat.get())

        self._privateKeyBag = Blob(
            decoder.readBlobTlv(Tlv.SafeBag_EncryptedKeyBag), True)

        decoder.finishNestedTlvs(endOffset)
Esempio n. 8
0
    def decodeStateVector(input):
        """
        Decode the input as a TLV state vector.

        :param input: The array with the bytes to decode.
        :type input: An array type with int elements
        :return: A new dictionary where the key is the member ID string and the
          value is the sequence number. If the input encoding has repeated
          entries with the same member ID, this uses only the last entry.
        :rtype: dict<str,int>
        :raises ValueError: For invalid encoding.
        """
        stateVector = {}

        # If input is a blob, get its buf().
        decodeBuffer = input.buf() if isinstance(input, Blob) else input
        decoder = TlvDecoder(decodeBuffer)

        endOffset = decoder.readNestedTlvsStart(
            StateVectorSync2018.TLV_StateVector)

        while decoder.getOffset() < endOffset:
            entryEndOffset = decoder.readNestedTlvsStart(
                StateVectorSync2018.TLV_StateVectorEntry)

            memberIdBlob = Blob(
                decoder.readBlobTlv(
                    StateVectorSync2018.TLV_StateVector_MemberId), False)
            stateVector[str(memberIdBlob)] = decoder.readNonNegativeIntegerTlv(
                StateVectorSync2018.TLV_StateVector_SequenceNumber)
            decoder.finishNestedTlvs(entryEndOffset)

        decoder.finishNestedTlvs(endOffset)

        return stateVector
Esempio n. 9
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):
        decoder = TlvDecoder(wire)

        beginOffset = decoder.getOffset()
        endOffset = decoder.readNestedTlvsStart(Tlv.SignatureInfo)

        signatureType = decoder.readNonNegativeIntegerTlv(Tlv.SignatureType)
        if signatureType != Tlv.SignatureType_Sha256WithAbsSignature:
            raise RuntimeError("Invalid SignatureType code: expected %d, got %d" % (Tlv.SignatureType_Sha256WithAbsSignature, signatureType))

        keyLocator = KeyLocator()
        Tlv0_2WireFormat._decodeKeyLocator(Tlv.KeyLocator, keyLocator, decoder, True)

        self._keyLocator = ChangeCounter(keyLocator)

        # if decoder.peekType(Tlv.ValidityPeriod_ValidityPeriod, endOffset):
        #     Tlv0_2WireFormat._decodeValidityPeriod(
        #         signatureInfo.getValidityPeriod(), decoder)

        decoder.finishNestedTlvs(endOffset)
Esempio n. 11
0
    def wireDecode(self, input):
        """
        Decode the input as an NDN-TLV PSyncContent and update this object.

        :param input: The array with the bytes to decode.
        :type input: Blob or an array type with int elements
        """
        # If input is a blob, get its buf().
        decodeBuffer = input.buf() if isinstance(input, Blob) else input

        self.clear()

        # Decode directly as TLV. We don't support the WireFormat abstraction
        # because this isn't meant to go directly on the wire.
        decoder = TlvDecoder(decodeBuffer)
        endOffset = decoder.readNestedTlvsStart(PSyncState.Tlv_PSyncContent)

        # Decode a sequence of Name.
        while decoder.getOffset() < len(decodeBuffer):
            name = Name()
            Tlv0_3WireFormat._decodeName(name, decoder, True)
            self._content.append(name)

        decoder.finishNestedTlvs(endOffset)
Esempio n. 12
0
    def findElementEnd(self, input):
        """
        Continue scanning input starting from self._offset to find the element 
        end.  If the end of the element which started at offset 0 is found, 
        this returns True and getOffset() is the length of the element.  
        Otherwise, this returns False which means you should read more into 
        input and call again.
        
        :param input: The input buffer. You have to pass in input each time 
          because the buffer could be reallocated.
        :type input: An array type with int elements
        :return: True if found the element end, False if not.
        :rtype: bool
        """
        if self._gotElementEnd:
            # Someone is calling when we already got the end.
            return True

        decoder = TlvDecoder(input)

        while True:
            if self._offset >= len(input):
                # All the cases assume we have some input. Return and wait 
                #   for more.
                return False

            if self._state == self.READ_TYPE:
                firstOctet = input[self._offset]
                self._offset += 1
                if firstOctet < 253:
                    # The value is simple, so we can skip straight to reading 
                    #   the length.
                    self._state = self.READ_LENGTH
                else:
                    # Set up to skip the type bytes.
                    if firstOctet == 253:
                        self._nBytesToRead = 2
                    elif firstOctet == 254:
                        self._nBytesToRead = 4
                    else:
                        # value == 255.
                        self._nBytesToRead = 8

                    self._state = self.READ_TYPE_BYTES
            elif self._state == self.READ_TYPE_BYTES:
                nRemainingBytes = len(input) - self._offset
                if nRemainingBytes < self._nBytesToRead:
                    # Need more.
                    self._offset += nRemainingBytes
                    self._nBytesToRead -= nRemainingBytes
                    return False

                # Got the type bytes. Move on to read the length.
                self._offset += self._nBytesToRead
                self._state = self.READ_LENGTH
            elif self._state == self.READ_LENGTH:
                firstOctet = input[self._offset]
                self._offset += 1
                if firstOctet < 253:
                    # The value is simple, so we can skip straight to reading 
                    #  the value bytes.
                    self._nBytesToRead = firstOctet
                    if self._nBytesToRead == 0:
                        # No value bytes to read. We're finished.
                        self._gotElementEnd = True
                        return True

                    self._state = self.READ_VALUE_BYTES
                else:
                    # We need to read the bytes in the extended encoding of 
                    #  the length.
                    if firstOctet == 253:
                        self._nBytesToRead = 2
                    elif firstOctet == 254:
                        self._nBytesToRead = 4
                    else:
                        # value == 255.
                        self._nBytesToRead = 8

                    # We need to use firstOctet in the next state.
                    self._firstOctet = firstOctet
                    self._state = self.READ_LENGTH_BYTES
            elif self._state == self.READ_LENGTH_BYTES:
                nRemainingBytes = len(input) - self._offset
                if (not self._useHeaderBuffer and 
                    nRemainingBytes >= self._nBytesToRead):
                    # We don't have to use the headerBuffer. Set nBytesToRead.
                    decoder.seek(self._offset)

                    self._nBytesToRead = decoder.readExtendedVarNumber(
                      self._firstOctet)
                    # Update self._offset to the decoder's offset after reading.
                    self._offset = decoder.getOffset()
                else:
                    self._useHeaderBuffer = True

                    nNeededBytes = self._nBytesToRead - self._headerLength
                    if nNeededBytes > nRemainingBytes:
                        # We can't get all of the header bytes from this input. 
                        # Save in headerBuffer.
                        if (self._headerLength + nRemainingBytes > 
                              len(self._headerBuffer)):
                            # We don't expect this to happen.
                            raise RuntimeError(
                 "Cannot store more header bytes than the size of headerBuffer")
                        self._headerBuffer[
                          self._headerLength:self._headerLength + nRemainingBytes] = \
                          input[self._offset:self._offset + nRemainingBytes]
                        self._offset += nRemainingBytes
                        self._headerLength += nRemainingBytes

                        return False

                    # Copy the remaining bytes into headerBuffer, read the 
                    #   length and set nBytesToRead.
                    if (self._headerLength + nNeededBytes > 
                          len(self._headerBuffer)):
                        # We don't expect this to happen.
                        raise RuntimeError(
                 "Cannot store more header bytes than the size of headerBuffer")
                    self._headerBuffer[
                      self._headerLength:self._headerLength + nNeededBytes] = \
                      input[self._offset:self._offset + nNeededBytes]
                    self._offset += nNeededBytes

                    # Use a local decoder just for the headerBuffer.
                    bufferDecoder = TlvDecoder(self._headerBuffer)
                    # Replace nBytesToRead with the length of the value.
                    self._nBytesToRead = bufferDecoder.readExtendedVarNumber(
                      self._firstOctet)

                if self._nBytesToRead == 0:
                    # No value bytes to read. We're finished.
                    self._gotElementEnd = True
                    return True

                # Get ready to read the value bytes.
                self._state = self.READ_VALUE_BYTES
            elif self._state == self.READ_VALUE_BYTES:
                nRemainingBytes = len(input) - self._offset
                if nRemainingBytes < self._nBytesToRead:
                    # Need more.
                    self._offset += nRemainingBytes
                    self._nBytesToRead -= nRemainingBytes
                    return False

                # Got the bytes. We're finished.
                self._offset += self._nBytesToRead
                self._gotElementEnd = True
                return True
            else:
                # We don't expect this to happen.
                raise RuntimeError("findElementEnd: unrecognized state")