freedom.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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. "runtime"
  6. "time"
  7. "v2ray.com/core/app"
  8. "v2ray.com/core/app/dns"
  9. "v2ray.com/core/app/log"
  10. "v2ray.com/core/common"
  11. "v2ray.com/core/common/buf"
  12. "v2ray.com/core/common/dice"
  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. keepAliveOnResponseClose bool
  26. }
  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. keepAliveOnResponseClose: config.KeepAliveOnResponseClose,
  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. return nil
  46. })
  47. return f, nil
  48. }
  49. func (h *Handler) ResolveIP(destination net.Destination) net.Destination {
  50. if !destination.Address.Family().IsDomain() {
  51. return destination
  52. }
  53. ips := h.dns.Get(destination.Address.Domain())
  54. if len(ips) == 0 {
  55. log.Trace(newError("DNS returns nil answer. Keep domain as is."))
  56. return destination
  57. }
  58. ip := ips[dice.Roll(len(ips))]
  59. newDest := net.Destination{
  60. Network: destination.Network,
  61. Address: net.IPAddress(ip),
  62. Port: destination.Port,
  63. }
  64. log.Trace(newError("changing destination from ", destination, " to ", newDest))
  65. return newDest
  66. }
  67. func (h *Handler) Process(ctx context.Context, outboundRay ray.OutboundRay, dialer proxy.Dialer) error {
  68. destination, _ := proxy.TargetFromContext(ctx)
  69. if h.destOverride != nil {
  70. server := h.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.Trace(newError("opening connection to ", destination))
  78. input := outboundRay.OutboundInput()
  79. output := outboundRay.OutboundOutput()
  80. var conn internet.Connection
  81. if h.domainStrategy == Config_USE_IP && destination.Address.Family().IsDomain() {
  82. destination = h.ResolveIP(destination)
  83. }
  84. err := retry.ExponentialBackoff(5, 100).On(func() error {
  85. rawConn, err := dialer.Dial(ctx, destination)
  86. if err != nil {
  87. return err
  88. }
  89. conn = rawConn
  90. return nil
  91. })
  92. if err != nil {
  93. return newError("failed to open connection to ", destination).Base(err)
  94. }
  95. defer conn.Close()
  96. timeout := time.Second * time.Duration(h.timeout)
  97. if timeout == 0 {
  98. timeout = time.Minute * 5
  99. }
  100. ctx, timer := signal.CancelAfterInactivity(ctx, timeout)
  101. requestDone := signal.ExecuteAsync(func() error {
  102. var writer buf.Writer
  103. if destination.Network == net.Network_TCP {
  104. writer = buf.NewWriter(conn)
  105. } else {
  106. writer = buf.NewSequentialWriter(conn)
  107. }
  108. if err := buf.Copy(input, writer, buf.UpdateActivity(timer)); err != nil {
  109. return newError("failed to process request").Base(err)
  110. }
  111. return nil
  112. })
  113. responseDone := signal.ExecuteAsync(func() error {
  114. defer func() {
  115. if h.keepAliveOnResponseClose {
  116. output.Close()
  117. } else {
  118. output.CloseError()
  119. }
  120. }()
  121. v2reader := buf.NewReader(conn)
  122. if err := buf.Copy(v2reader, output, buf.UpdateActivity(timer)); err != nil {
  123. return newError("failed to process response").Base(err)
  124. }
  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. runtime.KeepAlive(timer)
  133. return nil
  134. }
  135. func init() {
  136. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  137. return New(ctx, config.(*Config))
  138. }))
  139. }