hub.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. package udp
  2. import (
  3. "net"
  4. "sync"
  5. "v2ray.com/core/common/buf"
  6. "v2ray.com/core/common/dice"
  7. "v2ray.com/core/common/log"
  8. v2net "v2ray.com/core/common/net"
  9. "v2ray.com/core/common/signal"
  10. "v2ray.com/core/proxy"
  11. "v2ray.com/core/transport/internet/internal"
  12. )
  13. // Payload represents a single UDP payload.
  14. type Payload struct {
  15. payload *buf.Buffer
  16. session *proxy.SessionInfo
  17. }
  18. // PayloadHandler is function to handle Payload.
  19. type PayloadHandler func(*buf.Buffer, *proxy.SessionInfo)
  20. // PayloadQueue is a queue of Payload.
  21. type PayloadQueue struct {
  22. queue []chan Payload
  23. callback PayloadHandler
  24. }
  25. // NewPayloadQueue returns a new PayloadQueue.
  26. func NewPayloadQueue(option ListenOption) *PayloadQueue {
  27. queue := &PayloadQueue{
  28. callback: option.Callback,
  29. queue: make([]chan Payload, option.Concurrency),
  30. }
  31. for i := range queue.queue {
  32. queue.queue[i] = make(chan Payload, 64)
  33. go queue.Dequeue(queue.queue[i])
  34. }
  35. return queue
  36. }
  37. func (v *PayloadQueue) Enqueue(payload Payload) {
  38. size := len(v.queue)
  39. idx := 0
  40. if size > 1 {
  41. idx = dice.Roll(size)
  42. }
  43. for i := 0; i < size; i++ {
  44. select {
  45. case v.queue[idx%size] <- payload:
  46. return
  47. default:
  48. idx++
  49. }
  50. }
  51. }
  52. func (v *PayloadQueue) Dequeue(queue <-chan Payload) {
  53. for payload := range queue {
  54. v.callback(payload.payload, payload.session)
  55. }
  56. }
  57. func (v *PayloadQueue) Close() {
  58. for _, queue := range v.queue {
  59. close(queue)
  60. }
  61. }
  62. type ListenOption struct {
  63. Callback PayloadHandler
  64. ReceiveOriginalDest bool
  65. Concurrency int
  66. }
  67. type Hub struct {
  68. sync.RWMutex
  69. conn *net.UDPConn
  70. cancel *signal.CancelSignal
  71. queue *PayloadQueue
  72. option ListenOption
  73. }
  74. func ListenUDP(address v2net.Address, port v2net.Port, option ListenOption) (*Hub, error) {
  75. if option.Concurrency < 1 {
  76. option.Concurrency = 1
  77. }
  78. udpConn, err := net.ListenUDP("udp", &net.UDPAddr{
  79. IP: address.IP(),
  80. Port: int(port),
  81. })
  82. if err != nil {
  83. return nil, err
  84. }
  85. if option.ReceiveOriginalDest {
  86. fd, err := internal.GetSysFd(udpConn)
  87. if err != nil {
  88. log.Warning("UDP|Listener: Failed to get fd: ", err)
  89. return nil, err
  90. }
  91. err = SetOriginalDestOptions(fd)
  92. if err != nil {
  93. log.Warning("UDP|Listener: Failed to set socket options: ", err)
  94. return nil, err
  95. }
  96. }
  97. hub := &Hub{
  98. conn: udpConn,
  99. queue: NewPayloadQueue(option),
  100. option: option,
  101. cancel: signal.NewCloseSignal(),
  102. }
  103. go hub.start()
  104. return hub, nil
  105. }
  106. func (v *Hub) Close() {
  107. v.Lock()
  108. defer v.Unlock()
  109. v.cancel.Cancel()
  110. v.conn.Close()
  111. v.cancel.WaitForDone()
  112. v.queue.Close()
  113. }
  114. func (v *Hub) WriteTo(payload []byte, dest v2net.Destination) (int, error) {
  115. return v.conn.WriteToUDP(payload, &net.UDPAddr{
  116. IP: dest.Address.IP(),
  117. Port: int(dest.Port),
  118. })
  119. }
  120. func (v *Hub) start() {
  121. v.cancel.WaitThread()
  122. defer v.cancel.FinishThread()
  123. oobBytes := make([]byte, 256)
  124. for v.Running() {
  125. buffer := buf.NewSmall()
  126. var noob int
  127. var addr *net.UDPAddr
  128. err := buffer.AppendSupplier(func(b []byte) (int, error) {
  129. n, nb, _, a, e := ReadUDPMsg(v.conn, b, oobBytes)
  130. noob = nb
  131. addr = a
  132. return n, e
  133. })
  134. if err != nil {
  135. log.Info("UDP|Hub: Failed to read UDP msg: ", err)
  136. buffer.Release()
  137. continue
  138. }
  139. session := new(proxy.SessionInfo)
  140. session.Source = v2net.UDPDestination(v2net.IPAddress(addr.IP), v2net.Port(addr.Port))
  141. if v.option.ReceiveOriginalDest && noob > 0 {
  142. session.Destination = RetrieveOriginalDest(oobBytes[:noob])
  143. }
  144. v.queue.Enqueue(Payload{
  145. payload: buffer,
  146. session: session,
  147. })
  148. }
  149. }
  150. func (v *Hub) Running() bool {
  151. return !v.cancel.Cancelled()
  152. }
  153. // Connection return the net.Conn underneath this hub.
  154. // Private: Visible for testing only
  155. func (v *Hub) Connection() net.Conn {
  156. return v.conn
  157. }
  158. func (v *Hub) Addr() net.Addr {
  159. return v.conn.LocalAddr()
  160. }