freedom.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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. }
  26. func New(ctx context.Context, config *Config) (*Handler, error) {
  27. space := app.SpaceFromContext(ctx)
  28. if space == nil {
  29. return nil, newError("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 newError("DNS server is not found in the space")
  41. }
  42. }
  43. return nil
  44. })
  45. return f, nil
  46. }
  47. func (v *Handler) ResolveIP(destination net.Destination) net.Destination {
  48. if !destination.Address.Family().IsDomain() {
  49. return destination
  50. }
  51. ips := v.dns.Get(destination.Address.Domain())
  52. if len(ips) == 0 {
  53. log.Trace(newError("DNS returns nil answer. Keep domain as is."))
  54. return destination
  55. }
  56. ip := ips[dice.Roll(len(ips))]
  57. newDest := net.Destination{
  58. Network: destination.Network,
  59. Address: net.IPAddress(ip),
  60. Port: destination.Port,
  61. }
  62. log.Trace(newError("changing destination from ", destination, " to ", newDest))
  63. return newDest
  64. }
  65. func (v *Handler) Process(ctx context.Context, outboundRay ray.OutboundRay, dialer proxy.Dialer) error {
  66. destination, _ := proxy.TargetFromContext(ctx)
  67. if v.destOverride != nil {
  68. server := v.destOverride.Server
  69. destination = net.Destination{
  70. Network: destination.Network,
  71. Address: server.Address.AsAddress(),
  72. Port: net.Port(server.Port),
  73. }
  74. }
  75. log.Trace(newError("opening connection to ", destination))
  76. input := outboundRay.OutboundInput()
  77. output := outboundRay.OutboundOutput()
  78. var conn internet.Connection
  79. if v.domainStrategy == Config_USE_IP && destination.Address.Family().IsDomain() {
  80. destination = v.ResolveIP(destination)
  81. }
  82. err := retry.ExponentialBackoff(5, 100).On(func() error {
  83. rawConn, err := dialer.Dial(ctx, destination)
  84. if err != nil {
  85. return err
  86. }
  87. conn = rawConn
  88. return nil
  89. })
  90. if err != nil {
  91. return newError("failed to open connection to ", destination).Base(err)
  92. }
  93. defer conn.Close()
  94. timeout := time.Second * time.Duration(v.timeout)
  95. if timeout == 0 {
  96. timeout = time.Minute * 5
  97. }
  98. ctx, timer := signal.CancelAfterInactivity(ctx, timeout)
  99. requestDone := signal.ExecuteAsync(func() error {
  100. var writer buf.Writer
  101. if destination.Network == net.Network_TCP {
  102. writer = buf.NewWriter(conn)
  103. } else {
  104. writer = buf.NewSequentialWriter(conn)
  105. }
  106. if err := buf.Copy(input, writer, buf.UpdateActivity(timer)); err != nil {
  107. return newError("failed to process request").Base(err)
  108. }
  109. return nil
  110. })
  111. responseDone := signal.ExecuteAsync(func() error {
  112. defer output.Close()
  113. v2reader := buf.NewReader(conn)
  114. if err := buf.Copy(v2reader, output, buf.UpdateActivity(timer)); err != nil {
  115. return newError("failed to process response").Base(err)
  116. }
  117. return nil
  118. })
  119. if err := signal.ErrorOrFinish2(ctx, requestDone, responseDone); err != nil {
  120. input.CloseError()
  121. output.CloseError()
  122. return newError("connection ends").Base(err)
  123. }
  124. runtime.KeepAlive(timer)
  125. return nil
  126. }
  127. func init() {
  128. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  129. return New(ctx, config.(*Config))
  130. }))
  131. }