inbound_detour.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package point
  2. import (
  3. "github.com/v2ray/v2ray-core/common/log"
  4. v2net "github.com/v2ray/v2ray-core/common/net"
  5. "github.com/v2ray/v2ray-core/common/retry"
  6. "github.com/v2ray/v2ray-core/proxy/common/connhandler"
  7. "github.com/v2ray/v2ray-core/shell/point/config"
  8. )
  9. type InboundConnectionHandlerWithPort struct {
  10. port v2net.Port
  11. handler connhandler.InboundConnectionHandler
  12. }
  13. // Handler for inbound detour connections.
  14. type InboundDetourHandler struct {
  15. point *Point
  16. config config.InboundDetourConfig
  17. ich []*InboundConnectionHandlerWithPort
  18. }
  19. func (this *InboundDetourHandler) Initialize() error {
  20. ichFactory := connhandler.GetInboundConnectionHandlerFactory(this.config.Protocol())
  21. if ichFactory == nil {
  22. log.Error("Unknown inbound connection handler factory %s", this.config.Protocol())
  23. return config.BadConfiguration
  24. }
  25. ports := this.config.PortRange()
  26. this.ich = make([]*InboundConnectionHandlerWithPort, 0, ports.To()-ports.From()+1)
  27. for i := ports.From(); i <= ports.To(); i++ {
  28. ichConfig := this.config.Settings()
  29. ich, err := ichFactory.Create(this.point, ichConfig)
  30. if err != nil {
  31. log.Error("Failed to create inbound connection handler: %v", err)
  32. return err
  33. }
  34. this.ich = append(this.ich, &InboundConnectionHandlerWithPort{
  35. port: i,
  36. handler: ich,
  37. })
  38. }
  39. return nil
  40. }
  41. // Starts the inbound connection handler.
  42. func (this *InboundDetourHandler) Start() error {
  43. for _, ich := range this.ich {
  44. err := retry.Timed(100 /* times */, 100 /* ms */).On(func() error {
  45. err := ich.handler.Listen(ich.port)
  46. if err != nil {
  47. log.Error("Failed to start inbound detour on port %d: %v", ich.port, err)
  48. return err
  49. }
  50. return nil
  51. })
  52. if err != nil {
  53. return err
  54. }
  55. }
  56. return nil
  57. }