freedom.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. package freedom
  2. //go:generate go run $GOPATH/src/v2ray.com/core/common/errors/errorgen/main.go -pkg freedom -path Proxy,Freedom
  3. import (
  4. "context"
  5. "v2ray.com/core/app"
  6. "v2ray.com/core/app/policy"
  7. "v2ray.com/core/common"
  8. "v2ray.com/core/common/buf"
  9. "v2ray.com/core/common/dice"
  10. "v2ray.com/core/common/net"
  11. "v2ray.com/core/common/retry"
  12. "v2ray.com/core/common/signal"
  13. "v2ray.com/core/proxy"
  14. "v2ray.com/core/transport/internet"
  15. "v2ray.com/core/transport/ray"
  16. )
  17. // Handler handles Freedom connections.
  18. type Handler struct {
  19. domainStrategy Config_DomainStrategy
  20. timeout uint32
  21. destOverride *DestinationOverride
  22. policy policy.Policy
  23. }
  24. // New creates a new Freedom handler.
  25. func New(ctx context.Context, config *Config) (*Handler, error) {
  26. space := app.SpaceFromContext(ctx)
  27. if space == nil {
  28. return nil, newError("no space in context")
  29. }
  30. f := &Handler{
  31. domainStrategy: config.DomainStrategy,
  32. timeout: config.Timeout,
  33. destOverride: config.DestinationOverride,
  34. }
  35. space.On(app.SpaceInitializing, func(interface{}) error {
  36. pm := policy.FromSpace(space)
  37. if pm == nil {
  38. return newError("Policy not found in space.")
  39. }
  40. f.policy = pm.GetPolicy(config.UserLevel)
  41. if config.Timeout > 0 && config.UserLevel == 0 {
  42. f.policy.Timeout.ConnectionIdle.Value = config.Timeout
  43. }
  44. return nil
  45. })
  46. return f, nil
  47. }
  48. func (h *Handler) resolveIP(ctx context.Context, domain string) net.Address {
  49. if resolver, ok := proxy.ResolvedIPsFromContext(ctx); ok {
  50. ips := resolver.Resolve()
  51. if len(ips) == 0 {
  52. return nil
  53. }
  54. return ips[dice.Roll(len(ips))]
  55. }
  56. ips, err := net.LookupIP(domain)
  57. if err != nil {
  58. newError("failed to get IP address for domain ", domain).Base(err).WriteToLog()
  59. }
  60. if len(ips) == 0 {
  61. return nil
  62. }
  63. return net.IPAddress(ips[dice.Roll(len(ips))])
  64. }
  65. // Process implements proxy.Outbound.
  66. func (h *Handler) Process(ctx context.Context, outboundRay ray.OutboundRay, dialer proxy.Dialer) error {
  67. destination, _ := proxy.TargetFromContext(ctx)
  68. if h.destOverride != nil {
  69. server := h.destOverride.Server
  70. destination = net.Destination{
  71. Network: destination.Network,
  72. Address: server.Address.AsAddress(),
  73. Port: net.Port(server.Port),
  74. }
  75. }
  76. newError("opening connection to ", destination).WriteToLog()
  77. input := outboundRay.OutboundInput()
  78. output := outboundRay.OutboundOutput()
  79. if h.domainStrategy == Config_USE_IP && destination.Address.Family().IsDomain() {
  80. ip := h.resolveIP(ctx, destination.Address.Domain())
  81. if ip != nil {
  82. destination = net.Destination{
  83. Network: destination.Network,
  84. Address: ip,
  85. Port: destination.Port,
  86. }
  87. newError("changing destination to ", destination).WriteToLog()
  88. }
  89. }
  90. var conn internet.Connection
  91. err := retry.ExponentialBackoff(5, 100).On(func() error {
  92. rawConn, err := dialer.Dial(ctx, destination)
  93. if err != nil {
  94. return err
  95. }
  96. conn = rawConn
  97. return nil
  98. })
  99. if err != nil {
  100. return newError("failed to open connection to ", destination).Base(err)
  101. }
  102. defer conn.Close()
  103. ctx, cancel := context.WithCancel(ctx)
  104. timer := signal.CancelAfterInactivity(ctx, cancel, h.policy.Timeout.ConnectionIdle.Duration())
  105. requestDone := signal.ExecuteAsync(func() error {
  106. var writer buf.Writer
  107. if destination.Network == net.Network_TCP {
  108. writer = buf.NewWriter(conn)
  109. } else {
  110. writer = buf.NewSequentialWriter(conn)
  111. }
  112. if err := buf.Copy(input, writer, buf.UpdateActivity(timer)); err != nil {
  113. return newError("failed to process request").Base(err)
  114. }
  115. timer.SetTimeout(h.policy.Timeout.DownlinkOnly.Duration())
  116. return nil
  117. })
  118. responseDone := signal.ExecuteAsync(func() error {
  119. defer output.Close()
  120. v2reader := buf.NewReader(conn)
  121. if err := buf.Copy(v2reader, output, buf.UpdateActivity(timer)); err != nil {
  122. return newError("failed to process response").Base(err)
  123. }
  124. timer.SetTimeout(h.policy.Timeout.UplinkOnly.Duration())
  125. return nil
  126. })
  127. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  128. input.CloseError()
  129. output.CloseError()
  130. return newError("connection ends").Base(err)
  131. }
  132. return nil
  133. }
  134. func init() {
  135. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  136. return New(ctx, config.(*Config))
  137. }))
  138. }