dynamic.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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.FromContext(ctx)
  29. if v == nil {
  30. return nil, newError("V is not in context.")
  31. }
  32. h := &DynamicInboundHandler{
  33. tag: tag,
  34. proxyConfig: proxyConfig,
  35. receiverConfig: receiverConfig,
  36. portsInUse: make(map[net.Port]bool),
  37. mux: mux.NewServer(ctx),
  38. v: v,
  39. }
  40. h.task = &signal.PeriodicTask{
  41. Interval: time.Minute * time.Duration(h.receiverConfig.AllocationStrategy.GetRefreshValue()),
  42. Execute: h.refresh,
  43. }
  44. return h, nil
  45. }
  46. func (h *DynamicInboundHandler) allocatePort() net.Port {
  47. from := int(h.receiverConfig.PortRange.From)
  48. delta := int(h.receiverConfig.PortRange.To) - from + 1
  49. h.portMutex.Lock()
  50. defer h.portMutex.Unlock()
  51. for {
  52. r := dice.Roll(delta)
  53. port := net.Port(from + r)
  54. _, used := h.portsInUse[port]
  55. if !used {
  56. h.portsInUse[port] = true
  57. return port
  58. }
  59. }
  60. }
  61. func (h *DynamicInboundHandler) closeWorkers(workers []worker) {
  62. ports2Del := make([]net.Port, len(workers))
  63. for idx, worker := range workers {
  64. ports2Del[idx] = worker.Port()
  65. worker.Close()
  66. }
  67. h.portMutex.Lock()
  68. for _, port := range ports2Del {
  69. delete(h.portsInUse, port)
  70. }
  71. h.portMutex.Unlock()
  72. }
  73. func (h *DynamicInboundHandler) refresh() error {
  74. h.lastRefresh = time.Now()
  75. timeout := time.Minute * time.Duration(h.receiverConfig.AllocationStrategy.GetRefreshValue()) * 2
  76. concurrency := h.receiverConfig.AllocationStrategy.GetConcurrencyValue()
  77. workers := make([]worker, 0, concurrency)
  78. address := h.receiverConfig.Listen.AsAddress()
  79. if address == nil {
  80. address = net.AnyIP
  81. }
  82. for i := uint32(0); i < concurrency; i++ {
  83. port := h.allocatePort()
  84. rawProxy, err := h.v.CreateObject(h.proxyConfig)
  85. if err != nil {
  86. newError("failed to create proxy instance").Base(err).AtWarning().WriteToLog()
  87. continue
  88. }
  89. p := rawProxy.(proxy.Inbound)
  90. nl := p.Network()
  91. if nl.HasNetwork(net.Network_TCP) {
  92. worker := &tcpWorker{
  93. tag: h.tag,
  94. address: address,
  95. port: port,
  96. proxy: p,
  97. stream: h.receiverConfig.StreamSettings,
  98. recvOrigDest: h.receiverConfig.ReceiveOriginalDestination,
  99. dispatcher: h.mux,
  100. sniffers: h.receiverConfig.DomainOverride,
  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. }
  117. if err := worker.Start(); err != nil {
  118. newError("failed to create UDP worker").Base(err).AtWarning().WriteToLog()
  119. continue
  120. }
  121. workers = append(workers, worker)
  122. }
  123. }
  124. h.workerMutex.Lock()
  125. h.worker = workers
  126. h.workerMutex.Unlock()
  127. time.AfterFunc(timeout, func() {
  128. h.closeWorkers(workers)
  129. })
  130. return nil
  131. }
  132. func (h *DynamicInboundHandler) Start() error {
  133. return h.task.Start()
  134. }
  135. func (h *DynamicInboundHandler) Close() error {
  136. return h.task.Close()
  137. }
  138. func (h *DynamicInboundHandler) GetRandomInboundProxy() (interface{}, net.Port, int) {
  139. h.workerMutex.RLock()
  140. defer h.workerMutex.RUnlock()
  141. if len(h.worker) == 0 {
  142. return nil, 0, 0
  143. }
  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. }
  148. func (h *DynamicInboundHandler) Tag() string {
  149. return h.tag
  150. }