ttlv

package
v0.0.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 29, 2021 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package ttlv encodes and decodes the 3 wire formats defined in the KMIP specification:

1. TTLV (the default, binary wire format) 2. JSON 3. XML

The core representation of KMIP values is the ttlv.TTLV type, which is a []byte encoded in the TTLV binary format. The ttlv.TTLV type knows how to marshal/ unmarshal to and from the JSON and XML encoding formats.

This package also knows how to marshal and unmarshal ttlv.TTLV values to golang structs, in a way similar to the json or xml packages.

See Marshal() and Unmarshal() for the rules about how golang values map to KMIP TTLVs. Encoder and Decoder can be used to process streams of KMIP values.

This package holds a registry of type, tag, and enum value names, which are used to transcode strings into these values. KMIP 1.4 names will be automatically loaded into the DefaultRegistry. See the kmip20 package to add definitions for 2.0 names.

Print() and PrettyPrintHex() can be used to debug TTLV values.

Example (Json)
input := `{"tag":"KeyFormatType","type":"Enumeration","value":"X_509"}`
var output TTLV

_ = json.Unmarshal([]byte(input), &output)
fmt.Println(output)

b, _ := json.Marshal(output)
fmt.Println(string(b))
Output:

KeyFormatType (Enumeration/4): X_509
{"tag":"KeyFormatType","type":"Enumeration","value":"X_509"}
Example (Xml)
input := `<Operation type="Enumeration" value="Activate"></Operation>`
var output TTLV

_ = xml.Unmarshal([]byte(input), &output)
fmt.Println(output)

b, _ := xml.Marshal(output)
fmt.Println(string(b))
Output:

Operation (Enumeration/4): Activate
<Operation type="Enumeration" value="Activate"></Operation>

Index

Examples

Constants

View Source
const TagNone = Tag(0)

Variables

View Source
var ErrHeaderTruncated = errors.New("header truncated")
View Source
var ErrIntOverflow = fmt.Errorf("value exceeds max int value %d", math.MaxInt32)
View Source
var ErrInvalidHexString = kmiputil.ErrInvalidHexString
View Source
var ErrInvalidLen = errors.New("invalid length")
View Source
var ErrInvalidTag = errors.New("invalid tag")
View Source
var ErrInvalidType = errors.New("invalid KMIP type")
View Source
var ErrNoTag = errors.New("unable to determine tag for field")
View Source
var ErrTagConflict = errors.New("tag conflict")
View Source
var ErrUnexpectedValue = errors.New("no field was found to unmarshal value into")
View Source
var ErrUnregisteredEnumName = merry.New("unregistered enum name")
View Source
var ErrUnsupportedEnumTypeError = errors.New("unsupported type for enums, must be string, or int types")
View Source
var ErrUnsupportedTypeError = errors.New("marshaling/unmarshaling is not supported for this type")
View Source
var ErrValueTruncated = errors.New("value truncated")

Functions

func Details

func Details(err error) string

Details prints details from the error, including a stacktrace when available.

func FormatEnum

func FormatEnum(v uint32, enumMap EnumMap) string

FormatEnum formats an uint32 as a KMIP Enumeration string, as described in the KMIP Profiles spec. If the value is registered, the normalized name of the value will be returned. Otherwise, a four byte hex string is returned. Examples:

- SymmetricKey - 0x00000002

func FormatInt

func FormatInt(i int32, enumMap EnumMap) string

FormatInt formats an integer as a KMIP bitmask string, as described in the KMIP Profiles spec for JSON under the "Special case for Masks" section. Examples:

- 0x0000100c - Encrypt|Decrypt|CertificateSign - CertificateSign|0x00000004|0x0000008 - CertificateSign|0x0000000c

func FormatTag

func FormatTag(v uint32, enumMap EnumMap) string

FormatTag formats an uint32 as a KMIP Tag string, as described in the KMIP Profiles spec. If the value is registered, the normalized name of the value will be returned. Otherwise, a 3 byte hex string is returned. Examples:

- ActivationDate - 0x420001

func FormatTagCanonical

func FormatTagCanonical(v uint32, enumMap EnumMap) string

FormatTagCanonical formats an uint32 as a canonical Tag name from the KMIP spec. If the value is registered, the canonical name of the value will be returned. Otherwise, a 3 byte hex string is returned. Examples:

