hub.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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.Trace(newError("listening UDP on ", address, ":", port))
  84. if option.ReceiveOriginalDest {
  85. fd, err := internal.GetSysFd(udpConn)
  86. if err != nil {
  87. return nil, newError("failed to get fd").Base(err)
  88. }
  89. err = SetOriginalDestOptions(fd)
  90. if err != nil {
  91. return nil, newError("failed to set socket options").Base(err)
  92. }
  93. }
  94. ctx, cancel := context.WithCancel(context.Background())
  95. hub := &Hub{
  96. conn: udpConn,
  97. queue: NewPayloadQueue(option),
  98. option: option,
  99. cancel: cancel,
  100. }
  101. go hub.start(ctx)
  102. return hub, nil
  103. }
  104. func (v *Hub) Close() {
  105. v.cancel()
  106. v.conn.Close()
  107. }
  108. func (v *Hub) WriteTo(payload []byte, dest v2net.Destination) (int, error) {
  109. return v.conn.WriteToUDP(payload, &net.UDPAddr{
  110. IP: dest.Address.IP(),
  111. Port: int(dest.Port),
  112. })
  113. }
  114. func (v *Hub) start(ctx context.Context) {
  115. oobBytes := make([]byte, 256)
  116. L:
  117. for {
  118. select {
  119. case <-ctx.Done():
  120. break L
  121. default:
  122. }
  123. buffer := buf.New()
  124. var noob int
  125. var addr *net.UDPAddr
  126. err := buffer.AppendSupplier(func(b []byte) (int, error) {
  127. n, nb, _, a, e := ReadUDPMsg(v.conn, b, oobBytes)
  128. noob = nb
  129. addr = a
  130. return n, e
  131. })
  132. if err != nil {
  133. log.Trace(newError("failed to read UDP msg").Base(err))
  134. buffer.Release()
  135. continue
  136. }
  137. payload := Payload{
  138. payload: buffer,
  139. }
  140. payload.source = v2net.UDPDestination(v2net.IPAddress(addr.IP), v2net.Port(addr.Port))
  141. if v.option.ReceiveOriginalDest && noob > 0 {
  142. payload.originalDest = RetrieveOriginalDest(oobBytes[:noob])
  143. }
  144. v.queue.Enqueue(payload)
  145. }
  146. v.queue.Close()
  147. }
  148. // Connection returns the net.Conn underneath this hub.
  149. // Private: Visible for testing only
  150. func (v *Hub) Connection() net.Conn {
  151. return v.conn
  152. }
  153. func (v *Hub) Addr() net.Addr {
  154. return v.conn.LocalAddr()
  155. }