inbound_detour_always.go 2.0 KB

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