inbound_detour.go 1.6 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"
  8. proxyrepo "github.com/v2ray/v2ray-core/proxy/repo"
  9. )
  10. type InboundConnectionHandlerWithPort struct {
  11. port v2net.Port
  12. handler proxy.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 := proxyrepo.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. func (this *InboundDetourHandler) Close() {
  38. for _, ich := range this.ich {
  39. ich.handler.Close()
  40. }
  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. }