dynamic.go 4.2 KB

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