dtls.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. sequence uint32
  11. length uint16
  12. }
  13. // Size implements PacketHeader.
  14. func (*DTLS) Size() int32 {
  15. return 1 + 2 + 2 + 3 + 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] = byte(d.sequence >> 16)
  25. b[6] = byte(d.sequence >> 8)
  26. b[7] = byte(d.sequence)
  27. d.sequence++
  28. b[8] = byte(d.length >> 8)
  29. b[9] = byte(d.length)
  30. d.length += 17
  31. if d.length > 1024 {
  32. d.length -= 1024
  33. }
  34. return 10, nil
  35. }
  36. // New creates a new UTP header for the given config.
  37. func New(ctx context.Context, config interface{}) (interface{}, error) {
  38. return &DTLS{
  39. epoch: dice.RollUint16(),
  40. sequence: 0,
  41. length: uint16(dice.Roll(1024) + 100),
  42. }, nil
  43. }
  44. func init() {
  45. common.Must(common.RegisterConfig((*PacketConfig)(nil), New))
  46. }