freedom.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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. destination = net.Destination{
  64. Network: destination.Network,
  65. Address: server.Address.AsAddress(),
  66. Port: net.Port(server.Port),
  67. }
  68. }
  69. newError("opening connection to ", destination).WriteToLog(session.ExportIDToError(ctx))
  70. input := link.Reader
  71. output := link.Writer
  72. if h.config.DomainStrategy == Config_USE_IP && destination.Address.Family().IsDomain() {
  73. ip := h.resolveIP(ctx, destination.Address.Domain())
  74. if ip != nil {
  75. destination = net.Destination{
  76. Network: destination.Network,
  77. Address: ip,
  78. Port: destination.Port,
  79. }
  80. newError("changing destination to ", destination).WriteToLog(session.ExportIDToError(ctx))
  81. }
  82. }
  83. var conn internet.Connection
  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. ctx, cancel := context.WithCancel(ctx)
  97. timer := signal.CancelAfterInactivity(ctx, cancel, h.policy().Timeouts.ConnectionIdle)
  98. requestDone := func() error {
  99. defer timer.SetTimeout(h.policy().Timeouts.DownlinkOnly)
  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 := func() error {
  112. defer timer.SetTimeout(h.policy().Timeouts.UplinkOnly)
  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 := task.Run(task.WithContext(ctx), task.Parallel(requestDone, task.Single(responseDone, task.OnSuccess(task.Close(output)))))(); err != nil {
  120. return newError("connection ends").Base(err)
  121. }
  122. return nil
  123. }
  124. func init() {
  125. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  126. return New(ctx, config.(*Config))
  127. }))
  128. }