inbound_detour_always.go 1.8 KB

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