freedom.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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. "time"
  6. "v2ray.com/core/app"
  7. "v2ray.com/core/app/dns"
  8. "v2ray.com/core/app/log"
  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. }
  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.OnInitialize(func() 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. 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 := h.dns.Get(domain)
  57. if len(ips) == 0 {
  58. return nil
  59. }
  60. return net.IPAddress(ips[dice.Roll(len(ips))])
  61. }
  62. // Process implements proxy.Outbound.
  63. func (h *Handler) Process(ctx context.Context, outboundRay ray.OutboundRay, dialer proxy.Dialer) error {
  64. destination, _ := proxy.TargetFromContext(ctx)
  65. if h.destOverride != nil {
  66. server := h.destOverride.Server
  67. destination = net.Destination{
  68. Network: destination.Network,
  69. Address: server.Address.AsAddress(),
  70. Port: net.Port(server.Port),
  71. }
  72. }
  73. log.Trace(newError("opening connection to ", destination))
  74. input := outboundRay.OutboundInput()
  75. output := outboundRay.OutboundOutput()
  76. if h.domainStrategy == Config_USE_IP && destination.Address.Family().IsDomain() {
  77. ip := h.resolveIP(ctx, destination.Address.Domain())
  78. if ip != nil {
  79. destination = net.Destination{
  80. Network: destination.Network,
  81. Address: ip,
  82. Port: destination.Port,
  83. }
  84. log.Trace(newError("changing destination to ", destination))
  85. }
  86. }
  87. var conn internet.Connection
  88. err := retry.ExponentialBackoff(5, 100).On(func() error {
  89. rawConn, err := dialer.Dial(ctx, destination)
  90. if err != nil {
  91. return err
  92. }
  93. conn = rawConn
  94. return nil
  95. })
  96. if err != nil {
  97. return newError("failed to open connection to ", destination).Base(err)
  98. }
  99. defer conn.Close()
  100. timeout := time.Second * time.Duration(h.timeout)
  101. if timeout == 0 {
  102. timeout = time.Minute * 5
  103. }
  104. ctx, cancel := context.WithCancel(ctx)
  105. timer := signal.CancelAfterInactivity(ctx, cancel, timeout)
  106. requestDone := signal.ExecuteAsync(func() error {
  107. var writer buf.Writer
  108. if destination.Network == net.Network_TCP {
  109. writer = buf.NewWriter(conn)
  110. } else {
  111. writer = buf.NewSequentialWriter(conn)
  112. }
  113. if err := buf.Copy(input, writer, buf.UpdateActivity(timer)); err != nil {
  114. return newError("failed to process request").Base(err)
  115. }
  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. return nil
  125. })
  126. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  127. input.CloseError()
  128. output.CloseError()
  129. return newError("connection ends").Base(err)
  130. }
  131. return nil
  132. }
  133. func init() {
  134. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  135. return New(ctx, config.(*Config))
  136. }))
  137. }