freedom.go 3.8 KB

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