inbound_detour.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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"
  8. "github.com/v2ray/v2ray-core/proxy/common/connhandler"
  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 InboundDetourConfig
  18. ich []*InboundConnectionHandlerWithPort
  19. }
  20. func (this *InboundDetourHandler) Initialize() error {
  21. ports := this.config.PortRange()
  22. this.ich = make([]*InboundConnectionHandlerWithPort, 0, ports.To()-ports.From()+1)
  23. for i := ports.From(); i <= ports.To(); i++ {
  24. ichConfig := this.config.Settings()
  25. ich, err := proxy.CreateInboundConnectionHandler(this.config.Protocol(), this.space, ichConfig)
  26. if err != nil {
  27. log.Error("Failed to create inbound connection handler: %v", err)
  28. return err
  29. }
  30. this.ich = append(this.ich, &InboundConnectionHandlerWithPort{
  31. port: i,
  32. handler: ich,
  33. })
  34. }
  35. return nil
  36. }
  37. // Starts the inbound connection handler.
  38. func (this *InboundDetourHandler) Start() error {
  39. for _, ich := range this.ich {
  40. err := retry.Timed(100 /* times */, 100 /* ms */).On(func() error {
  41. err := ich.handler.Listen(ich.port)
  42. if err != nil {
  43. log.Error("Failed to start inbound detour on port %d: %v", ich.port, err)
  44. return err
  45. }
  46. return nil
  47. })
  48. if err != nil {
  49. return err
  50. }
  51. }
  52. return nil
  53. }