mux.go 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. // Package mux multiplexes packets on a single socket (RFC7983)
  4. package mux
  5. import (
  6. "errors"
  7. "io"
  8. "net"
  9. "sync"
  10. "github.com/pion/ice/v2"
  11. "github.com/pion/logging"
  12. "github.com/pion/transport/v2/packetio"
  13. )
  14. // The maximum amount of data that can be buffered before returning errors.
  15. const maxBufferSize = 1000 * 1000 // 1MB
  16. // Config collects the arguments to mux.Mux construction into
  17. // a single structure
  18. type Config struct {
  19. Conn net.Conn
  20. BufferSize int
  21. LoggerFactory logging.LoggerFactory
  22. }
  23. // Mux allows multiplexing
  24. type Mux struct {
  25. lock sync.RWMutex
  26. nextConn net.Conn
  27. endpoints map[*Endpoint]MatchFunc
  28. bufferSize int
  29. closedCh chan struct{}
  30. log logging.LeveledLogger
  31. }
  32. // NewMux creates a new Mux
  33. func NewMux(config Config) *Mux {
  34. m := &Mux{
  35. nextConn: config.Conn,
  36. endpoints: make(map[*Endpoint]MatchFunc),
  37. bufferSize: config.BufferSize,
  38. closedCh: make(chan struct{}),
  39. log: config.LoggerFactory.NewLogger("mux"),
  40. }
  41. go m.readLoop()
  42. return m
  43. }
  44. // NewEndpoint creates a new Endpoint
  45. func (m *Mux) NewEndpoint(f MatchFunc) *Endpoint {
  46. e := &Endpoint{
  47. mux: m,
  48. buffer: packetio.NewBuffer(),
  49. }
  50. // Set a maximum size of the buffer in bytes.
  51. e.buffer.SetLimitSize(maxBufferSize)
  52. m.lock.Lock()
  53. m.endpoints[e] = f
  54. m.lock.Unlock()
  55. return e
  56. }
  57. // RemoveEndpoint removes an endpoint from the Mux
  58. func (m *Mux) RemoveEndpoint(e *Endpoint) {
  59. m.lock.Lock()
  60. defer m.lock.Unlock()
  61. delete(m.endpoints, e)
  62. }
  63. // Close closes the Mux and all associated Endpoints.
  64. func (m *Mux) Close() error {
  65. m.lock.Lock()
  66. for e := range m.endpoints {
  67. if err := e.close(); err != nil {
  68. m.lock.Unlock()
  69. return err
  70. }
  71. delete(m.endpoints, e)
  72. }
  73. m.lock.Unlock()
  74. err := m.nextConn.Close()
  75. if err != nil {
  76. return err
  77. }
  78. // Wait for readLoop to end
  79. <-m.closedCh
  80. return nil
  81. }
  82. func (m *Mux) readLoop() {
  83. defer func() {
  84. close(m.closedCh)
  85. }()
  86. buf := make([]byte, m.bufferSize)
  87. for {
  88. n, err := m.nextConn.Read(buf)
  89. switch {
  90. case errors.Is(err, io.EOF), errors.Is(err, ice.ErrClosed):
  91. return
  92. case errors.Is(err, io.ErrShortBuffer), errors.Is(err, packetio.ErrTimeout):
  93. m.log.Errorf("mux: failed to read from packetio.Buffer %s", err.Error())
  94. continue
  95. case err != nil:
  96. m.log.Errorf("mux: ending readLoop packetio.Buffer error %s", err.Error())
  97. return
  98. }
  99. if err = m.dispatch(buf[:n]); err != nil {
  100. m.log.Errorf("mux: ending readLoop dispatch error %s", err.Error())
  101. return
  102. }
  103. }
  104. }
  105. func (m *Mux) dispatch(buf []byte) error {
  106. var endpoint *Endpoint
  107. m.lock.Lock()
  108. for e, f := range m.endpoints {
  109. if f(buf) {
  110. endpoint = e
  111. break
  112. }
  113. }
  114. m.lock.Unlock()
  115. if endpoint == nil {
  116. if len(buf) > 0 {
  117. m.log.Warnf("Warning: mux: no endpoint for packet starting with %d", buf[0])
  118. } else {
  119. m.log.Warnf("Warning: mux: no endpoint for zero length packet")
  120. }
  121. return nil
  122. }
  123. _, err := endpoint.buffer.Write(buf)
  124. // Expected when bytes are received faster than the endpoint can process them (#2152, #2180)
  125. if errors.Is(err, packetio.ErrFull) {
  126. m.log.Infof("mux: endpoint buffer is full, dropping packet")
  127. return nil
  128. }
  129. return err
  130. }