hub.go 3.8 KB

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