lifetime.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package proto
  2. import (
  3. "encoding/binary"
  4. "time"
  5. "github.com/pion/stun"
  6. )
  7. // DefaultLifetime in RFC 5766 is 10 minutes.
  8. //
  9. // RFC 5766 Section 2.2
  10. const DefaultLifetime = time.Minute * 10
  11. // Lifetime represents LIFETIME attribute.
  12. //
  13. // The LIFETIME attribute represents the duration for which the server
  14. // will maintain an allocation in the absence of a refresh. The value
  15. // portion of this attribute is 4-bytes long and consists of a 32-bit
  16. // unsigned integral value representing the number of seconds remaining
  17. // until expiration.
  18. //
  19. // RFC 5766 Section 14.2
  20. type Lifetime struct {
  21. time.Duration
  22. }
  23. // uint32 seconds
  24. const lifetimeSize = 4 // 4 bytes, 32 bits
  25. // AddTo adds LIFETIME to message.
  26. func (l Lifetime) AddTo(m *stun.Message) error {
  27. v := make([]byte, lifetimeSize)
  28. binary.BigEndian.PutUint32(v, uint32(l.Seconds()))
  29. m.Add(stun.AttrLifetime, v)
  30. return nil
  31. }
  32. // GetFrom decodes LIFETIME from message.
  33. func (l *Lifetime) GetFrom(m *stun.Message) error {
  34. v, err := m.Get(stun.AttrLifetime)
  35. if err != nil {
  36. return err
  37. }
  38. if err = stun.CheckSize(stun.AttrLifetime, len(v), lifetimeSize); err != nil {
  39. return err
  40. }
  41. _ = v[lifetimeSize-1] // asserting length
  42. seconds := binary.BigEndian.Uint32(v)
  43. l.Duration = time.Second * time.Duration(seconds)
  44. return nil
  45. }