freedom.go 4.0 KB

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