dynamic.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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. allowPassiveConn: h.receiverConfig.AllowPassiveConnection,
  94. dispatcher: h.mux,
  95. }
  96. if err := worker.Start(); err != nil {
  97. log.Warning("Proxyman:InboundHandler: Failed to create TCP worker: ", err)
  98. continue
  99. }
  100. workers = append(workers, worker)
  101. }
  102. if nl.HasNetwork(v2net.Network_UDP) {
  103. worker := &udpWorker{
  104. tag: h.tag,
  105. proxy: p,
  106. address: address,
  107. port: port,
  108. recvOrigDest: h.receiverConfig.ReceiveOriginalDestination,
  109. dispatcher: h.mux,
  110. }
  111. if err := worker.Start(); err != nil {
  112. log.Warning("Proxyman:InboundHandler: Failed to create UDP worker: ", err)
  113. continue
  114. }
  115. workers = append(workers, worker)
  116. }
  117. }
  118. h.workerMutex.Lock()
  119. h.worker = workers
  120. h.workerMutex.Unlock()
  121. go h.waitAnyCloseWorkers(ctx, cancel, workers, timeout)
  122. return nil
  123. }
  124. func (h *DynamicInboundHandler) monitor() {
  125. for {
  126. select {
  127. case <-h.ctx.Done():
  128. return
  129. case <-time.After(time.Minute * time.Duration(h.receiverConfig.AllocationStrategy.GetRefreshValue())):
  130. h.refresh()
  131. }
  132. }
  133. }
  134. func (h *DynamicInboundHandler) Start() error {
  135. err := h.refresh()
  136. go h.monitor()
  137. return err
  138. }
  139. func (h *DynamicInboundHandler) Close() {
  140. h.cancel()
  141. }
  142. func (h *DynamicInboundHandler) GetRandomInboundProxy() (proxy.Inbound, v2net.Port, int) {
  143. h.workerMutex.RLock()
  144. defer h.workerMutex.RUnlock()
  145. w := h.worker[dice.Roll(len(h.worker))]
  146. expire := h.receiverConfig.AllocationStrategy.GetRefreshValue() - uint32(time.Since(h.lastRefresh)/time.Minute)
  147. return w.Proxy(), w.Port(), int(expire)
  148. }