dynamic.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. package inbound
  2. import (
  3. "context"
  4. "sync"
  5. "time"
  6. "v2ray.com/core/app/log"
  7. "v2ray.com/core/app/proxyman"
  8. "v2ray.com/core/app/proxyman/mux"
  9. "v2ray.com/core/common/dice"
  10. v2net "v2ray.com/core/common/net"
  11. "v2ray.com/core/proxy"
  12. )
  13. type DynamicInboundHandler struct {
  14. tag string
  15. ctx context.Context
  16. cancel context.CancelFunc
  17. proxyConfig interface{}
  18. receiverConfig *proxyman.ReceiverConfig
  19. portMutex sync.Mutex
  20. portsInUse map[v2net.Port]bool
  21. workerMutex sync.RWMutex
  22. worker []worker
  23. lastRefresh time.Time
  24. mux *mux.Server
  25. }
  26. func NewDynamicInboundHandler(ctx context.Context, tag string, receiverConfig *proxyman.ReceiverConfig, proxyConfig interface{}) (*DynamicInboundHandler, error) {
  27. ctx, cancel := context.WithCancel(ctx)
  28. h := &DynamicInboundHandler{
  29. ctx: ctx,
  30. tag: tag,
  31. cancel: cancel,
  32. proxyConfig: proxyConfig,
  33. receiverConfig: receiverConfig,
  34. portsInUse: make(map[v2net.Port]bool),
  35. mux: mux.NewServer(ctx),
  36. }
  37. return h, nil
  38. }
  39. func (h *DynamicInboundHandler) allocatePort() v2net.Port {
  40. from := int(h.receiverConfig.PortRange.From)
  41. delta := int(h.receiverConfig.PortRange.To) - from + 1
  42. h.portMutex.Lock()
  43. defer h.portMutex.Unlock()
  44. for {
  45. r := dice.Roll(delta)
  46. port := v2net.Port(from + r)
  47. _, used := h.portsInUse[port]
  48. if !used {
  49. h.portsInUse[port] = true
  50. return port
  51. }
  52. }
  53. }
  54. func (h *DynamicInboundHandler) waitAnyCloseWorkers(ctx context.Context, cancel context.CancelFunc, workers []worker, duration time.Duration) {
  55. time.Sleep(duration)
  56. cancel()
  57. ports2Del := make([]v2net.Port, len(workers))
  58. for idx, worker := range workers {
  59. ports2Del[idx] = worker.Port()
  60. worker.Close()
  61. }
  62. h.portMutex.Lock()
  63. for _, port := range ports2Del {
  64. delete(h.portsInUse, port)
  65. }
  66. h.portMutex.Unlock()
  67. }
  68. func (h *DynamicInboundHandler) refresh() error {
  69. h.lastRefresh = time.Now()
  70. timeout := time.Minute * time.Duration(h.receiverConfig.AllocationStrategy.GetRefreshValue()) * 2
  71. concurrency := h.receiverConfig.AllocationStrategy.GetConcurrencyValue()
  72. ctx, cancel := context.WithTimeout(h.ctx, timeout)
  73. workers := make([]worker, 0, concurrency)
  74. address := h.receiverConfig.Listen.AsAddress()
  75. if address == nil {
  76. address = v2net.AnyIP
  77. }
  78. for i := uint32(0); i < concurrency; i++ {
  79. port := h.allocatePort()
  80. p, err := proxy.CreateInboundHandler(ctx, h.proxyConfig)
  81. if err != nil {
  82. log.Trace(newError("failed to create proxy instance").Base(err).AtWarning())
  83. continue
  84. }
  85. nl := p.Network()
  86. if nl.HasNetwork(v2net.Network_TCP) {
  87. worker := &tcpWorker{
  88. tag: h.tag,
  89. address: address,
  90. port: port,
  91. proxy: p,
  92. stream: h.receiverConfig.StreamSettings,
  93. recvOrigDest: h.receiverConfig.ReceiveOriginalDestination,
  94. dispatcher: h.mux,
  95. sniffers: h.receiverConfig.DomainOverride,
  96. }
  97. if err := worker.Start(); err != nil {
  98. log.Trace(newError("failed to create TCP worker").Base(err).AtWarning())
  99. continue
  100. }
  101. workers = append(workers, worker)
  102. }
  103. if nl.HasNetwork(v2net.Network_UDP) {
  104. worker := &udpWorker{
  105. tag: h.tag,
  106. proxy: p,
  107. address: address,
  108. port: port,
  109. recvOrigDest: h.receiverConfig.ReceiveOriginalDestination,
  110. dispatcher: h.mux,
  111. }
  112. if err := worker.Start(); err != nil {
  113. log.Trace(newError("failed to create UDP worker").Base(err).AtWarning())
  114. continue
  115. }
  116. workers = append(workers, worker)
  117. }
  118. }
  119. h.workerMutex.Lock()
  120. h.worker = workers
  121. h.workerMutex.Unlock()
  122. go h.waitAnyCloseWorkers(ctx, cancel, workers, timeout)
  123. return nil
  124. }
  125. func (h *DynamicInboundHandler) monitor() {
  126. timer := time.NewTicker(time.Minute * time.Duration(h.receiverConfig.AllocationStrategy.GetRefreshValue()))
  127. defer timer.Stop()
  128. for {
  129. select {
  130. case <-h.ctx.Done():
  131. return
  132. case <-timer.C:
  133. h.refresh()
  134. }
  135. }
  136. }
  137. func (h *DynamicInboundHandler) Start() error {
  138. err := h.refresh()
  139. go h.monitor()
  140. return err
  141. }
  142. func (h *DynamicInboundHandler) Close() {
  143. h.cancel()
  144. }
  145. func (h *DynamicInboundHandler) GetRandomInboundProxy() (proxy.Inbound, v2net.Port, int) {
  146. h.workerMutex.RLock()
  147. defer h.workerMutex.RUnlock()
  148. if len(h.worker) == 0 {
  149. return nil, 0, 0
  150. }
  151. w := h.worker[dice.Roll(len(h.worker))]
  152. expire := h.receiverConfig.AllocationStrategy.GetRefreshValue() - uint32(time.Since(h.lastRefresh)/time.Minute)
  153. return w.Proxy(), w.Port(), int(expire)
  154. }