dynamic.go 4.4 KB

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