dtls.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package tls
  2. import (
  3. "context"
  4. "v2ray.com/core/common"
  5. "v2ray.com/core/common/dice"
  6. )
  7. // DTLS writes header as DTLS. See https://tools.ietf.org/html/rfc6347
  8. type DTLS struct {
  9. epoch uint16
  10. length uint16
  11. sequence uint32
  12. }
  13. // Size implements PacketHeader.
  14. func (*DTLS) Size() int32 {
  15. return 1 + 2 + 2 + 6 + 2
  16. }
  17. // Write implements PacketHeader.
  18. func (d *DTLS) Write(b []byte) (int, error) {
  19. b[0] = 23 // application data
  20. b[1] = 254
  21. b[2] = 253
  22. b[3] = byte(d.epoch >> 8)
  23. b[4] = byte(d.epoch)
  24. b[5] = 0
  25. b[6] = 0
  26. b[7] = byte(d.sequence >> 24)
  27. b[8] = byte(d.sequence >> 16)
  28. b[9] = byte(d.sequence >> 8)
  29. b[10] = byte(d.sequence)
  30. d.sequence++
  31. b[11] = byte(d.length >> 8)
  32. b[12] = byte(d.length)
  33. d.length += 17
  34. if d.length > 100 {
  35. d.length -= 50
  36. }
  37. return 13, nil
  38. }
  39. // New creates a new UTP header for the given config.
  40. func New(ctx context.Context, config interface{}) (interface{}, error) {
  41. return &DTLS{
  42. epoch: dice.RollUint16(),
  43. sequence: 0,
  44. length: 17,
  45. }, nil
  46. }
  47. func init() {
  48. common.Must(common.RegisterConfig((*PacketConfig)(nil), New))
  49. }