inbound_detour_always.go 2.1 KB

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