freedom.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. package freedom
  2. import (
  3. "context"
  4. "time"
  5. "runtime"
  6. "v2ray.com/core/app"
  7. "v2ray.com/core/app/dns"
  8. "v2ray.com/core/common"
  9. "v2ray.com/core/common/buf"
  10. "v2ray.com/core/common/dice"
  11. "v2ray.com/core/common/errors"
  12. "v2ray.com/core/app/log"
  13. "v2ray.com/core/common/net"
  14. "v2ray.com/core/common/retry"
  15. "v2ray.com/core/common/signal"
  16. "v2ray.com/core/proxy"
  17. "v2ray.com/core/transport/internet"
  18. "v2ray.com/core/transport/ray"
  19. )
  20. type Handler struct {
  21. domainStrategy Config_DomainStrategy
  22. timeout uint32
  23. dns dns.Server
  24. destOverride *DestinationOverride
  25. }
  26. func New(ctx context.Context, config *Config) (*Handler, error) {
  27. space := app.SpaceFromContext(ctx)
  28. if space == nil {
  29. return nil, errors.New("Freedom: No space in context.")
  30. }
  31. f := &Handler{
  32. domainStrategy: config.DomainStrategy,
  33. timeout: config.Timeout,
  34. destOverride: config.DestinationOverride,
  35. }
  36. space.OnInitialize(func() error {
  37. if config.DomainStrategy == Config_USE_IP {
  38. f.dns = dns.FromSpace(space)
  39. if f.dns == nil {
  40. return errors.New("Freedom: DNS server is not found in the space.")
  41. }
  42. }
  43. return nil
  44. })
  45. return f, nil
  46. }
  47. // Private: Visible for testing.
  48. func (v *Handler) ResolveIP(destination net.Destination) net.Destination {
  49. if !destination.Address.Family().IsDomain() {
  50. return destination
  51. }
  52. ips := v.dns.Get(destination.Address.Domain())
  53. if len(ips) == 0 {
  54. log.Info("Freedom: DNS returns nil answer. Keep domain as is.")
  55. return destination
  56. }
  57. ip := ips[dice.Roll(len(ips))]
  58. var newDest net.Destination
  59. if destination.Network == net.Network_TCP {
  60. newDest = net.TCPDestination(net.IPAddress(ip), destination.Port)
  61. } else {
  62. newDest = net.UDPDestination(net.IPAddress(ip), destination.Port)
  63. }
  64. log.Info("Freedom: Changing destination from ", destination, " to ", newDest)
  65. return newDest
  66. }
  67. func (v *Handler) Process(ctx context.Context, outboundRay ray.OutboundRay) error {
  68. destination := proxy.DestinationFromContext(ctx)
  69. if v.destOverride != nil {
  70. server := v.destOverride.Server
  71. destination = net.Destination{
  72. Network: destination.Network,
  73. Address: server.Address.AsAddress(),
  74. Port: net.Port(server.Port),
  75. }
  76. }
  77. log.Info("Freedom: Opening connection to ", destination)
  78. input := outboundRay.OutboundInput()
  79. output := outboundRay.OutboundOutput()
  80. var conn internet.Connection
  81. if v.domainStrategy == Config_USE_IP && destination.Address.Family().IsDomain() {
  82. destination = v.ResolveIP(destination)
  83. }
  84. dialer := proxy.DialerFromContext(ctx)
  85. err := retry.ExponentialBackoff(5, 100).On(func() error {
  86. rawConn, err := dialer.Dial(ctx, destination)
  87. if err != nil {
  88. return err
  89. }
  90. conn = rawConn
  91. return nil
  92. })
  93. if err != nil {
  94. log.Warning("Freedom: Failed to open connection to ", destination, ": ", err)
  95. return err
  96. }
  97. defer conn.Close()
  98. conn.SetReusable(false)
  99. ctx, cancel := context.WithCancel(ctx)
  100. timeout := time.Second * time.Duration(v.timeout)
  101. if timeout == 0 {
  102. timeout = time.Minute * 10
  103. }
  104. timer := signal.CancelAfterInactivity(ctx, cancel, timeout)
  105. requestDone := signal.ExecuteAsync(func() error {
  106. v2writer := buf.NewWriter(conn)
  107. if err := buf.PipeUntilEOF(timer, input, v2writer); err != nil {
  108. return err
  109. }
  110. return nil
  111. })
  112. responseDone := signal.ExecuteAsync(func() error {
  113. defer output.Close()
  114. v2reader := buf.NewReader(conn)
  115. if err := buf.PipeUntilEOF(timer, v2reader, output); err != nil {
  116. return err
  117. }
  118. return nil
  119. })
  120. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  121. log.Info("Freedom: Connection ending with ", err)
  122. input.CloseError()
  123. output.CloseError()
  124. return err
  125. }
  126. runtime.KeepAlive(timer)
  127. return nil
  128. }
  129. func init() {
  130. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  131. return New(ctx, config.(*Config))
  132. }))
  133. }