udp_mux.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. package ice
  2. import (
  3. "io"
  4. "net"
  5. "os"
  6. "strings"
  7. "sync"
  8. "github.com/pion/logging"
  9. "github.com/pion/stun"
  10. )
  11. // UDPMux allows multiple connections to go over a single UDP port
  12. type UDPMux interface {
  13. io.Closer
  14. GetConn(ufrag string, isIPv6 bool) (net.PacketConn, error)
  15. RemoveConnByUfrag(ufrag string)
  16. }
  17. // UDPMuxDefault is an implementation of the interface
  18. type UDPMuxDefault struct {
  19. params UDPMuxParams
  20. closedChan chan struct{}
  21. closeOnce sync.Once
  22. // connsIPv4 and connsIPv6 are maps of all udpMuxedConn indexed by ufrag|network|candidateType
  23. connsIPv4, connsIPv6 map[string]*udpMuxedConn
  24. addressMapMu sync.RWMutex
  25. addressMap map[string]*udpMuxedConn
  26. // buffer pool to recycle buffers for net.UDPAddr encodes/decodes
  27. pool *sync.Pool
  28. mu sync.Mutex
  29. }
  30. const maxAddrSize = 512
  31. // UDPMuxParams are parameters for UDPMux.
  32. type UDPMuxParams struct {
  33. Logger logging.LeveledLogger
  34. UDPConn net.PacketConn
  35. }
  36. // NewUDPMuxDefault creates an implementation of UDPMux
  37. func NewUDPMuxDefault(params UDPMuxParams) *UDPMuxDefault {
  38. if params.Logger == nil {
  39. params.Logger = logging.NewDefaultLoggerFactory().NewLogger("ice")
  40. }
  41. m := &UDPMuxDefault{
  42. addressMap: map[string]*udpMuxedConn{},
  43. params: params,
  44. connsIPv4: make(map[string]*udpMuxedConn),
  45. connsIPv6: make(map[string]*udpMuxedConn),
  46. closedChan: make(chan struct{}, 1),
  47. pool: &sync.Pool{
  48. New: func() interface{} {
  49. // big enough buffer to fit both packet and address
  50. return newBufferHolder(receiveMTU + maxAddrSize)
  51. },
  52. },
  53. }
  54. go m.connWorker()
  55. return m
  56. }
  57. // LocalAddr returns the listening address of this UDPMuxDefault
  58. func (m *UDPMuxDefault) LocalAddr() net.Addr {
  59. return m.params.UDPConn.LocalAddr()
  60. }
  61. // GetConn returns a PacketConn given the connection's ufrag and network
  62. // creates the connection if an existing one can't be found
  63. func (m *UDPMuxDefault) GetConn(ufrag string, isIPv6 bool) (net.PacketConn, error) {
  64. m.mu.Lock()
  65. defer m.mu.Unlock()
  66. if m.IsClosed() {
  67. return nil, io.ErrClosedPipe
  68. }
  69. if conn, ok := m.getConn(ufrag, isIPv6); ok {
  70. return conn, nil
  71. }
  72. c := m.createMuxedConn(ufrag)
  73. go func() {
  74. <-c.CloseChannel()
  75. m.removeConn(ufrag)
  76. }()
  77. if isIPv6 {
  78. m.connsIPv6[ufrag] = c
  79. } else {
  80. m.connsIPv4[ufrag] = c
  81. }
  82. return c, nil
  83. }
  84. // RemoveConnByUfrag stops and removes the muxed packet connection
  85. func (m *UDPMuxDefault) RemoveConnByUfrag(ufrag string) {
  86. removedConns := make([]*udpMuxedConn, 0, 2)
  87. // Keep lock section small to avoid deadlock with conn lock
  88. m.mu.Lock()
  89. if c, ok := m.connsIPv4[ufrag]; ok {
  90. delete(m.connsIPv4, ufrag)
  91. removedConns = append(removedConns, c)
  92. }
  93. if c, ok := m.connsIPv6[ufrag]; ok {
  94. delete(m.connsIPv6, ufrag)
  95. removedConns = append(removedConns, c)
  96. }
  97. m.mu.Unlock()
  98. m.addressMapMu.Lock()
  99. defer m.addressMapMu.Unlock()
  100. for _, c := range removedConns {
  101. addresses := c.getAddresses()
  102. for _, addr := range addresses {
  103. delete(m.addressMap, addr)
  104. }
  105. }
  106. }
  107. // IsClosed returns true if the mux had been closed
  108. func (m *UDPMuxDefault) IsClosed() bool {
  109. select {
  110. case <-m.closedChan:
  111. return true
  112. default:
  113. return false
  114. }
  115. }
  116. // Close the mux, no further connections could be created
  117. func (m *UDPMuxDefault) Close() error {
  118. var err error
  119. m.closeOnce.Do(func() {
  120. m.mu.Lock()
  121. defer m.mu.Unlock()
  122. for _, c := range m.connsIPv4 {
  123. _ = c.Close()
  124. }
  125. for _, c := range m.connsIPv6 {
  126. _ = c.Close()
  127. }
  128. m.connsIPv4 = make(map[string]*udpMuxedConn)
  129. m.connsIPv6 = make(map[string]*udpMuxedConn)
  130. close(m.closedChan)
  131. })
  132. return err
  133. }
  134. func (m *UDPMuxDefault) removeConn(key string) {
  135. // keep lock section small to avoid deadlock with conn lock
  136. c := func() *udpMuxedConn {
  137. m.mu.Lock()
  138. defer m.mu.Unlock()
  139. if c, ok := m.connsIPv4[key]; ok {
  140. delete(m.connsIPv4, key)
  141. return c
  142. }
  143. if c, ok := m.connsIPv6[key]; ok {
  144. delete(m.connsIPv6, key)
  145. return c
  146. }
  147. return nil
  148. }()
  149. if c == nil {
  150. return
  151. }
  152. m.addressMapMu.Lock()
  153. defer m.addressMapMu.Unlock()
  154. addresses := c.getAddresses()
  155. for _, addr := range addresses {
  156. delete(m.addressMap, addr)
  157. }
  158. }
  159. func (m *UDPMuxDefault) writeTo(buf []byte, raddr net.Addr) (n int, err error) {
  160. return m.params.UDPConn.WriteTo(buf, raddr)
  161. }
  162. func (m *UDPMuxDefault) registerConnForAddress(conn *udpMuxedConn, addr string) {
  163. if m.IsClosed() {
  164. return
  165. }
  166. m.addressMapMu.Lock()
  167. defer m.addressMapMu.Unlock()
  168. existing, ok := m.addressMap[addr]
  169. if ok {
  170. existing.removeAddress(addr)
  171. }
  172. m.addressMap[addr] = conn
  173. m.params.Logger.Debugf("Registered %s for %s", addr, conn.params.Key)
  174. }
  175. func (m *UDPMuxDefault) createMuxedConn(key string) *udpMuxedConn {
  176. c := newUDPMuxedConn(&udpMuxedConnParams{
  177. Mux: m,
  178. Key: key,
  179. AddrPool: m.pool,
  180. LocalAddr: m.LocalAddr(),
  181. Logger: m.params.Logger,
  182. })
  183. return c
  184. }
  185. func (m *UDPMuxDefault) connWorker() {
  186. logger := m.params.Logger
  187. defer func() {
  188. _ = m.Close()
  189. }()
  190. buf := make([]byte, receiveMTU)
  191. for {
  192. n, addr, err := m.params.UDPConn.ReadFrom(buf)
  193. if m.IsClosed() {
  194. return
  195. } else if err != nil {
  196. if os.IsTimeout(err) {
  197. continue
  198. } else if err != io.EOF {
  199. logger.Errorf("could not read udp packet: %v", err)
  200. }
  201. return
  202. }
  203. udpAddr, ok := addr.(*net.UDPAddr)
  204. if !ok {
  205. logger.Errorf("underlying PacketConn did not return a UDPAddr")
  206. return
  207. }
  208. // If we have already seen this address dispatch to the appropriate destination
  209. m.addressMapMu.Lock()
  210. destinationConn := m.addressMap[addr.String()]
  211. m.addressMapMu.Unlock()
  212. // If we haven't seen this address before but is a STUN packet lookup by ufrag
  213. if destinationConn == nil && stun.IsMessage(buf[:n]) {
  214. msg := &stun.Message{
  215. Raw: append([]byte{}, buf[:n]...),
  216. }
  217. if err = msg.Decode(); err != nil {
  218. m.params.Logger.Warnf("Failed to handle decode ICE from %s: %v\n", addr.String(), err)
  219. continue
  220. }
  221. attr, stunAttrErr := msg.Get(stun.AttrUsername)
  222. if stunAttrErr != nil {
  223. m.params.Logger.Warnf("No Username attribute in STUN message from %s\n", addr.String())
  224. continue
  225. }
  226. ufrag := strings.Split(string(attr), ":")[0]
  227. isIPv6 := udpAddr.IP.To4() == nil
  228. m.mu.Lock()
  229. destinationConn, _ = m.getConn(ufrag, isIPv6)
  230. m.mu.Unlock()
  231. }
  232. if destinationConn == nil {
  233. m.params.Logger.Tracef("dropping packet from %s, addr: %s", udpAddr.String(), addr.String())
  234. continue
  235. }
  236. if err = destinationConn.writePacket(buf[:n], udpAddr); err != nil {
  237. m.params.Logger.Errorf("could not write packet: %v", err)
  238. }
  239. }
  240. }
  241. func (m *UDPMuxDefault) getConn(ufrag string, isIPv6 bool) (val *udpMuxedConn, ok bool) {
  242. if isIPv6 {
  243. val, ok = m.connsIPv6[ufrag]
  244. } else {
  245. val, ok = m.connsIPv4[ufrag]
  246. }
  247. return
  248. }
  249. type bufferHolder struct {
  250. buffer []byte
  251. }
  252. func newBufferHolder(size int) *bufferHolder {
  253. return &bufferHolder{
  254. buffer: make([]byte, size),
  255. }
  256. }