dynamic.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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. for i := uint32(0); i < concurrency; i++ {
  80. port := h.allocatePort()
  81. rawProxy, err := h.v.CreateObject(h.proxyConfig)
  82. if err != nil {
  83. newError("failed to create proxy instance").Base(err).AtWarning().WriteToLog()
  84. continue
  85. }
  86. p := rawProxy.(proxy.Inbound)
  87. nl := p.Network()
  88. if nl.HasNetwork(net.Network_TCP) {
  89. worker := &tcpWorker{
  90. tag: h.tag,
  91. address: address,
  92. port: port,
  93. proxy: p,
  94. stream: h.receiverConfig.StreamSettings,
  95. recvOrigDest: h.receiverConfig.ReceiveOriginalDestination,
  96. dispatcher: h.mux,
  97. sniffers: h.receiverConfig.DomainOverride,
  98. }
  99. if err := worker.Start(); err != nil {
  100. newError("failed to create TCP worker").Base(err).AtWarning().WriteToLog()
  101. continue
  102. }
  103. workers = append(workers, worker)
  104. }
  105. if nl.HasNetwork(net.Network_UDP) {
  106. worker := &udpWorker{
  107. tag: h.tag,
  108. proxy: p,
  109. address: address,
  110. port: port,
  111. recvOrigDest: h.receiverConfig.ReceiveOriginalDestination,
  112. dispatcher: h.mux,
  113. }
  114. if err := worker.Start(); err != nil {
  115. newError("failed to create UDP worker").Base(err).AtWarning().WriteToLog()
  116. continue
  117. }
  118. workers = append(workers, worker)
  119. }
  120. }
  121. h.workerMutex.Lock()
  122. h.worker = workers
  123. h.workerMutex.Unlock()
  124. time.AfterFunc(timeout, func() {
  125. h.closeWorkers(workers)
  126. })
  127. return nil
  128. }
  129. func (h *DynamicInboundHandler) Start() error {
  130. return h.task.Start()
  131. }
  132. func (h *DynamicInboundHandler) Close() error {
  133. return h.task.Close()
  134. }
  135. func (h *DynamicInboundHandler) GetRandomInboundProxy() (interface{}, net.Port, int) {
  136. h.workerMutex.RLock()
  137. defer h.workerMutex.RUnlock()
  138. if len(h.worker) == 0 {
  139. return nil, 0, 0
  140. }
  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. }
  145. func (h *DynamicInboundHandler) Tag() string {
  146. return h.tag
  147. }