hub.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. package udp
  2. import (
  3. "context"
  4. "v2ray.com/core/app/log"
  5. "v2ray.com/core/common/buf"
  6. "v2ray.com/core/common/dice"
  7. "v2ray.com/core/common/net"
  8. )
  9. // Payload represents a single UDP payload.
  10. type Payload struct {
  11. payload *buf.Buffer
  12. source net.Destination
  13. originalDest net.Destination
  14. }
  15. // PayloadHandler is function to handle Payload.
  16. type PayloadHandler func(payload *buf.Buffer, source net.Destination, originalDest net.Destination)
  17. // PayloadQueue is a queue of Payload.
  18. type PayloadQueue struct {
  19. queue []chan Payload
  20. callback PayloadHandler
  21. }
  22. // NewPayloadQueue returns a new PayloadQueue.
  23. func NewPayloadQueue(option ListenOption) *PayloadQueue {
  24. queue := &PayloadQueue{
  25. callback: option.Callback,
  26. queue: make([]chan Payload, option.Concurrency),
  27. }
  28. for i := range queue.queue {
  29. queue.queue[i] = make(chan Payload, 64)
  30. go queue.Dequeue(queue.queue[i])
  31. }
  32. return queue
  33. }
  34. // Enqueue adds the payload to the end of this queue.
  35. func (q *PayloadQueue) Enqueue(payload Payload) {
  36. size := len(q.queue)
  37. idx := 0
  38. if size > 1 {
  39. idx = dice.Roll(size)
  40. }
  41. for i := 0; i < size; i++ {
  42. select {
  43. case q.queue[idx%size] <- payload:
  44. return
  45. default:
  46. idx++
  47. }
  48. }
  49. }
  50. func (q *PayloadQueue) Dequeue(queue <-chan Payload) {
  51. for payload := range queue {
  52. q.callback(payload.payload, payload.source, payload.originalDest)
  53. }
  54. }
  55. func (q *PayloadQueue) Close() {
  56. for _, queue := range q.queue {
  57. close(queue)
  58. }
  59. }
  60. type ListenOption struct {
  61. Callback PayloadHandler
  62. ReceiveOriginalDest bool
  63. Concurrency int
  64. }
  65. type Hub struct {
  66. conn *net.UDPConn
  67. cancel context.CancelFunc
  68. queue *PayloadQueue
  69. option ListenOption
  70. }
  71. func ListenUDP(address net.Address, port net.Port, option ListenOption) (*Hub, error) {
  72. if option.Concurrency < 1 {
  73. option.Concurrency = 1
  74. }
  75. udpConn, err := net.ListenUDP("udp", &net.UDPAddr{
  76. IP: address.IP(),
  77. Port: int(port),
  78. })
  79. if err != nil {
  80. return nil, err
  81. }
  82. log.Trace(newError("listening UDP on ", address, ":", port))
  83. if option.ReceiveOriginalDest {
  84. rawConn, err := udpConn.SyscallConn()
  85. if err != nil {
  86. return nil, newError("failed to get fd").Base(err)
  87. }
  88. err = rawConn.Control(func(fd uintptr) {
  89. if err := SetOriginalDestOptions(int(fd)); err != nil {
  90. log.Trace(newError("failed to set socket options").Base(err))
  91. }
  92. })
  93. if err != nil {
  94. return nil, newError("failed to control socket").Base(err)
  95. }
  96. }
  97. ctx, cancel := context.WithCancel(context.Background())
  98. hub := &Hub{
  99. conn: udpConn,
  100. queue: NewPayloadQueue(option),
  101. option: option,
  102. cancel: cancel,
  103. }
  104. go hub.start(ctx)
  105. return hub, nil
  106. }
  107. func (h *Hub) Close() {
  108. h.cancel()
  109. h.conn.Close()
  110. }
  111. func (h *Hub) WriteTo(payload []byte, dest net.Destination) (int, error) {
  112. return h.conn.WriteToUDP(payload, &net.UDPAddr{
  113. IP: dest.Address.IP(),
  114. Port: int(dest.Port),
  115. })
  116. }
  117. func (h *Hub) start(ctx context.Context) {
  118. oobBytes := make([]byte, 256)
  119. L:
  120. for {
  121. select {
  122. case <-ctx.Done():
  123. break L
  124. default:
  125. }
  126. buffer := buf.New()
  127. var noob int
  128. var addr *net.UDPAddr
  129. err := buffer.AppendSupplier(func(b []byte) (int, error) {
  130. n, nb, _, a, e := ReadUDPMsg(h.conn, b, oobBytes)
  131. noob = nb
  132. addr = a
  133. return n, e
  134. })
  135. if err != nil {
  136. log.Trace(newError("failed to read UDP msg").Base(err))
  137. buffer.Release()
  138. continue
  139. }
  140. payload := Payload{
  141. payload: buffer,
  142. }
  143. payload.source = net.UDPDestination(net.IPAddress(addr.IP), net.Port(addr.Port))
  144. if h.option.ReceiveOriginalDest && noob > 0 {
  145. payload.originalDest = RetrieveOriginalDest(oobBytes[:noob])
  146. }
  147. h.queue.Enqueue(payload)
  148. }
  149. h.queue.Close()
  150. }
  151. func (h *Hub) Addr() net.Addr {
  152. return h.conn.LocalAddr()
  153. }