freedom.go 4.3 KB

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