- Activation Date - 0x420001

Canonical tag names are used in the AttributeName of Attribute structs.

func FormatType

func FormatType(b byte, enumMap EnumMap) string

FormatType formats a byte as a KMIP Type string, as described in the KMIP Profiles spec. If the value is registered, the normalized name of the value will be returned.

Otherwise, a 1 byte hex string is returned, but this is not technically a valid encoding for types in the JSON and XML encoding specs. Hex values Should only be used for debugging. Examples:

- Integer - 0x42

func Hex2bytes

func Hex2bytes(s string) []byte

Hex2bytes converts hex string to bytes. Any non-hex characters in the string are stripped first. panics on error

func NormalizeName

func NormalizeName(s string) string

NormalizeName tranforms KMIP names from the spec into the normalized form of the name. Typically, this means removing spaces, and replacing some special characters. The normalized form of the name is used in the JSON and XML encodings from the KMIP Profiles. The spec describes the normalization process in 5.4.1.1 and 5.5.1.1

func ParseEnum

func ParseEnum(s string, enumMap EnumMap) (uint32, error)

ParseEnum parses a string into a uint32 according to the rules in the KMIP Profiles regarding encoding enumeration values. See FormatEnum for examples of the formats which can be parsed. It will also parse numeric strings. Examples:

    ParseEnum("UnableToCancel", registry.EnumForTag(TagCancellationResult))
	   ParseEnum("0x00000002")
	   ParseEnum("2")

Returns ErrInvalidHexString if the string is invalid hex, or if the hex value is less than 1 byte or more than 4 bytes (ignoring leading zeroes).

Returns ErrUnregisteredEnumName if string value is not a registered enum value name.

func ParseInt

func ParseInt(s string, enumMap EnumMap) (int32, error)

ParseInt parses a string into an int32 according the rules in the KMIP Profiles regarding encoding integers, including the special rules for bitmasks. See FormatInt for examples of the formats which can be parsed.

Returns ErrInvalidHexString if the string is invalid hex, or if the hex value is less than 1 byte or more than 4 bytes (ignoring leading zeroes).

Returns ErrUnregisteredEnumName if string value is not a registered enum value name.

func Print

func Print(w io.Writer, prefix, indent string, t TTLV) error

Print pretty prints the TTLV value in a human-readable format. This format cannot be parsed back into TTLV.

Print is safe to call on any TTLV value, even one which is valid, not correctly encoded, or not actually TTLV bytes. Print will try and print as much of the value as it can decode, and return a parsing error.

Example
b, _ := hex.DecodeString("420069010000002042006a0200000004000000010000000042006b02000000040000000000000000")
_ = Print(os.Stdout, "", "  ", b)
Output:

ProtocolVersion (Structure/32):
  ProtocolVersionMajor (Integer/4): 1
  ProtocolVersionMinor (Integer/4): 0

func PrintPrettyHex

func PrintPrettyHex(w io.Writer, prefix, indent string, t TTLV) error

PrintPrettyHex pretty prints the TTLV value as hex values, with spacers between the segments of the TTLV. Like Print, this is safe to call even on invalid TTLV values. An error will only be returned if there is a problem with the writer.

Example
b, _ := hex.DecodeString("420069010000002042006a0200000004000000010000000042006b02000000040000000000000000")
_ = PrintPrettyHex(os.Stdout, "", "  ", b)
Output:

420069 | 01 | 00000020
  42006a | 02 | 00000004 | 0000000100000000
  42006b | 02 | 00000004 | 0000000000000000

func RegisterTypes

func RegisterTypes(r *Registry)

func Unmarshal

func Unmarshal(ttlv TTLV, v interface{}) error

Unmarshal parses TTLV encoded data and stores the result in the value pointed to by v.

An error will be returned if v is nil or not a point, or if b is not valid TTLV.

Unmarshal will allocate values to store the result in, similar to the json.Marshal. Generally, the destination value can be a pointer or or a direct value. Currently, Unmarshal does not support anonymous fields. They will be ignored. Private fields are ignored.

