inbound_detour_always.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. v2net "github.com/v2ray/v2ray-core/common/net"
  7. "github.com/v2ray/v2ray-core/common/retry"
  8. "github.com/v2ray/v2ray-core/proxy"
  9. proxyrepo "github.com/v2ray/v2ray-core/proxy/repo"
  10. )
  11. type InboundConnectionHandlerWithPort struct {
  12. port v2net.Port
  13. handler proxy.InboundConnectionHandler
  14. }
  15. // Handler for inbound detour connections.
  16. type InboundDetourHandlerAlways struct {
  17. space app.Space
  18. config *InboundDetourConfig
  19. ich []*InboundConnectionHandlerWithPort
  20. }
  21. func NewInboundDetourHandlerAlways(space app.Space, config *InboundDetourConfig) (*InboundDetourHandlerAlways, error) {
  22. handler := &InboundDetourHandlerAlways{
  23. space: space,
  24. config: config,
  25. }
  26. ports := config.PortRange
  27. handler.ich = make([]*InboundConnectionHandlerWithPort, 0, ports.To-ports.From+1)
  28. for i := ports.From; i <= ports.To; i++ {
  29. ichConfig := config.Settings
  30. ich, err := proxyrepo.CreateInboundConnectionHandler(config.Protocol, space, ichConfig)
  31. if err != nil {
  32. log.Error("Failed to create inbound connection handler: ", err)
  33. return nil, err
  34. }
  35. handler.ich = append(handler.ich, &InboundConnectionHandlerWithPort{
  36. port: i,
  37. handler: ich,
  38. })
  39. }
  40. return handler, nil
  41. }
  42. func (this *InboundDetourHandlerAlways) GetConnectionHandler() (proxy.InboundConnectionHandler, int) {
  43. ich := this.ich[dice.Roll(len(this.ich))]
  44. return ich.handler, this.config.Allocation.Refresh
  45. }
  46. func (this *InboundDetourHandlerAlways) Close() {
  47. for _, ich := range this.ich {
  48. ich.handler.Close()
  49. }
  50. }
  51. // Starts the inbound connection handler.
  52. func (this *InboundDetourHandlerAlways) Start() error {
  53. for _, ich := range this.ich {
  54. err := retry.Timed(100 /* times */, 100 /* ms */).On(func() error {
  55. err := ich.handler.Listen(ich.port)
  56. if err != nil {
  57. log.Error("Failed to start inbound detour on port ", ich.port, ": ", err)
  58. return err
  59. }
  60. return nil
  61. })
  62. if err != nil {
  63. return err
  64. }
  65. }
  66. return nil
  67. }