hub.go 3.8 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/app/log"
  8. v2net "v2ray.com/core/common/net"
  9. "v2ray.com/core/common/signal"
  10. "v2ray.com/core/transport/internet/internal"
  11. )
  12. // Payload represents a single UDP payload.
  13. type Payload struct {
  14. payload *buf.Buffer
  15. source v2net.Destination
  16. originalDest v2net.Destination
  17. }
  18. // PayloadHandler is function to handle Payload.
  19. type PayloadHandler func(payload *buf.Buffer, source v2net.Destination, originalDest v2net.Destination)
  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.source, payload.originalDest)
  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. log.Info("UDP|Hub: Listening on ", address, ":", port)
  86. if option.ReceiveOriginalDest {
  87. fd, err := internal.GetSysFd(udpConn)
  88. if err != nil {
  89. log.Warning("UDP|Listener: Failed to get fd: ", err)
  90. return nil, err
  91. }
  92. err = SetOriginalDestOptions(fd)
  93. if err != nil {
  94. log.Warning("UDP|Listener: Failed to set socket options: ", err)
  95. return nil, err
  96. }
  97. }
  98. hub := &Hub{
  99. conn: udpConn,
  100. queue: NewPayloadQueue(option),
  101. option: option,
  102. cancel: signal.NewCloseSignal(),
  103. }
  104. go hub.start()
  105. return hub, nil
  106. }
  107. func (v *Hub) Close() {
  108. v.Lock()
  109. defer v.Unlock()
  110. v.cancel.Cancel()
  111. v.conn.Close()
  112. v.cancel.WaitForDone()
  113. v.queue.Close()
  114. }
  115. func (v *Hub) WriteTo(payload []byte, dest v2net.Destination) (int, error) {
  116. return v.conn.WriteToUDP(payload, &net.UDPAddr{
  117. IP: dest.Address.IP(),
  118. Port: int(dest.Port),
  119. })
  120. }
  121. func (v *Hub) start() {
  122. v.cancel.WaitThread()
  123. defer v.cancel.FinishThread()
  124. oobBytes := make([]byte, 256)
  125. for v.Running() {
  126. buffer := buf.NewSmall()
  127. var noob int
  128. var addr *net.UDPAddr
  129. err := buffer.AppendSupplier(func(b []byte) (int, error) {
  130. n, nb, _, a, e := ReadUDPMsg(v.conn, b, oobBytes)
  131. noob = nb
  132. addr = a
  133. return n, e
  134. })
  135. if err != nil {
  136. log.Info("UDP|Hub: Failed to read UDP msg: ", err)
  137. buffer.Release()
  138. continue
  139. }
  140. payload := Payload{
  141. payload: buffer,
  142. }
  143. payload.source = v2net.UDPDestination(v2net.IPAddress(addr.IP), v2net.Port(addr.Port))
  144. if v.option.ReceiveOriginalDest && noob > 0 {
  145. payload.originalDest = RetrieveOriginalDest(oobBytes[:noob])
  146. }
  147. v.queue.Enqueue(payload)
  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. }