inbound_detour_always.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package point
  2. import (
  3. "math/rand"
  4. "github.com/v2ray/v2ray-core/app"
  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. idx := rand.Intn(len(this.ich))
  44. ich := this.ich[idx]
  45. return ich.handler, this.config.Allocation.Refresh
  46. }
  47. func (this *InboundDetourHandlerAlways) Close() {
  48. for _, ich := range this.ich {
  49. ich.handler.Close()
  50. }
  51. }
  52. // Starts the inbound connection handler.
  53. func (this *InboundDetourHandlerAlways) Start() error {
  54. for _, ich := range this.ich {
  55. err := retry.Timed(100 /* times */, 100 /* ms */).On(func() error {
  56. err := ich.handler.Listen(ich.port)
  57. if err != nil {
  58. log.Error("Failed to start inbound detour on port ", ich.port, ": ", err)
  59. return err
  60. }
  61. return nil
  62. })
  63. if err != nil {
  64. return err
  65. }
  66. }
  67. return nil
  68. }