inbound_detour_always.go 1.9 KB

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