freedom.go 3.9 KB

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