Unmarshal maps TTLV values to golang values according to the following rules:

  1. If the destination value is interface{}, it will be set to the result of TTLV.Value()
  2. If the destination implements Unmarshaler, that will be called.
  3. If the destination is a slice (except for []byte), append the unmarshalled value to the slice
  4. Structure unmarshals into a struct. See rules below for matching struct fields to the values in the Structure.
  5. Interval unmarshals into an int64
  6. DateTime and DateTimeExtended ummarshal into time.Time
  7. ByteString unmarshals to a []byte
  8. TextString unmarshals into a string
  9. Boolean unmarshals into a bool
  10. Enumeration can unmarshal into an int, int8, int16, int32, or their uint counterparts. If the KMIP value overflows the destination, a *UnmarshalerError with cause ErrIntOverflow is returned.
  11. Integer can unmarshal to the same types as Enumeration, with the same overflow check.
  12. LongInteger unmarshals to int64 or uint64
  13. BitInteger unmarshals to big.Int.

If the destination value is not a supported type, an *UnmarshalerError with cause ErrUnsupportedTypeError is returned. If the source value's type is not recognized, *UnmarshalerError with cause ErrInvalidType is returned.

Unmarshaling Structure

Unmarshal will try to match the values in the Structure with the fields in the destination struct. Structure is an array of values, while a struct is more like a map, so not all Structure values can be accurately represented by a golang struct. In particular, a Structure can hold the same tag multiple times, e.g. 3 TagComment values in a row.

