flight2handler.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. package dtls
  4. import (
  5. "bytes"
  6. "context"
  7. "github.com/pion/dtls/v2/pkg/protocol"
  8. "github.com/pion/dtls/v2/pkg/protocol/alert"
  9. "github.com/pion/dtls/v2/pkg/protocol/handshake"
  10. "github.com/pion/dtls/v2/pkg/protocol/recordlayer"
  11. )
  12. func flight2Parse(ctx context.Context, c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert.Alert, error) {
  13. seq, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence, state.cipherSuite,
  14. handshakeCachePullRule{handshake.TypeClientHello, cfg.initialEpoch, true, false},
  15. )
  16. if !ok {
  17. // Client may retransmit the first ClientHello when HelloVerifyRequest is dropped.
  18. // Parse as flight 0 in this case.
  19. return flight0Parse(ctx, c, state, cache, cfg)
  20. }
  21. state.handshakeRecvSequence = seq
  22. var clientHello *handshake.MessageClientHello
  23. // Validate type
  24. if clientHello, ok = msgs[handshake.TypeClientHello].(*handshake.MessageClientHello); !ok {
  25. return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, nil
  26. }
  27. if !clientHello.Version.Equal(protocol.Version1_2) {
  28. return 0, &alert.Alert{Level: alert.Fatal, Description: alert.ProtocolVersion}, errUnsupportedProtocolVersion
  29. }
  30. if len(clientHello.Cookie) == 0 {
  31. return 0, nil, nil
  32. }
  33. if !bytes.Equal(state.cookie, clientHello.Cookie) {
  34. return 0, &alert.Alert{Level: alert.Fatal, Description: alert.AccessDenied}, errCookieMismatch
  35. }
  36. return flight4, nil, nil
  37. }
  38. func flight2Generate(_ flightConn, state *State, _ *handshakeCache, _ *handshakeConfig) ([]*packet, *alert.Alert, error) {
  39. state.handshakeSendSequence = 0
  40. return []*packet{
  41. {
  42. record: &recordlayer.RecordLayer{
  43. Header: recordlayer.Header{
  44. Version: protocol.Version1_2,
  45. },
  46. Content: &handshake.Handshake{
  47. Message: &handshake.MessageHelloVerifyRequest{
  48. Version: protocol.Version1_2,
  49. Cookie: state.cookie,
  50. },
  51. },
  52. },
  53. },
  54. }, nil, nil
  55. }