always.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package inbound
  2. import (
  3. "context"
  4. "v2ray.com/core/app/log"
  5. "v2ray.com/core/app/proxyman"
  6. "v2ray.com/core/app/proxyman/mux"
  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. }
  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. }
  25. nl := p.Network()
  26. pr := receiverConfig.PortRange
  27. address := receiverConfig.Listen.AsAddress()
  28. if address == nil {
  29. address = net.AnyIP
  30. }
  31. for port := pr.From; port <= pr.To; port++ {
  32. if nl.HasNetwork(net.Network_TCP) {
  33. log.Trace(newError("creating tcp worker on ", address, ":", port).AtDebug())
  34. worker := &tcpWorker{
  35. address: address,
  36. port: net.Port(port),
  37. proxy: p,
  38. stream: receiverConfig.StreamSettings,
  39. recvOrigDest: receiverConfig.ReceiveOriginalDestination,
  40. tag: tag,
  41. dispatcher: h.mux,
  42. sniffers: receiverConfig.DomainOverride,
  43. }
  44. h.workers = append(h.workers, worker)
  45. }
  46. if nl.HasNetwork(net.Network_UDP) {
  47. worker := &udpWorker{
  48. tag: tag,
  49. proxy: p,
  50. address: address,
  51. port: net.Port(port),
  52. recvOrigDest: receiverConfig.ReceiveOriginalDestination,
  53. dispatcher: h.mux,
  54. }
  55. h.workers = append(h.workers, worker)
  56. }
  57. }
  58. return h, nil
  59. }
  60. func (h *AlwaysOnInboundHandler) Start() error {
  61. for _, worker := range h.workers {
  62. if err := worker.Start(); err != nil {
  63. return err
  64. }
  65. }
  66. return nil
  67. }
  68. func (h *AlwaysOnInboundHandler) Close() {
  69. for _, worker := range h.workers {
  70. worker.Close()
  71. }
  72. }
  73. func (h *AlwaysOnInboundHandler) GetRandomInboundProxy() (proxy.Inbound, net.Port, int) {
  74. if len(h.workers) == 0 {
  75. return nil, 0, 0
  76. }
  77. w := h.workers[dice.Roll(len(h.workers))]
  78. return w.Proxy(), w.Port(), 9999
  79. }