inbound_detour.go 1.7 KB

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