always.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package inbound
  2. import (
  3. "context"
  4. "v2ray.com/core/app/proxyman"
  5. "v2ray.com/core/app/proxyman/mux"
  6. "v2ray.com/core/common"
  7. "v2ray.com/core/common/dice"
  8. "v2ray.com/core/common/net"
  9. "v2ray.com/core/proxy"
  10. )
  11. type AlwaysOnInboundHandler struct {
  12. proxy proxy.Inbound
  13. workers []worker
  14. mux *mux.Server
  15. tag string
  16. }
  17. func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig *proxyman.ReceiverConfig, proxyConfig interface{}) (*AlwaysOnInboundHandler, error) {
  18. rawProxy, err := common.CreateObject(ctx, proxyConfig)
  19. if err != nil {
  20. return nil, err
  21. }
  22. p, ok := rawProxy.(proxy.Inbound)
  23. if !ok {
  24. return nil, newError("not an inbound proxy.")
  25. }
  26. h := &AlwaysOnInboundHandler{
  27. proxy: p,
  28. mux: mux.NewServer(ctx),
  29. tag: tag,
  30. }
  31. nl := p.Network()
  32. pr := receiverConfig.PortRange
  33. address := receiverConfig.Listen.AsAddress()
  34. if address == nil {
  35. address = net.AnyIP
  36. }
  37. for port := pr.From; port <= pr.To; port++ {
  38. if nl.HasNetwork(net.Network_TCP) {
  39. newError("creating stream worker on ", address, ":", port).AtDebug().WriteToLog()
  40. worker := &tcpWorker{
  41. address: address,
  42. port: net.Port(port),
  43. proxy: p,
  44. stream: receiverConfig.StreamSettings,
  45. recvOrigDest: receiverConfig.ReceiveOriginalDestination,
  46. tag: tag,
  47. dispatcher: h.mux,
  48. sniffers: receiverConfig.DomainOverride,
  49. }
  50. h.workers = append(h.workers, worker)
  51. }
  52. if nl.HasNetwork(net.Network_UDP) {
  53. worker := &udpWorker{
  54. tag: tag,
  55. proxy: p,
  56. address: address,
  57. port: net.Port(port),
  58. recvOrigDest: receiverConfig.ReceiveOriginalDestination,
  59. dispatcher: h.mux,
  60. }
  61. h.workers = append(h.workers, worker)
  62. }
  63. }
  64. return h, nil
  65. }
  66. func (h *AlwaysOnInboundHandler) Start() error {
  67. for _, worker := range h.workers {
  68. if err := worker.Start(); err != nil {
  69. return err
  70. }
  71. }
  72. return nil
  73. }
  74. func (h *AlwaysOnInboundHandler) Close() error {
  75. for _, worker := range h.workers {
  76. worker.Close()
  77. }
  78. h.mux.Close()
  79. return nil
  80. }
  81. func (h *AlwaysOnInboundHandler) GetRandomInboundProxy() (interface{}, net.Port, int) {
  82. if len(h.workers) == 0 {
  83. return nil, 0, 0
  84. }
  85. w := h.workers[dice.Roll(len(h.workers))]
  86. return w.Proxy(), w.Port(), 9999
  87. }
  88. func (h *AlwaysOnInboundHandler) Tag() string {
  89. return h.tag
  90. }
  91. func (h *AlwaysOnInboundHandler) GetInbound() proxy.Inbound {
  92. return h.proxy
  93. }