freedom.go 4.3 KB

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