dynamic.go 4.2 KB

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