always.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. }
  43. h.workers = append(h.workers, worker)
  44. }
  45. if nl.HasNetwork(net.Network_UDP) {
  46. worker := &udpWorker{
  47. tag: tag,
  48. proxy: p,
  49. address: address,
  50. port: net.Port(port),
  51. recvOrigDest: receiverConfig.ReceiveOriginalDestination,
  52. dispatcher: h.mux,
  53. }
  54. h.workers = append(h.workers, worker)
  55. }
  56. }
  57. return h, nil
  58. }
  59. func (h *AlwaysOnInboundHandler) Start() error {
  60. for _, worker := range h.workers {
  61. if err := worker.Start(); err != nil {
  62. return err
  63. }
  64. }
  65. return nil
  66. }
  67. func (h *AlwaysOnInboundHandler) Close() {
  68. for _, worker := range h.workers {
  69. worker.Close()
  70. }
  71. }
  72. func (h *AlwaysOnInboundHandler) GetRandomInboundProxy() (proxy.Inbound, net.Port, int) {
  73. if len(h.workers) == 0 {
  74. return nil, 0, 0
  75. }
  76. w := h.workers[dice.Roll(len(h.workers))]
  77. return w.Proxy(), w.Port(), 9999
  78. }