candidate_relay.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. package ice
  4. import (
  5. "net"
  6. )
  7. // CandidateRelay ...
  8. type CandidateRelay struct {
  9. candidateBase
  10. relayProtocol string
  11. onClose func() error
  12. }
  13. // CandidateRelayConfig is the config required to create a new CandidateRelay
  14. type CandidateRelayConfig struct {
  15. CandidateID string
  16. Network string
  17. Address string
  18. Port int
  19. Component uint16
  20. Priority uint32
  21. Foundation string
  22. RelAddr string
  23. RelPort int
  24. RelayProtocol string
  25. OnClose func() error
  26. }
  27. // NewCandidateRelay creates a new relay candidate
  28. func NewCandidateRelay(config *CandidateRelayConfig) (*CandidateRelay, error) {
  29. candidateID := config.CandidateID
  30. if candidateID == "" {
  31. candidateID = globalCandidateIDGenerator.Generate()
  32. }
  33. ip := net.ParseIP(config.Address)
  34. if ip == nil {
  35. return nil, ErrAddressParseFailed
  36. }
  37. networkType, err := determineNetworkType(config.Network, ip)
  38. if err != nil {
  39. return nil, err
  40. }
  41. return &CandidateRelay{
  42. candidateBase: candidateBase{
  43. id: candidateID,
  44. networkType: networkType,
  45. candidateType: CandidateTypeRelay,
  46. address: config.Address,
  47. port: config.Port,
  48. resolvedAddr: &net.UDPAddr{IP: ip, Port: config.Port},
  49. component: config.Component,
  50. foundationOverride: config.Foundation,
  51. priorityOverride: config.Priority,
  52. relatedAddress: &CandidateRelatedAddress{
  53. Address: config.RelAddr,
  54. Port: config.RelPort,
  55. },
  56. remoteCandidateCaches: map[AddrPort]Candidate{},
  57. },
  58. relayProtocol: config.RelayProtocol,
  59. onClose: config.OnClose,
  60. }, nil
  61. }
  62. // RelayProtocol returns the protocol used between the endpoint and the relay server.
  63. func (c *CandidateRelay) RelayProtocol() string {
  64. return c.relayProtocol
  65. }
  66. func (c *CandidateRelay) close() error {
  67. err := c.candidateBase.close()
  68. if c.onClose != nil {
  69. err = c.onClose()
  70. c.onClose = nil
  71. }
  72. return err
  73. }
  74. func (c *CandidateRelay) copy() (Candidate, error) {
  75. cc, err := c.candidateBase.copy()
  76. if err != nil {
  77. return nil, err
  78. }
  79. if ccr, ok := cc.(*CandidateRelay); ok {
  80. ccr.relayProtocol = c.relayProtocol
  81. }
  82. return cc, nil
  83. }