udp_mux.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. package ice
  4. import (
  5. "errors"
  6. "io"
  7. "net"
  8. "os"
  9. "strings"
  10. "sync"
  11. "github.com/pion/logging"
  12. "github.com/pion/stun"
  13. "github.com/pion/transport/v2"
  14. "github.com/pion/transport/v2/stdnet"
  15. )
  16. // UDPMux allows multiple connections to go over a single UDP port
  17. type UDPMux interface {
  18. io.Closer
  19. GetConn(ufrag string, addr net.Addr) (net.PacketConn, error)
  20. RemoveConnByUfrag(ufrag string)
  21. GetListenAddresses() []net.Addr
  22. }
  23. // UDPMuxDefault is an implementation of the interface
  24. type UDPMuxDefault struct {
  25. params UDPMuxParams
  26. closedChan chan struct{}
  27. closeOnce sync.Once
  28. // connsIPv4 and connsIPv6 are maps of all udpMuxedConn indexed by ufrag|network|candidateType
  29. connsIPv4, connsIPv6 map[string]*udpMuxedConn
  30. addressMapMu sync.RWMutex
  31. addressMap map[string]*udpMuxedConn
  32. // Buffer pool to recycle buffers for net.UDPAddr encodes/decodes
  33. pool *sync.Pool
  34. mu sync.Mutex
  35. // For UDP connection listen at unspecified address
  36. localAddrsForUnspecified []net.Addr
  37. }
  38. const maxAddrSize = 512
  39. // UDPMuxParams are parameters for UDPMux.
  40. type UDPMuxParams struct {
  41. Logger logging.LeveledLogger
  42. UDPConn net.PacketConn
  43. // Required for gathering local addresses
  44. // in case a un UDPConn is passed which does not
  45. // bind to a specific local address.
  46. Net transport.Net
  47. }
  48. // NewUDPMuxDefault creates an implementation of UDPMux
  49. func NewUDPMuxDefault(params UDPMuxParams) *UDPMuxDefault {
  50. if params.Logger == nil {
  51. params.Logger = logging.NewDefaultLoggerFactory().NewLogger("ice")
  52. }
  53. var localAddrsForUnspecified []net.Addr
  54. if addr, ok := params.UDPConn.LocalAddr().(*net.UDPAddr); !ok {
  55. params.Logger.Errorf("LocalAddr is not a net.UDPAddr, got %T", params.UDPConn.LocalAddr())
  56. } else if ok && addr.IP.IsUnspecified() {
  57. // For unspecified addresses, the correct behavior is to return errListenUnspecified, but
  58. // it will break the applications that are already using unspecified UDP connection
  59. // with UDPMuxDefault, so print a warn log and create a local address list for mux.
  60. params.Logger.Warn("UDPMuxDefault should not listening on unspecified address, use NewMultiUDPMuxFromPort instead")
  61. var networks []NetworkType
  62. switch {
  63. case addr.IP.To4() != nil:
  64. networks = []NetworkType{NetworkTypeUDP4}
  65. case addr.IP.To16() != nil:
  66. networks = []NetworkType{NetworkTypeUDP4, NetworkTypeUDP6}
  67. default:
  68. params.Logger.Errorf("LocalAddr expected IPV4 or IPV6, got %T", params.UDPConn.LocalAddr())
  69. }
  70. if len(networks) > 0 {
  71. if params.Net == nil {
  72. var err error
  73. if params.Net, err = stdnet.NewNet(); err != nil {
  74. params.Logger.Errorf("Failed to get create network: %v", err)
  75. }
  76. }
  77. ips, err := localInterfaces(params.Net, nil, nil, networks, true)
  78. if err == nil {
  79. for _, ip := range ips {
  80. localAddrsForUnspecified = append(localAddrsForUnspecified, &net.UDPAddr{IP: ip, Port: addr.Port})
  81. }
  82. } else {
  83. params.Logger.Errorf("Failed to get local interfaces for unspecified addr: %v", err)
  84. }
  85. }
  86. }
  87. m := &UDPMuxDefault{
  88. addressMap: map[string]*udpMuxedConn{},
  89. params: params,
  90. connsIPv4: make(map[string]*udpMuxedConn),
  91. connsIPv6: make(map[string]*udpMuxedConn),
  92. closedChan: make(chan struct{}, 1),
  93. pool: &sync.Pool{
  94. New: func() interface{} {
  95. // Big enough buffer to fit both packet and address
  96. return newBufferHolder(receiveMTU + maxAddrSize)
  97. },
  98. },
  99. localAddrsForUnspecified: localAddrsForUnspecified,
  100. }
  101. // [Psiphon]
  102. //
  103. // - Currently, pion/ice code produces the following race condition due to
  104. // NewUDPMuxDefault launching go m.connWorker() before the called
  105. // assigns m.UDPMuxDefault = NewUDPMuxDefault(udpMuxParams), while
  106. // connWorker may access fields in the
  107. // UniversalUDPMuxDefault.UDPMuxDefault embedded struct.
  108. //
  109. // - For Psiphon's use case, the simple workaround is to delay launching
  110. // go m.connWorker() until after the assignment in
  111. // NewUniversalUDPMuxDefault. This isn't a general purpose fix since it
  112. // means NewUDPMuxDefault by itself won't work.
  113. //
  114. // - Note that the IsPsiphon flag/check added for
  115. // gatherCandidatesSrflxUDPMux also checks that this fix is in place.
  116. //
  117. //
  118. // ==================
  119. // WARNING: DATA RACE
  120. // Read at 0x00c000ee28c0 by goroutine 22319:
  121. // github.com/pion/ice/v2.(*UniversalUDPMuxDefault).isXORMappedResponse()
  122. // /pion/ice/v2/udp_mux_universal.go:136 +0x40
  123. // github.com/pion/ice/v2.(*udpConn).ReadFrom()
  124. // /pion/ice/v2/udp_mux_universal.go:122 +0x234
  125. // github.com/pion/ice/v2.(*UDPMuxDefault).connWorker()
  126. // /pion/ice/v2/udp_mux.go:286 +0xd4
  127. // github.com/pion/ice/v2.NewUDPMuxDefault.func2()
  128. // /pion/ice/v2/udp_mux.go:122 +0x34
  129. //
  130. // Previous write at 0x00c000ee28c0 by goroutine 22315:
  131. // github.com/pion/ice/v2.NewUniversalUDPMuxDefault()
  132. // /pion/ice/v2/udp_mux_universal.go:73 +0x354
  133. // github.com/pion/webrtc/v3.NewICEUniversalUDPMux()
  134. // /pion/webrtc/v3/icemux.go:39 +0x2b4
  135. // ==================
  136. //go m.connWorker()
  137. return m
  138. }
  139. // LocalAddr returns the listening address of this UDPMuxDefault
  140. func (m *UDPMuxDefault) LocalAddr() net.Addr {
  141. return m.params.UDPConn.LocalAddr()
  142. }
  143. // GetListenAddresses returns the list of addresses that this mux is listening on
  144. func (m *UDPMuxDefault) GetListenAddresses() []net.Addr {
  145. if len(m.localAddrsForUnspecified) > 0 {
  146. return m.localAddrsForUnspecified
  147. }
  148. return []net.Addr{m.LocalAddr()}
  149. }
  150. // GetConn returns a PacketConn given the connection's ufrag and network address
  151. // creates the connection if an existing one can't be found
  152. func (m *UDPMuxDefault) GetConn(ufrag string, addr net.Addr) (net.PacketConn, error) {
  153. // don't check addr for mux using unspecified address
  154. if len(m.localAddrsForUnspecified) == 0 && m.params.UDPConn.LocalAddr().String() != addr.String() {
  155. return nil, errInvalidAddress
  156. }
  157. var isIPv6 bool
  158. if udpAddr, _ := addr.(*net.UDPAddr); udpAddr != nil && udpAddr.IP.To4() == nil {
  159. isIPv6 = true
  160. }
  161. m.mu.Lock()
  162. defer m.mu.Unlock()
  163. if m.IsClosed() {
  164. return nil, io.ErrClosedPipe
  165. }
  166. if conn, ok := m.getConn(ufrag, isIPv6); ok {
  167. return conn, nil
  168. }
  169. c := m.createMuxedConn(ufrag)
  170. go func() {
  171. <-c.CloseChannel()
  172. m.RemoveConnByUfrag(ufrag)
  173. }()
  174. if isIPv6 {
  175. m.connsIPv6[ufrag] = c
  176. } else {
  177. m.connsIPv4[ufrag] = c
  178. }
  179. return c, nil
  180. }
  181. // RemoveConnByUfrag stops and removes the muxed packet connection
  182. func (m *UDPMuxDefault) RemoveConnByUfrag(ufrag string) {
  183. removedConns := make([]*udpMuxedConn, 0, 2)
  184. // Keep lock section small to avoid deadlock with conn lock
  185. m.mu.Lock()
  186. if c, ok := m.connsIPv4[ufrag]; ok {
  187. delete(m.connsIPv4, ufrag)
  188. removedConns = append(removedConns, c)
  189. }
  190. if c, ok := m.connsIPv6[ufrag]; ok {
  191. delete(m.connsIPv6, ufrag)
  192. removedConns = append(removedConns, c)
  193. }
  194. m.mu.Unlock()
  195. if len(removedConns) == 0 {
  196. // No need to lock if no connection was found
  197. return
  198. }
  199. m.addressMapMu.Lock()
  200. defer m.addressMapMu.Unlock()
  201. for _, c := range removedConns {
  202. addresses := c.getAddresses()
  203. for _, addr := range addresses {
  204. delete(m.addressMap, addr)
  205. }
  206. }
  207. }
  208. // IsClosed returns true if the mux had been closed
  209. func (m *UDPMuxDefault) IsClosed() bool {
  210. select {
  211. case <-m.closedChan:
  212. return true
  213. default:
  214. return false
  215. }
  216. }
  217. // Close the mux, no further connections could be created
  218. func (m *UDPMuxDefault) Close() error {
  219. var err error
  220. m.closeOnce.Do(func() {
  221. m.mu.Lock()
  222. defer m.mu.Unlock()
  223. for _, c := range m.connsIPv4 {
  224. _ = c.Close()
  225. }
  226. for _, c := range m.connsIPv6 {
  227. _ = c.Close()
  228. }
  229. m.connsIPv4 = make(map[string]*udpMuxedConn)
  230. m.connsIPv6 = make(map[string]*udpMuxedConn)
  231. close(m.closedChan)
  232. _ = m.params.UDPConn.Close()
  233. })
  234. return err
  235. }
  236. func (m *UDPMuxDefault) writeTo(buf []byte, rAddr net.Addr) (n int, err error) {
  237. return m.params.UDPConn.WriteTo(buf, rAddr)
  238. }
  239. func (m *UDPMuxDefault) registerConnForAddress(conn *udpMuxedConn, addr string) {
  240. if m.IsClosed() {
  241. return
  242. }
  243. m.addressMapMu.Lock()
  244. defer m.addressMapMu.Unlock()
  245. existing, ok := m.addressMap[addr]
  246. if ok {
  247. existing.removeAddress(addr)
  248. }
  249. m.addressMap[addr] = conn
  250. m.params.Logger.Debugf("Registered %s for %s", addr, conn.params.Key)
  251. }
  252. func (m *UDPMuxDefault) createMuxedConn(key string) *udpMuxedConn {
  253. c := newUDPMuxedConn(&udpMuxedConnParams{
  254. Mux: m,
  255. Key: key,
  256. AddrPool: m.pool,
  257. LocalAddr: m.LocalAddr(),
  258. Logger: m.params.Logger,
  259. })
  260. return c
  261. }
  262. func (m *UDPMuxDefault) connWorker() {
  263. logger := m.params.Logger
  264. defer func() {
  265. _ = m.Close()
  266. }()
  267. buf := make([]byte, receiveMTU)
  268. for {
  269. n, addr, err := m.params.UDPConn.ReadFrom(buf)
  270. if m.IsClosed() {
  271. return
  272. } else if err != nil {
  273. if os.IsTimeout(err) {
  274. continue
  275. } else if !errors.Is(err, io.EOF) {
  276. logger.Errorf("Failed to read UDP packet: %v", err)
  277. }
  278. return
  279. }
  280. udpAddr, ok := addr.(*net.UDPAddr)
  281. if !ok {
  282. logger.Errorf("Underlying PacketConn did not return a UDPAddr")
  283. return
  284. }
  285. // If we have already seen this address dispatch to the appropriate destination
  286. m.addressMapMu.Lock()
  287. destinationConn := m.addressMap[addr.String()]
  288. m.addressMapMu.Unlock()
  289. // If we haven't seen this address before but is a STUN packet lookup by ufrag
  290. if destinationConn == nil && stun.IsMessage(buf[:n]) {
  291. msg := &stun.Message{
  292. Raw: append([]byte{}, buf[:n]...),
  293. }
  294. if err = msg.Decode(); err != nil {
  295. m.params.Logger.Warnf("Failed to handle decode ICE from %s: %v", addr.String(), err)
  296. continue
  297. }
  298. attr, stunAttrErr := msg.Get(stun.AttrUsername)
  299. if stunAttrErr != nil {
  300. m.params.Logger.Warnf("No Username attribute in STUN message from %s", addr.String())
  301. continue
  302. }
  303. ufrag := strings.Split(string(attr), ":")[0]
  304. isIPv6 := udpAddr.IP.To4() == nil
  305. m.mu.Lock()
  306. destinationConn, _ = m.getConn(ufrag, isIPv6)
  307. m.mu.Unlock()
  308. }
  309. if destinationConn == nil {
  310. m.params.Logger.Tracef("Dropping packet from %s, addr: %s", udpAddr.String(), addr.String())
  311. continue
  312. }
  313. if err = destinationConn.writePacket(buf[:n], udpAddr); err != nil {
  314. m.params.Logger.Errorf("Failed to write packet: %v", err)
  315. }
  316. }
  317. }
  318. func (m *UDPMuxDefault) getConn(ufrag string, isIPv6 bool) (val *udpMuxedConn, ok bool) {
  319. if isIPv6 {
  320. val, ok = m.connsIPv6[ufrag]
  321. } else {
  322. val, ok = m.connsIPv4[ufrag]
  323. }
  324. return
  325. }
  326. type bufferHolder struct {
  327. buf []byte
  328. }
  329. func newBufferHolder(size int) *bufferHolder {
  330. return &bufferHolder{
  331. buf: make([]byte, size),
  332. }
  333. }