inbound_detour_always.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. if err != nil {
  31. log.Error("Failed to create inbound connection handler: ", err)
  32. return nil, err
  33. }
  34. handler.ich = append(handler.ich, ich)
  35. }
  36. return handler, nil
  37. }
  38. func (this *InboundDetourHandlerAlways) GetConnectionHandler() (proxy.InboundHandler, int) {
  39. ich := this.ich[dice.Roll(len(this.ich))]
  40. return ich, this.config.Allocation.Refresh
  41. }
  42. func (this *InboundDetourHandlerAlways) Close() {
  43. for _, ich := range this.ich {
  44. ich.Close()
  45. }
  46. }
  47. // Starts the inbound connection handler.
  48. func (this *InboundDetourHandlerAlways) Start() error {
  49. for _, ich := range this.ich {
  50. err := retry.Timed(100 /* times */, 100 /* ms */).On(func() error {
  51. err := ich.Start()
  52. if err != nil {
  53. log.Error("Failed to start inbound detour:", err)
  54. return err
  55. }
  56. return nil
  57. })
  58. if err != nil {
  59. return err
  60. }
  61. }
  62. return nil
  63. }