uattrs.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. package stun
  4. import "errors"
  5. // UnknownAttributes represents UNKNOWN-ATTRIBUTES attribute.
  6. //
  7. // RFC 5389 Section 15.9
  8. type UnknownAttributes []AttrType
  9. func (a UnknownAttributes) String() string {
  10. s := ""
  11. if len(a) == 0 {
  12. return "<nil>"
  13. }
  14. last := len(a) - 1
  15. for i, t := range a {
  16. s += t.String()
  17. if i != last {
  18. s += ", "
  19. }
  20. }
  21. return s
  22. }
  23. // type size is 16 bit.
  24. const attrTypeSize = 4
  25. // AddTo adds UNKNOWN-ATTRIBUTES attribute to message.
  26. func (a UnknownAttributes) AddTo(m *Message) error {
  27. v := make([]byte, 0, attrTypeSize*20) // 20 should be enough
  28. // If len(a.Types) > 20, there will be allocations.
  29. for i, t := range a {
  30. v = append(v, 0, 0, 0, 0) // 4 times by 0 (16 bits)
  31. first := attrTypeSize * i
  32. last := first + attrTypeSize
  33. bin.PutUint16(v[first:last], t.Value())
  34. }
  35. m.Add(AttrUnknownAttributes, v)
  36. return nil
  37. }
  38. // ErrBadUnknownAttrsSize means that UNKNOWN-ATTRIBUTES attribute value
  39. // has invalid length.
  40. var ErrBadUnknownAttrsSize = errors.New("bad UNKNOWN-ATTRIBUTES size")
  41. // GetFrom parses UNKNOWN-ATTRIBUTES from message.
  42. func (a *UnknownAttributes) GetFrom(m *Message) error {
  43. v, err := m.Get(AttrUnknownAttributes)
  44. if err != nil {
  45. return err
  46. }
  47. if len(v)%attrTypeSize != 0 {
  48. return ErrBadUnknownAttrsSize
  49. }
  50. *a = (*a)[:0]
  51. first := 0
  52. for first < len(v) {
  53. last := first + attrTypeSize
  54. *a = append(*a, AttrType(bin.Uint16(v[first:last])))
  55. first = last
  56. }
  57. return nil
  58. }