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))
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))
def _encodeSignatureInfo(signature, encoder): """ An internal method to encode signature as the appropriate form of SignatureInfo in NDN-TLV. :param Signature signature: An object of a subclass of Signature to encode. :param TlvEncoder encoder: The TlvEncoder to receive the encoding. """ if isinstance(signature, GenericSignature): # Handle GenericSignature separately since it has the entire encoding. encoding = signature.getSignatureInfoEncoding() # Do a test decoding to sanity check that it is valid TLV. try: decoder = TlvDecoder(encoding.buf()) endOffset = decoder.readNestedTlvsStart(Tlv.SignatureInfo) decoder.readNonNegativeIntegerTlv(Tlv.SignatureType) decoder.finishNestedTlvs(endOffset) except ValueError as ex: raise ValueError( "The GenericSignature encoding is not a valid NDN-TLV SignatureInfo: " + ex) encoder.writeBuffer(encoding.buf()) return saveLength = len(encoder) if isinstance(signature, Sha256WithRsaSignature): # Encode backwards. Tlv0_1_1WireFormat._encodeKeyLocator( Tlv.KeyLocator, signature.getKeyLocator(), encoder) encoder.writeNonNegativeIntegerTlv( Tlv.SignatureType, Tlv.SignatureType_SignatureSha256WithRsa) elif isinstance(signature, Sha256WithEcdsaSignature): # Encode backwards. Tlv0_1_1WireFormat._encodeKeyLocator( Tlv.KeyLocator, signature.getKeyLocator(), encoder) encoder.writeNonNegativeIntegerTlv( Tlv.SignatureType, Tlv.SignatureType_SignatureSha256WithEcdsa) elif isinstance(signature, HmacWithSha256Signature): Tlv0_1_1WireFormat._encodeKeyLocator( Tlv.KeyLocator, signature.getKeyLocator(), encoder) encoder.writeNonNegativeIntegerTlv( Tlv.SignatureType, Tlv.SignatureType_SignatureHmacWithSha256) elif isinstance(signature, DigestSha256Signature): encoder.writeNonNegativeIntegerTlv( Tlv.SignatureType, Tlv.SignatureType_DigestSha256) else: raise RuntimeError( "encodeSignatureInfo: Unrecognized Signature object type") encoder.writeTypeAndLength(Tlv.SignatureInfo, len(encoder) - saveLength)
def onData(self, interest, responseData): """ We received the response. Do a quick check of expected name components. """ if self._isNfdCommand: # Decode responseData->getContent() and check for a success code. # TODO: Move this into the TLV code. statusCode = None try: decoder = TlvDecoder(responseData.getContent().buf()) decoder.readNestedTlvsStart(Tlv.NfdCommand_ControlResponse) statusCode = decoder.readNonNegativeIntegerTlv( Tlv.NfdCommand_StatusCode) except ValueError: # Error decoding the ControlResponse. self._onRegisterFailed_(self._prefix) return # Status code 200 is "OK". if statusCode != 200: self._onRegisterFailed_(self._prefix) # Otherwise, silently succeed. else: expectedName = Name("/ndnx/.../selfreg") if (responseData.getName().size() < 4 or responseData.getName()[0] != expectedName[0] or responseData.getName()[2] != expectedName[2]): self._onRegisterFailed(self._prefix) return
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)
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 onData(self, interest, responseData): """ We received the response. Do a quick check of expected name components. """ if self._isNfdCommand: # Decode responseData->getContent() and check for a success code. # TODO: Move this into the TLV code. statusCode = None try: decoder = TlvDecoder(responseData.getContent().buf()) decoder.readNestedTlvsStart(Tlv.NfdCommand_ControlResponse) statusCode = decoder.readNonNegativeIntegerTlv(Tlv.NfdCommand_StatusCode) except ValueError: # Error decoding the ControlResponse. self._onRegisterFailed_(self._prefix) return # Status code 200 is "OK". if statusCode != 200: self._onRegisterFailed_(self._prefix) # Otherwise, silently succeed. else: expectedName = Name("/ndnx/.../selfreg") if (responseData.getName().size() < 4 or responseData.getName()[0] != expectedName[0] or responseData.getName()[2] != expectedName[2]): self._onRegisterFailed(self._prefix) return
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
def onData(self, interest, responseData): """ We received the response. Do a quick check of expected name components. """ if self._isNfdCommand: # Decode responseData->getContent() and check for a success code. # TODO: Move this into the TLV code. statusCode = None try: decoder = TlvDecoder(responseData.getContent().buf()) decoder.readNestedTlvsStart(Tlv.NfdCommand_ControlResponse) statusCode = decoder.readNonNegativeIntegerTlv(Tlv.NfdCommand_StatusCode) except ValueError as ex: logging.getLogger(__name__).info( "Register prefix failed: Error decoding the NFD response: %s", str(ex)) self._onRegisterFailed(self._prefix) return # Status code 200 is "OK". if statusCode != 200: logging.getLogger(__name__).info( "Register prefix failed: Expected NFD status code 200, got: %d", statusCode) self._onRegisterFailed(self._prefix) return logging.getLogger(__name__).info( "Register prefix succeeded with the NFD forwarder for prefix %s", self._prefix.toUri()) else: expectedName = Name("/ndnx/.../selfreg") if (responseData.getName().size() < 4 or responseData.getName()[0] != expectedName[0] or responseData.getName()[2] != expectedName[2]): logging.getLogger(__name__).info( "Register prefix failed: Unexpected name in NDNx response: %s", responseData.getName().toUri()) self._onRegisterFailed(self._prefix) return logging.getLogger(__name__).info( "Register prefix succeeded with the NDNx forwarder for prefix %s", self._prefix.toUri())
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)
def decodeEncryptedContent(self, encryptedContent, input): """ Decode input as an EncryptedContent in NDN-TLV and set the fields of the encryptedContent object. :param EncryptedContent encryptedContent: The EncryptedContent 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.Encrypt_EncryptedContent) Tlv0_1_1WireFormat._decodeKeyLocator( Tlv.KeyLocator, encryptedContent.getKeyLocator(), decoder) encryptedContent.setAlgorithmType( decoder.readNonNegativeIntegerTlv(Tlv.Encrypt_EncryptionAlgorithm)) encryptedContent.setInitialVector( Blob(decoder.readOptionalBlobTlv (Tlv.Encrypt_InitialVector, endOffset), True)) encryptedContent.setPayload( Blob(decoder.readBlobTlv(Tlv.Encrypt_EncryptedPayload), True)) decoder.finishNestedTlvs(endOffset)
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)