inbound_detour_always.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package point
  2. import (
  3. "github.com/v2ray/v2ray-core/app"
  4. "github.com/v2ray/v2ray-core/common/dice"
  5. "github.com/v2ray/v2ray-core/common/log"
  6. "github.com/v2ray/v2ray-core/common/retry"
  7. "github.com/v2ray/v2ray-core/proxy"
  8. proxyrepo "github.com/v2ray/v2ray-core/proxy/repo"
  9. )
  10. // Handler for inbound detour connections.
  11. type InboundDetourHandlerAlways struct {
  12. space app.Space
  13. config *InboundDetourConfig
  14. ich []proxy.InboundHandler
  15. }
  16. func NewInboundDetourHandlerAlways(space app.Space, config *InboundDetourConfig) (*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.From; i <= ports.To; i++ {
  24. ichConfig := config.Settings
  25. ich, err := proxyrepo.CreateInboundHandler(config.Protocol, space, ichConfig, &proxy.InboundHandlerMeta{
  26. Address: config.ListenOn,
  27. Port: i,
  28. Tag: config.Tag,
  29. StreamSettings: config.StreamSettings,
  30. AllowPassiveConnection: config.AllowPassiveConnection,
  31. })
  32. if err != nil {
  33. log.Error("Failed to create inbound connection handler: ", err)
  34. return nil, err
  35. }
  36. handler.ich = append(handler.ich, ich)
  37. }
  38. return handler, nil
  39. }
  40. func (this *InboundDetourHandlerAlways) GetConnectionHandler() (proxy.InboundHandler, int) {
  41. ich := this.ich[dice.Roll(len(this.ich))]
  42. return ich, this.config.Allocation.Refresh
  43. }
  44. func (this *InboundDetourHandlerAlways) Close() {
  45. for _, ich := range this.ich {
  46. ich.Close()
  47. }
  48. }
  49. // Starts the inbound connection handler.
  50. func (this *InboundDetourHandlerAlways) Start() error {
  51. for _, ich := range this.ich {
  52. err := retry.Timed(100 /* times */, 100 /* ms */).On(func() error {
  53. err := ich.Start()
  54. if err != nil {
  55. log.Error("Failed to start inbound detour:", err)
  56. return err
  57. }
  58. return nil
  59. })
  60. if err != nil {
  61. return err
  62. }
  63. }
  64. return nil
  65. }