For each field in the struct, Unmarshal infers a KMIP Tag by examining both the name and type of the field. It uses the following rules, in order:

  1. If the type of a field is a struct, and the struct contains a field named "TTLVTag", and the field has a "ttlv" struct tag, the value of the struct tag will be parsed using ParseTag(). If parsing fails, an error is returned. The type and value of the TTLVTag field is ignored. In this example, the F field will map to TagDeactivationDate:

    type Bar struct { F Foo } type Foo struct { TTLVTag struct{} `ttlv:"DeactivationDate"` }

    If Bar uses a struct tag on F indicating a different tag, it is an error:

    type Bar struct { F Foo `ttlv:"DerivationData"` // this will cause an ErrTagConflict // because conflict Bar's field tag // conflicts with Foo's intrinsic tag F2 Foo `ttlv:"0x420034"` // the value can also be hex }

  1. If the type of the field is a struct, and the struct contains a field named "TTLVTag", and that field is of type ttlv.Tag and is not empty, the value of the field will be the inferred Tag. For example:

    type Foo struct { TTLVTag ttlv.Tag } f := Foo{TTLVTag: ttlv.TagState}

    This allows you to dynamically set the KMIP tag that a value will marshal to.

  1. The "ttlv" struct tag can be used to indicate the tag for a field. The value will be parsed with ParseTag()

    type Bar struct { F Foo `ttlv:"DerivationData"` }

4. The name of the field is parsed with ParseTag():

type Bar struct {
    DerivationData int
}

5. The name of the field's type is parsed with ParseTab():

type DerivationData int

type Bar struct {
    dd DerivationData
}

If no tag value can be inferred, the field is ignored. Multiple fields *cannot* map to the same KMIP tag. If they do, an ErrTagConflict will be returned.

Each value in the Structure will be matched against the first field in the struct with the same inferred tag.

If the value cannot be matched with a field, Unmarshal will look for the first field with the "any" struct flag set and unmarshal into that:

type Foo struct {
    Comment string                            // the Comment will unmarshal into this
    EverythingElse []interface{}  `,any`      // all other values will unmarshal into this
    AnotherAny []interface{}  `,any`          // allowed, but ignored.  first any field will always match
    NotLegal []interface{}  `TagComment,any`  // you cannot specify a tag and the any flag.
                                              // will return error
}

If after applying these rules no destination field is found, the KMIP value is ignored.

Types

type DateTimeExtended

type DateTimeExtended struct {
	time.Time
}

DateTimeExtended is a time wrapper which always marshals to a DateTimeExtended.

func (DateTimeExtended) MarshalTTLV

func (t DateTimeExtended) MarshalTTLV(e *Encoder, tag Tag) error

func (*DateTimeExtended) UnmarshalTTLV

func (t *DateTimeExtended) UnmarshalTTLV(d *Decoder, ttlv TTLV) error

type Decoder

type Decoder struct {
	DisallowExtraValues bool
	// contains filtered or unexported fields
}

Decoder reads KMIP values from a stream, and decodes them into golang values. It currently only decodes TTLV encoded KMIP values. TODO: support decoding XML and JSON, so their decoding can be configured

If DisallowExtraValues is true, the decoder will return an error when decoding Structures into structs and a matching field can't get found for every value.

func NewDecoder

func NewDecoder(r io.Reader) *Decoder

func (*Decoder) Decode

func (dec *Decoder) Decode(v interface{}) error

Decode the first KMIP value from the reader into v. See Unmarshal for decoding rules.

func (*Decoder) DecodeValue

func (dec *Decoder) DecodeValue(v interface{}, ttlv TTLV) error

DecodeValue decodes a ttlv value into v. This doesn't read anything from the Decoder's reader. See Unmarshal for decoding rules.

func (*Decoder) NextTTLV

func (dec *Decoder) NextTTLV() (TTLV, error)

NextTTLV reads the next, full KMIP value off the reader.

func (*Decoder) Reset

func (dec *Decoder) Reset(r io.Reader)

Reset resets the internal state of the decoder for reuse.

type Encoder

type Encoder struct {
	// contains filtered or unexported fields
}

func NewEncoder

func NewEncoder(w io.Writer) *Encoder

func (*Encoder) Encode

func (e *Encoder) Encode(v interface{}) error

Encode a single value and flush to the writer. The tag will be inferred from the value. If no tag can be inferred, an error is returned. See Marshal for encoding rules.

func (*Encoder) EncodeBigInteger

func (e *Encoder) EncodeBigInteger(tag Tag, v *big.Int)

func (*Encoder) EncodeBoolean

func (e *Encoder) EncodeBoolean(tag Tag, v bool)

func (*Encoder) EncodeByteString

func (e *Encoder) EncodeByteString(tag Tag, v []byte)

func (*Encoder) EncodeDateTime

func (e *Encoder) EncodeDateTime(tag Tag, v time.Time)

func (*Encoder) EncodeDateTimeExtended

func (e *Encoder) EncodeDateTimeExtended(tag Tag, v time.Time)

func (*Encoder) EncodeEnumeration

func (e *Encoder) EncodeEnumeration(tag Tag, v uint32)

EncodeEnumeration, along with the other Encode<Type> methods, encodes a single KMIP value with the given tag to an internal buffer. These methods do not flush the data to the writer: call Flush() to flush the buffer.

func (*Encoder) EncodeInteger

func (e *Encoder) EncodeInteger(tag Tag, v int32)

func (*Encoder) EncodeInterval

func (e *Encoder) EncodeInterval(tag Tag, v time.Duration)

func (*Encoder) EncodeLongInteger

func (e *Encoder) EncodeLongInteger(tag Tag, v int64)

func (*Encoder) EncodeStructure

func (e *Encoder) EncodeStructure(tag Tag, f func(e *Encoder) error) error

EncodeStructure encodes a Structure with the given tag to the writer. The function argument should encode the enclosed values inside the Structure. Call Flush() to write the data to the writer.

func (*Encoder) EncodeTextString

func (e *Encoder) EncodeTextString(tag Tag, v string)

func (*Encoder) EncodeValue

func (e *Encoder) EncodeValue(tag Tag, v interface{}) error

EncodeValue encodes a single value with the given tag and flushes it to the writer. See Marshal for encoding rules.

func (*Encoder) Flush

func (e *Encoder) Flush() error

Flush flushes the internal encoding buffer to the writer.

type Enum

type Enum struct {
	// contains filtered or unexported fields
}

Enum represents an enumeration of KMIP values (as uint32), and maps them to the canonical string names and the normalized string names of the value as declared in the KMIP specs. Enum is used to transpose values from strings to byte values, as required by the JSON and XML encodings defined in the KMIP Profiles spec. These mappings are also used to pretty print KMIP values, and to marshal and unmarshal enum and bitmask values to golang string values.

Enum currently uses plain maps, so it is not thread safe to register new values concurrently. You should register all values at the start of your program before using this package concurrently.

Enums are used in the KMIP spec for two purposes: for defining the possible values for values encoded as the KMIP Enumeration type, and for bitmask values. Bitmask values are encoded as Integers, but are really enum values bitwise-OR'd together.

Enums are registered with a Registry. The code to register enums is typically generated by the kmipgen tool.

func NewBitmask

func NewBitmask() Enum

func NewEnum

func NewEnum() Enum

func (*Enum) Bitmask

func (e *Enum) Bitmask() bool

func (*Enum) CanonicalName

func (e *Enum) CanonicalName(v uint32) (string, bool)

func (*Enum) Name

func (e *Enum) Name(v uint32) (string, bool)

func (*Enum) RegisterValue

func (e *Enum) RegisterValue(v uint32, name string)

RegisterValue adds a mapping of a uint32 value to a name. The name will be processed by NormalizeName to produce the normalized enum value name as described in the KMIP spec.

func (*Enum) Value

func (e *Enum) Value(name string) (uint32, bool)

func (*Enum) Values

func (e *Enum) Values() []uint32

type EnumMap

type EnumMap interface {
	// Name returns the normalized name for a value, e.g. AttributeName.
	// If the name is not registered, it returns "", false.
	Name(v uint32) (string, bool)
	// CanonicalName returns the canonical name for the value from the spec,
	// e.g. Attribute Name.
	// If the name is not registered, it returns "", false
	CanonicalName(v uint32) (string, bool)
	// Value returns the value registered for the name argument.  If there is
	// no name registered for this value, it returns 0, false.
	// The name argument may be the canonical name (e.g. "Cryptographic Algorithm") or
	// the normalized name (e.g. "CryptographicAlgorithm").
	Value(name string) (uint32, bool)
	// Values returns the complete set of registered values.  The order
	// they are returned in will be the order they are encoded in when
	// encoding bitmasks as strings.
	Values() []uint32
	// Bitmask returns true if this is an enumeration of bitmask flags.
	Bitmask() bool
}

EnumMap defines a set of named enumeration values. Canonical names should be the name from the spec. Names should be in the normalized format described in the KMIP spec (see NormalizeName()).

Value enumerations are used for encoding and decoding KMIP Enumeration values, KMIP Integer bitmask values, Types, and Tags.

type EnumValue

type EnumValue uint32

EnumValue is a uint32 wrapper which always encodes as an enumeration.

func (EnumValue) MarshalTTLV

func (v EnumValue) MarshalTTLV(e *Encoder, tag Tag) error

type Marshaler

type Marshaler interface {
	MarshalTTLV(e *Encoder, tag Tag) error
}

Marshaler knows how to encode itself to TTLV. The implementation should use the primitive methods of the encoder, such as EncodeInteger(), etc.

The tag inferred by the Encoder from the field or type information is passed as an argument, but the implementation can choose to ignore it.

type MarshalerError

type MarshalerError struct {
	// Type is the golang type of the value being marshaled
	Type reflect.Type
	// Struct is the name of the enclosing struct if the marshaled value is a field.
	Struct string
	// Field is the name of the field being marshaled
	Field string
	Tag   Tag
}

func (*MarshalerError) Error

func (e *MarshalerError) Error() string

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry holds all the known tags, types, enums and bitmaps declared in a KMIP spec. It's used throughout the package to map values their canonical and normalized names.

var DefaultRegistry Registry

DefaultRegistry holds the default mappings of types, tags, enums, and bitmasks to canonical names and normalized names from the KMIP spec. It is pre-populated with the 1.4 spec's values. It can be replaced, or additional values can be registered with it.

It is not currently concurrent-safe, so replace or configure it early in your program.

func (*Registry) EnumForTag

func (r *Registry) EnumForTag(t Tag) EnumMap

EnumForTag returns the enum map registered for a tag. Returns nil if no map is registered for this tag.

func (*Registry) FormatEnum

func (r *Registry) FormatEnum(t Tag, v uint32) string

func (*Registry) FormatInt

func (r *Registry) FormatInt(t Tag, v int32) string

func (*Registry) FormatTag

func (r *Registry) FormatTag(t Tag) string

func (*Registry) FormatTagCanonical

func (r *Registry) FormatTagCanonical(t Tag) string

func (*Registry) FormatType

func (r *Registry) FormatType(t Type) string

func (*Registry) IsBitmask

func (r *Registry) IsBitmask(t Tag) bool

func (*Registry) IsEnum

func (r *Registry) IsEnum(t Tag) bool

func (*Registry) ParseEnum

func (r *Registry) ParseEnum(t Tag, s string) (uint32, error)

func (*Registry) ParseInt

func (r *Registry) ParseInt(t Tag, s string) (int32, error)

func (*Registry) ParseTag

func (r *Registry) ParseTag(s string) (Tag, error)

returns TagNone if not found. returns error if s is a malformed hex string, or a hex string of incorrect length

func (*Registry) ParseType

func (r *Registry) ParseType(s string) (Type, error)

func (*Registry) RegisterEnum

func (r *Registry) RegisterEnum(t Tag, def EnumMap)

func (*Registry) RegisterTag

func (r *Registry) RegisterTag(t Tag, name string)

func (*Registry) RegisterType

func (r *Registry) RegisterType(t Type, name string)

func (*Registry) Tags

func (r *Registry) Tags() EnumMap

func (*Registry) Types

func (r *Registry) Types() EnumMap

type TTLV

type TTLV []byte

TTLV is a byte slice that begins with a TTLV encoded block. The methods of TTLV operate on the TTLV value located at the beginning of the slice. Any bytes in the slice after the end of the TTLV are ignored. Use TTLV.Next() to return a new slice starting after the current value.

TTLV knows how to marshal/unmarshal to XML and JSON, following the KMIP specification for those encodings. Wherever possible, normalized names for tags, enum values, and mask values will be used, if those values have been registered. Otherwise, compliant hex value encoding is used.

func Marshal

func Marshal(v interface{}) (TTLV, error)

Marshal encodes a golang value into a KMIP value.

An error will be returned if v is an invalid pointer.

Currently, Marshal does not support anonymous fields. Private fields are ignored.

Marshal maps the golang value to a KMIP tag, type, and value encoding. To determine the KMIP tag, Marshal uses the same rules as Unmarshal.

The appropriate type and encoding are inferred from the golang type and from the inferred KMIP tag, according to these rules:

  1. If the value is a TTLV, it is copied byte for byte

  2. If the value implements Marshaler, call that

  3. If the struct field has an "omitempty" flag, and the value is zero, skip the field:

    type Foo struct { Comment string `ttlv:,omitempty` }

  1. If the value is a slice (except []byte) or array, marshal all values concatenated

  2. If a tag has not been inferred at this point, return *MarshalerError with cause ErrNoTag

  3. If the Tag is registered as an enum, or has the "enum" struct tag flag, attempt to marshal as an Enumeration. int, int8, int16, int32, and their uint counterparts can be marshaled as an Enumeration. A string can be marshaled to an Enumeration if the string contains a number, a 4 byte (8 char) hex string with the prefix "0x", or the normalized name of an enum value registered to this tag. Examples:

    type Foo struct { CancellationResult string // will encode as an Enumeration because // the tag CancellationResult is registered // as an enum. C int `ttlv:"Comment,enum" // The tag Comment is not registered as an enum // but the enum flag will force this to encode // as an enumeration. }

    If the string can't be interpreted as an enum value, it will be encoded as a TextString. If the "enum" struct flag is set, the value *must* successfully encode to an Enumeration using above rules, or an error is returned.

  1. If the Tag is registered as a bitmask, or has the "bitmask" struct tag flag, attempt to marshal to an Integer, following the same rules as for Enumerations. The ParseInt() function is used to parse string values.

  2. time.Time marshals to DateTime. If the field has the "datetimeextended" struct flag, marshal as DateTimeExtended. Example:

    type Foo struct { ActivationDate time.Time `ttlv:",datetimeextended"` }

  1. big.Int marshals to BigInteger
  2. time.Duration marshals to Interval
  3. string marshals to TextString
  4. []byte marshals to ByteString
  5. all int and uint variants except int64 and uint64 marshal to Integer. If the golang value overflows the KMIP value, *MarshalerError with cause ErrIntOverflow is returned
  6. int64 and uint64 marshal to LongInteger
  7. bool marshals to Boolean
  8. structs marshal to Structure. Each field of the struct will be marshaled into the values of the Structure according to the above rules.

Any other golang type will return *MarshalerError with cause ErrUnsupportedTypeError

func (TTLV) FullLen

func (t TTLV) FullLen() int

FullLen returns the expected length of the entire TTLV block (header + value), based on the type and len encoded in the header.

Does not check whether the actual value segment matches the expected length. See Valid().

panics if type encoded in header is invalid or unrecognized.

func (TTLV) Len

func (t TTLV) Len() int

Len returns the length encoded in the TTLV header. Note: The value segment of the TTLV may be longer since some value types encode with padding. See FullLen()

Len only reads the header, so it does not validate if the value segment's length matches the length in the header. See Valid().

Returns empty value if TTLV header is truncated.

func (TTLV) MarshalJSON

func (t TTLV) MarshalJSON() ([]byte, error)

func (TTLV) MarshalXML

func (t TTLV) MarshalXML(e *xml.Encoder, _ xml.StartElement) error

func (TTLV) Next

func (t TTLV) Next() TTLV

func (TTLV) String

func (t TTLV) String() string

String renders the TTLV in a human-friendly format using Print().

func (TTLV) Tag

func (t TTLV) Tag() Tag

Tag returns the KMIP Tag encoded in the TTLV header. Returns empty value if TTLV header is truncated.

func (TTLV) Type

func (t TTLV) Type() Type

Type returns the KMIP Type encoded in the TTLV header. Returns empty value if TTLV header is truncated.

func (*TTLV) UnmarshalJSON

func (t *TTLV) UnmarshalJSON(b []byte) error

func (*TTLV) UnmarshalTTLV

func (t *TTLV) UnmarshalTTLV(_ *Decoder, ttlv TTLV) error

UnmarshalTTLV implements ttlv.Unmarshaler. Unmarshaling a TTLV into another TTLV will allocate a new slice, and copy the bytes from the source TTLV into the new slice.

func (*TTLV) UnmarshalXML

func (t *TTLV) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

func (TTLV) Valid

func (t TTLV) Valid() error

Valid checks whether a TTLV value is valid. It checks whether the value segment is long enough to hold the encoded type. If the type is Structure, it recursively checks all the enclosed TTLV values.

Returns nil if valid.

func (TTLV) ValidHeader

func (t TTLV) ValidHeader() error

ValidHeader checks whether the header is valid. It ensures the value is long enough to hold a full header, whether the tag value is within valid ranges, whether the type is recognized, and whether the encoded length is valid for the encoded type.

Returns nil if valid.

func (TTLV) Value

func (t TTLV) Value() interface{}

Value returns the value of the TTLV, converted to an idiomatic go type.

func (TTLV) ValueBigInteger

func (t TTLV) ValueBigInteger() *big.Int

func (TTLV) ValueBoolean

func (t TTLV) ValueBoolean() bool

func (TTLV) ValueByteString

func (t TTLV) ValueByteString() []byte

func (TTLV) ValueDateTime

func (t TTLV) ValueDateTime() time.Time

func (TTLV) ValueDateTimeExtended

func (t TTLV) ValueDateTimeExtended() DateTimeExtended

func (TTLV) ValueEnumeration

func (t TTLV) ValueEnumeration() EnumValue

func (TTLV) ValueInteger

func (t TTLV) ValueInteger() int32

ValueInteger, and the other Value<Type>() variants attempt to decode the value segment of the TTLV into a golang value. These methods do not check the type of the TTLV. If the value in the TTLV isn't actually encoded as expected, the result is undetermined, and it may panic.

func (TTLV) ValueInterval

func (t TTLV) ValueInterval() time.Duration

func (TTLV) ValueLongInteger

func (t TTLV) ValueLongInteger() int64

func (TTLV) ValueRaw

func (t TTLV) ValueRaw() []byte

ValueRaw returns the raw bytes of the value segment of the TTLV. It relies on the length segment of the TTLV to know how many bytes to read. If the length segment's value is greater than the length of the TTLV slice, all the remaining bytes in the slice will be returned, but it will not panic.

func (TTLV) ValueStructure

func (t TTLV) ValueStructure() TTLV

ValueStructure returns the raw bytes of the value segment of the TTLV as a new TTLV. The value segment of a TTLV Structure is just a concatenation of more TTLV values.

func (TTLV) ValueTextString

func (t TTLV) ValueTextString() string

type Tag

type Tag uint32

Tag 9.1.3.1

func ParseTag

func ParseTag(s string, enumMap EnumMap) (Tag, error)

ParseTag parses a string into Tag according the rules in the KMIP Profiles regarding encoding tag values. See FormatTag for examples of the formats which can be parsed.

Returns ErrInvalidHexString if the string is invalid hex, or if the hex value is less than 1 byte or more than 3 bytes (ignoring leading zeroes).

Returns ErrUnregisteredEnumName if string value is not a registered enum value name.

func (Tag) CanonicalName

func (t Tag) CanonicalName() string

CanonicalName returns the canonical name of the tag.

func (Tag) MarshalText

func (t Tag) MarshalText() (text []byte, err error)

func (Tag) String

func (t Tag) String() string

String returns the normalized name of the tag.

func (*Tag) UnmarshalText

func (t *Tag) UnmarshalText(text []byte) (err error)

func (Tag) Valid

func (t Tag) Valid() bool

Valid checks whether the tag's numeric value is valid according to the ranges in the spec.

type Type

type Type byte

Type describes the type of a KMIP TTLV. 2 and 9.1.1.2

const (
	TypeStructure        Type = 0x01
	TypeInteger          Type = 0x02
	TypeLongInteger      Type = 0x03
	TypeBigInteger       Type = 0x04
	TypeEnumeration      Type = 0x05
	TypeBoolean          Type = 0x06
	TypeTextString       Type = 0x07
	TypeByteString       Type = 0x08
	TypeDateTime         Type = 0x09
	TypeInterval         Type = 0x0A
	TypeDateTimeExtended Type = 0x0B
)

func ParseType

func ParseType(s string, enumMap EnumMap) (Type, error)

ParseType parses a string into Type according the rules in the KMIP Profiles regarding encoding type values. See FormatType for examples of the formats which can be parsed. This also supports parsing a hex string type (e.g. "0x01"), though this is not technically a valid encoding of a type in the spec.

Returns ErrInvalidHexString if the string is invalid hex, or if the hex value is less than 1 byte or more than 3 bytes (ignoring leading zeroes).

Returns ErrUnregisteredEnumName if string value is not a registered enum value name.

func (Type) MarshalText

func (t Type) MarshalText() (text []byte, err error)

func (Type) String

func (t Type) String() string

String returns the normalized name of the type. If the type name isn't registered, it returns the hex value of the type, e.g. "0x01" (TypeStructure). The value of String() is suitable for use in the JSON or XML encoding of TTLV.

func (*Type) UnmarshalText

func (t *Type) UnmarshalText(text []byte) (err error)

type Unmarshaler

type Unmarshaler interface {
	UnmarshalTTLV(d *Decoder, ttlv TTLV) error
}

Unmarshaler knows how to unmarshal a ttlv value into itself. The decoder argument may be used to decode the ttlv value into intermediary values if needed.

type UnmarshalerError

type UnmarshalerError struct {
	// Val is the type of the destination value
	Val reflect.Type
	// Struct is the type of the containing struct if the value is a field
	Struct reflect.Type
	// Field is the name of the value field
	Field string
	Tag   Tag
	Type  Type
}

func (*UnmarshalerError) Error

func (e *UnmarshalerError) Error() string

type Value

type Value struct {
	Tag   Tag
	Value interface{}
}

Value is a go-typed mapping for a TTLV value. It holds a tag, and the value in the form of a native go type.

Value supports marshaling and unmarshaling, allowing a mapping between encoded TTLV bytes and native go types. It's useful in tests, or where you want to construct an arbitrary TTLV structure in code without declaring a bespoke type, e.g.:

    v := ttlv.Value{Tag: TagBatchCount, Value: Values{
				Value{Tag: TagComment, Value: "red"},
				Value{Tag: TagComment, Value: "blue"},
				Value{Tag: TagComment, Value: "green"},
         }
    t, err := ttlv.Marshal(v)

KMIP Structure types are mapped to the Values go type. When marshaling, if the Value field is set to a Values{}, the resulting TTLV will be TypeStructure. When unmarshaling a TTLV with TypeStructure, the Value field will be set to a Values{}.

func NewStruct

func NewStruct(tag Tag, vals ...Value) Value

NewStruct creates a new tagged value which is of type struct.

func NewValue

func NewValue(tag Tag, val interface{}) Value

NewValue creates a new tagged value.

func (Value) MarshalTTLV

func (t Value) MarshalTTLV(e *Encoder, tag Tag) error

MarshalTTLV implements Marshaler

func (*Value) UnmarshalTTLV

func (t *Value) UnmarshalTTLV(d *Decoder, ttlv TTLV) error

UnmarshalTTLV implements Unmarshaler

type Values

type Values []Value

Values is a slice of Value objects. It represents the body of a TTLV with a type of Structure.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL