freedom.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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/session"
  13. "v2ray.com/core/common/signal"
  14. "v2ray.com/core/common/task"
  15. "v2ray.com/core/proxy"
  16. "v2ray.com/core/transport/internet"
  17. )
  18. // Handler handles Freedom connections.
  19. type Handler struct {
  20. policyManager core.PolicyManager
  21. dns core.DNSClient
  22. config Config
  23. }
  24. // New creates a new Freedom handler.
  25. func New(ctx context.Context, config *Config) (*Handler, error) {
  26. v := core.MustFromContext(ctx)
  27. f := &Handler{
  28. config: *config,
  29. policyManager: v.PolicyManager(),
  30. dns: v.DNSClient(),
  31. }
  32. return f, nil
  33. }
  34. func (h *Handler) policy() core.Policy {
  35. p := h.policyManager.ForLevel(h.config.UserLevel)
  36. if h.config.Timeout > 0 && h.config.UserLevel == 0 {
  37. p.Timeouts.ConnectionIdle = time.Duration(h.config.Timeout) * time.Second
  38. }
  39. return p
  40. }
  41. func (h *Handler) resolveIP(ctx context.Context, domain string) net.Address {
  42. if resolver, ok := proxy.ResolvedIPsFromContext(ctx); ok {
  43. ips := resolver.Resolve()
  44. if len(ips) == 0 {
  45. return nil
  46. }
  47. return ips[dice.Roll(len(ips))]
  48. }
  49. ips, err := h.dns.LookupIP(domain)
  50. if err != nil {
  51. newError("failed to get IP address for domain ", domain).Base(err).WriteToLog(session.ExportIDToError(ctx))
  52. }
  53. if len(ips) == 0 {
  54. return nil
  55. }
  56. return net.IPAddress(ips[dice.Roll(len(ips))])
  57. }
  58. // Process implements proxy.Outbound.
  59. func (h *Handler) Process(ctx context.Context, link *core.Link, dialer proxy.Dialer) error {
  60. destination, _ := proxy.TargetFromContext(ctx)
  61. if h.config.DestinationOverride != nil {
  62. server := h.config.DestinationOverride.Server
  63. if server.Address != nil {
  64. destination.Address = server.Address.AsAddress()
  65. }
  66. if server.Port != 0 {
  67. destination.Port = net.Port(server.Port)
  68. }
  69. }
  70. newError("opening connection to ", destination).WriteToLog(session.ExportIDToError(ctx))
  71. input := link.Reader
  72. output := link.Writer
  73. var conn internet.Connection
  74. err := retry.ExponentialBackoff(5, 100).On(func() error {
  75. dialDest := destination
  76. if h.config.DomainStrategy == Config_USE_IP && dialDest.Address.Family().IsDomain() {
  77. ip := h.resolveIP(ctx, dialDest.Address.Domain())
  78. if ip != nil {
  79. dialDest = net.Destination{
  80. Network: dialDest.Network,
  81. Address: ip,
  82. Port: dialDest.Port,
  83. }
  84. newError("dialing to to ", dialDest).WriteToLog(session.ExportIDToError(ctx))
  85. }
  86. }
  87. rawConn, err := dialer.Dial(ctx, dialDest)
  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() // nolint: errcheck
  98. ctx, cancel := context.WithCancel(ctx)
  99. timer := signal.CancelAfterInactivity(ctx, cancel, h.policy().Timeouts.ConnectionIdle)
  100. requestDone := func() error {
  101. defer timer.SetTimeout(h.policy().Timeouts.DownlinkOnly)
  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 := func() error {
  114. defer timer.SetTimeout(h.policy().Timeouts.UplinkOnly)
  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. return nil
  120. }
  121. if err := task.Run(task.WithContext(ctx), task.Parallel(requestDone, task.Single(responseDone, task.OnSuccess(task.Close(output)))))(); err != nil {
  122. return newError("connection ends").Base(err)
  123. }
  124. return nil
  125. }
  126. func init() {
  127. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  128. return New(ctx, config.(*Config))
  129. }))
  130. }