hub.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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. func (v *PayloadQueue) Enqueue(payload Payload) {
  35. size := len(v.queue)
  36. idx := 0
  37. if size > 1 {
  38. idx = dice.Roll(size)
  39. }
  40. for i := 0; i < size; i++ {
  41. select {
  42. case v.queue[idx%size] <- payload:
  43. return
  44. default:
  45. idx++
  46. }
  47. }
  48. }
  49. func (v *PayloadQueue) Dequeue(queue <-chan Payload) {
  50. for payload := range queue {
  51. v.callback(payload.payload, payload.source, payload.originalDest)
  52. }
  53. }
  54. func (v *PayloadQueue) Close() {
  55. for _, queue := range v.queue {
  56. close(queue)
  57. }
  58. }
  59. type ListenOption struct {
  60. Callback PayloadHandler
  61. ReceiveOriginalDest bool
  62. Concurrency int
  63. }
  64. type Hub struct {
  65. conn *net.UDPConn
  66. cancel context.CancelFunc
  67. queue *PayloadQueue
  68. option ListenOption
  69. }
  70. func ListenUDP(address net.Address, port net.Port, option ListenOption) (*Hub, error) {
  71. if option.Concurrency < 1 {
  72. option.Concurrency = 1
  73. }
  74. udpConn, err := net.ListenUDP("udp", &net.UDPAddr{
  75. IP: address.IP(),
  76. Port: int(port),
  77. })
  78. if err != nil {
  79. return nil, err
  80. }
  81. log.Trace(newError("listening UDP on ", address, ":", port))
  82. if option.ReceiveOriginalDest {
  83. rawConn, err := udpConn.SyscallConn()
  84. if err != nil {
  85. return nil, newError("failed to get fd").Base(err)
  86. }
  87. err = rawConn.Control(func(fd uintptr) {
  88. if err := SetOriginalDestOptions(int(fd)); err != nil {
  89. log.Trace(newError("failed to set socket options").Base(err))
  90. }
  91. })
  92. if err != nil {
  93. return nil, newError("failed to control socket").Base(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 net.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.New()
  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.Trace(newError("failed to read UDP msg").Base(err))
  136. buffer.Release()
  137. continue
  138. }
  139. payload := Payload{
  140. payload: buffer,
  141. }
  142. payload.source = net.UDPDestination(net.IPAddress(addr.IP), net.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. }