always.go 2.2 KB

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