hub.go 3.7 KB

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