inbound_detour_always.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package core
  2. import (
  3. "v2ray.com/core/app"
  4. "v2ray.com/core/common/dice"
  5. "v2ray.com/core/common/log"
  6. "v2ray.com/core/common/retry"
  7. "v2ray.com/core/proxy"
  8. proxyregistry "v2ray.com/core/proxy/registry"
  9. )
  10. // Handler for inbound detour connections.
  11. type InboundDetourHandlerAlways struct {
  12. space app.Space
  13. config *InboundConnectionConfig
  14. ich []proxy.InboundHandler
  15. }
  16. func NewInboundDetourHandlerAlways(space app.Space, config *InboundConnectionConfig) (*InboundDetourHandlerAlways, error) {
  17. handler := &InboundDetourHandlerAlways{
  18. space: space,
  19. config: config,
  20. }
  21. ports := config.PortRange
  22. handler.ich = make([]proxy.InboundHandler, 0, ports.To-ports.From+1)
  23. for i := ports.FromPort(); i <= ports.ToPort(); i++ {
  24. ichConfig, err := config.GetTypedSettings()
  25. if err != nil {
  26. return nil, err
  27. }
  28. ich, err := proxyregistry.CreateInboundHandler(config.Settings.Type, space, ichConfig, &proxy.InboundHandlerMeta{
  29. Address: config.GetListenOnValue(),
  30. Port: i,
  31. Tag: config.Tag,
  32. StreamSettings: config.StreamSettings,
  33. AllowPassiveConnection: config.AllowPassiveConnection,
  34. })
  35. if err != nil {
  36. log.Error("Failed to create inbound connection handler: ", err)
  37. return nil, err
  38. }
  39. handler.ich = append(handler.ich, ich)
  40. }
  41. return handler, nil
  42. }
  43. func (v *InboundDetourHandlerAlways) GetConnectionHandler() (proxy.InboundHandler, int) {
  44. ich := v.ich[dice.Roll(len(v.ich))]
  45. return ich, int(v.config.GetAllocationStrategyValue().Refresh.GetValue())
  46. }
  47. func (v *InboundDetourHandlerAlways) Close() {
  48. for _, ich := range v.ich {
  49. ich.Close()
  50. }
  51. }
  52. // Starts the inbound connection handler.
  53. func (v *InboundDetourHandlerAlways) Start() error {
  54. for _, ich := range v.ich {
  55. err := retry.ExponentialBackoff(10 /* times */, 200 /* ms */).On(func() error {
  56. err := ich.Start()
  57. if err != nil {
  58. log.Error("Failed to start inbound detour:", err)
  59. return err
  60. }
  61. return nil
  62. })
  63. if err != nil {
  64. return err
  65. }
  66. }
  67. return nil
  68. }