allocation.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. // Package allocation contains all CRUD operations for allocations
  2. package allocation
  3. import (
  4. "net"
  5. "sync"
  6. "sync/atomic"
  7. "time"
  8. "github.com/pion/logging"
  9. "github.com/pion/stun"
  10. "github.com/pion/turn/v2/internal/ipnet"
  11. "github.com/pion/turn/v2/internal/proto"
  12. )
  13. type allocationResponse struct {
  14. transactionID [stun.TransactionIDSize]byte
  15. responseAttrs []stun.Setter
  16. }
  17. // Allocation is tied to a FiveTuple and relays traffic
  18. // use CreateAllocation and GetAllocation to operate
  19. type Allocation struct {
  20. RelayAddr net.Addr
  21. Protocol Protocol
  22. TurnSocket net.PacketConn
  23. RelaySocket net.PacketConn
  24. fiveTuple *FiveTuple
  25. permissionsLock sync.RWMutex
  26. permissions map[string]*Permission
  27. channelBindingsLock sync.RWMutex
  28. channelBindings []*ChannelBind
  29. lifetimeTimer *time.Timer
  30. closed chan interface{}
  31. log logging.LeveledLogger
  32. // some clients (firefox or others using resiprocate's nICE lib) may retry allocation
  33. // with same 5 tuple when received 413, for compatible with these clients,
  34. // cache for response lost and client retry to implement 'stateless stack approach'
  35. // https://datatracker.ietf.org/doc/html/rfc5766#section-6.2
  36. responseCache atomic.Value // *allocationResponse
  37. }
  38. func addr2IPFingerprint(addr net.Addr) string {
  39. switch a := addr.(type) {
  40. case *net.UDPAddr:
  41. return a.IP.String()
  42. case *net.TCPAddr: // Do we really need this case?
  43. return a.IP.String()
  44. }
  45. return "" // shoud never happen
  46. }
  47. // NewAllocation creates a new instance of NewAllocation.
  48. func NewAllocation(turnSocket net.PacketConn, fiveTuple *FiveTuple, log logging.LeveledLogger) *Allocation {
  49. return &Allocation{
  50. TurnSocket: turnSocket,
  51. fiveTuple: fiveTuple,
  52. permissions: make(map[string]*Permission, 64),
  53. closed: make(chan interface{}),
  54. log: log,
  55. }
  56. }
  57. // GetPermission gets the Permission from the allocation
  58. func (a *Allocation) GetPermission(addr net.Addr) *Permission {
  59. a.permissionsLock.RLock()
  60. defer a.permissionsLock.RUnlock()
  61. return a.permissions[addr2IPFingerprint(addr)]
  62. }
  63. // AddPermission adds a new permission to the allocation
  64. func (a *Allocation) AddPermission(p *Permission) {
  65. fingerprint := addr2IPFingerprint(p.Addr)
  66. a.permissionsLock.RLock()
  67. existedPermission, ok := a.permissions[fingerprint]
  68. a.permissionsLock.RUnlock()
  69. if ok {
  70. existedPermission.refresh(permissionTimeout)
  71. return
  72. }
  73. p.allocation = a
  74. a.permissionsLock.Lock()
  75. a.permissions[fingerprint] = p
  76. a.permissionsLock.Unlock()
  77. p.start(permissionTimeout)
  78. }
  79. // RemovePermission removes the net.Addr's fingerprint from the allocation's permissions
  80. func (a *Allocation) RemovePermission(addr net.Addr) {
  81. a.permissionsLock.Lock()
  82. defer a.permissionsLock.Unlock()
  83. delete(a.permissions, addr2IPFingerprint(addr))
  84. }
  85. // AddChannelBind adds a new ChannelBind to the allocation, it also updates the
  86. // permissions needed for this ChannelBind
  87. func (a *Allocation) AddChannelBind(c *ChannelBind, lifetime time.Duration) error {
  88. // Check that this channel id isn't bound to another transport address, and
  89. // that this transport address isn't bound to another channel number.
  90. channelByNumber := a.GetChannelByNumber(c.Number)
  91. if channelByNumber != a.GetChannelByAddr(c.Peer) {
  92. return errSameChannelDifferentPeer
  93. }
  94. // Add or refresh this channel.
  95. if channelByNumber == nil {
  96. a.channelBindingsLock.Lock()
  97. defer a.channelBindingsLock.Unlock()
  98. c.allocation = a
  99. a.channelBindings = append(a.channelBindings, c)
  100. c.start(lifetime)
  101. // Channel binds also refresh permissions.
  102. a.AddPermission(NewPermission(c.Peer, a.log))
  103. } else {
  104. channelByNumber.refresh(lifetime)
  105. // Channel binds also refresh permissions.
  106. a.AddPermission(NewPermission(channelByNumber.Peer, a.log))
  107. }
  108. return nil
  109. }
  110. // RemoveChannelBind removes the ChannelBind from this allocation by id
  111. func (a *Allocation) RemoveChannelBind(number proto.ChannelNumber) bool {
  112. a.channelBindingsLock.Lock()
  113. defer a.channelBindingsLock.Unlock()
  114. for i := len(a.channelBindings) - 1; i >= 0; i-- {
  115. if a.channelBindings[i].Number == number {
  116. a.channelBindings = append(a.channelBindings[:i], a.channelBindings[i+1:]...)
  117. return true
  118. }
  119. }
  120. return false
  121. }
  122. // GetChannelByNumber gets the ChannelBind from this allocation by id
  123. func (a *Allocation) GetChannelByNumber(number proto.ChannelNumber) *ChannelBind {
  124. a.channelBindingsLock.RLock()
  125. defer a.channelBindingsLock.RUnlock()
  126. for _, cb := range a.channelBindings {
  127. if cb.Number == number {
  128. return cb
  129. }
  130. }
  131. return nil
  132. }
  133. // GetChannelByAddr gets the ChannelBind from this allocation by net.Addr
  134. func (a *Allocation) GetChannelByAddr(addr net.Addr) *ChannelBind {
  135. a.channelBindingsLock.RLock()
  136. defer a.channelBindingsLock.RUnlock()
  137. for _, cb := range a.channelBindings {
  138. if ipnet.AddrEqual(cb.Peer, addr) {
  139. return cb
  140. }
  141. }
  142. return nil
  143. }
  144. // Refresh updates the allocations lifetime
  145. func (a *Allocation) Refresh(lifetime time.Duration) {
  146. if !a.lifetimeTimer.Reset(lifetime) {
  147. a.log.Errorf("Failed to reset allocation timer for %v", a.fiveTuple)
  148. }
  149. }
  150. // SetResponseCache cache allocation response for retransmit allocation request
  151. func (a *Allocation) SetResponseCache(transactionID [stun.TransactionIDSize]byte, attrs []stun.Setter) {
  152. a.responseCache.Store(&allocationResponse{
  153. transactionID: transactionID,
  154. responseAttrs: attrs,
  155. })
  156. }
  157. // GetResponseCache return response cache for retransmit allocation request
  158. func (a *Allocation) GetResponseCache() (id [stun.TransactionIDSize]byte, attrs []stun.Setter) {
  159. if r := a.responseCache.Load(); r != nil {
  160. res := r.(*allocationResponse)
  161. id, attrs = res.transactionID, res.responseAttrs
  162. }
  163. return
  164. }
  165. // Close closes the allocation
  166. func (a *Allocation) Close() error {
  167. select {
  168. case <-a.closed:
  169. return nil
  170. default:
  171. }
  172. close(a.closed)
  173. a.lifetimeTimer.Stop()
  174. a.permissionsLock.RLock()
  175. for _, p := range a.permissions {
  176. p.lifetimeTimer.Stop()
  177. }
  178. a.permissionsLock.RUnlock()
  179. a.channelBindingsLock.RLock()
  180. for _, c := range a.channelBindings {
  181. c.lifetimeTimer.Stop()
  182. }
  183. a.channelBindingsLock.RUnlock()
  184. return a.RelaySocket.Close()
  185. }
  186. // https://tools.ietf.org/html/rfc5766#section-10.3
  187. // When the server receives a UDP datagram at a currently allocated
  188. // relayed transport address, the server looks up the allocation
  189. // associated with the relayed transport address. The server then
  190. // checks to see whether the set of permissions for the allocation allow
  191. // the relaying of the UDP datagram as described in Section 8.
  192. //
  193. // If relaying is permitted, then the server checks if there is a
  194. // channel bound to the peer that sent the UDP datagram (see
  195. // Section 11). If a channel is bound, then processing proceeds as
  196. // described in Section 11.7.
  197. //
  198. // If relaying is permitted but no channel is bound to the peer, then
  199. // the server forms and sends a Data indication. The Data indication
  200. // MUST contain both an XOR-PEER-ADDRESS and a DATA attribute. The DATA
  201. // attribute is set to the value of the 'data octets' field from the
  202. // datagram, and the XOR-PEER-ADDRESS attribute is set to the source
  203. // transport address of the received UDP datagram. The Data indication
  204. // is then sent on the 5-tuple associated with the allocation.
  205. const rtpMTU = 1600
  206. func (a *Allocation) packetHandler(m *Manager) {
  207. buffer := make([]byte, rtpMTU)
  208. for {
  209. n, srcAddr, err := a.RelaySocket.ReadFrom(buffer)
  210. if err != nil {
  211. m.DeleteAllocation(a.fiveTuple)
  212. return
  213. }
  214. a.log.Debugf("relay socket %s received %d bytes from %s",
  215. a.RelaySocket.LocalAddr().String(),
  216. n,
  217. srcAddr.String())
  218. if channel := a.GetChannelByAddr(srcAddr); channel != nil {
  219. channelData := &proto.ChannelData{
  220. Data: buffer[:n],
  221. Number: channel.Number,
  222. }
  223. channelData.Encode()
  224. if _, err = a.TurnSocket.WriteTo(channelData.Raw, a.fiveTuple.SrcAddr); err != nil {
  225. a.log.Errorf("Failed to send ChannelData from allocation %v %v", srcAddr, err)
  226. }
  227. } else if p := a.GetPermission(srcAddr); p != nil {
  228. udpAddr := srcAddr.(*net.UDPAddr)
  229. peerAddressAttr := proto.PeerAddress{IP: udpAddr.IP, Port: udpAddr.Port}
  230. dataAttr := proto.Data(buffer[:n])
  231. msg, err := stun.Build(stun.TransactionID, stun.NewType(stun.MethodData, stun.ClassIndication), peerAddressAttr, dataAttr)
  232. if err != nil {
  233. a.log.Errorf("Failed to send DataIndication from allocation %v %v", srcAddr, err)
  234. }
  235. a.log.Debugf("relaying message from %s to client at %s",
  236. srcAddr.String(),
  237. a.fiveTuple.SrcAddr.String())
  238. if _, err = a.TurnSocket.WriteTo(msg.Raw, a.fiveTuple.SrcAddr); err != nil {
  239. a.log.Errorf("Failed to send DataIndication from allocation %v %v", srcAddr, err)
  240. }
  241. } else {
  242. a.log.Infof("No Permission or Channel exists for %v on allocation %v", srcAddr, a.RelayAddr.String())
  243. }
  244. }
  245. }