freedom.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. package freedom
  2. //go:generate errorgen
  3. import (
  4. "context"
  5. "time"
  6. "v2ray.com/core/features"
  7. "v2ray.com/core"
  8. "v2ray.com/core/common"
  9. "v2ray.com/core/common/buf"
  10. "v2ray.com/core/common/dice"
  11. "v2ray.com/core/common/net"
  12. "v2ray.com/core/common/retry"
  13. "v2ray.com/core/common/session"
  14. "v2ray.com/core/common/signal"
  15. "v2ray.com/core/common/task"
  16. "v2ray.com/core/common/vio"
  17. "v2ray.com/core/features/dns"
  18. "v2ray.com/core/features/policy"
  19. "v2ray.com/core/proxy"
  20. "v2ray.com/core/transport/internet"
  21. )
  22. // Handler handles Freedom connections.
  23. type Handler struct {
  24. policyManager policy.Manager
  25. dns dns.Client
  26. config Config
  27. }
  28. // New creates a new Freedom handler.
  29. func New(ctx context.Context, config *Config) (*Handler, error) {
  30. f := &Handler{
  31. config: *config,
  32. }
  33. v := core.MustFromContext(ctx)
  34. v.RequireFeatures([]interface{}{policy.ManagerType(), dns.ClientType()}, func(fs []features.Feature) {
  35. f.policyManager = fs[0].(policy.Manager)
  36. f.dns = fs[1].(dns.Client)
  37. })
  38. return f, nil
  39. }
  40. func (h *Handler) policy() policy.Session {
  41. p := h.policyManager.ForLevel(h.config.UserLevel)
  42. if h.config.Timeout > 0 && h.config.UserLevel == 0 {
  43. p.Timeouts.ConnectionIdle = time.Duration(h.config.Timeout) * time.Second
  44. }
  45. return p
  46. }
  47. func (h *Handler) resolveIP(ctx context.Context, domain string) net.Address {
  48. if resolver, ok := proxy.ResolvedIPsFromContext(ctx); ok {
  49. ips := resolver.Resolve()
  50. if len(ips) == 0 {
  51. return nil
  52. }
  53. return ips[dice.Roll(len(ips))]
  54. }
  55. ips, err := h.dns.LookupIP(domain)
  56. if err != nil {
  57. newError("failed to get IP address for domain ", domain).Base(err).WriteToLog(session.ExportIDToError(ctx))
  58. }
  59. if len(ips) == 0 {
  60. return nil
  61. }
  62. return net.IPAddress(ips[dice.Roll(len(ips))])
  63. }
  64. func isValidAddress(addr *net.IPOrDomain) bool {
  65. if addr == nil {
  66. return false
  67. }
  68. a := addr.AsAddress()
  69. return a != net.AnyIP
  70. }
  71. // Process implements proxy.Outbound.
  72. func (h *Handler) Process(ctx context.Context, link *vio.Link, dialer proxy.Dialer) error {
  73. outbound := session.OutboundFromContext(ctx)
  74. if outbound == nil || !outbound.Target.IsValid() {
  75. return newError("target not specified.")
  76. }
  77. destination := outbound.Target
  78. if h.config.DestinationOverride != nil {
  79. server := h.config.DestinationOverride.Server
  80. if isValidAddress(server.Address) {
  81. destination.Address = server.Address.AsAddress()
  82. }
  83. if server.Port != 0 {
  84. destination.Port = net.Port(server.Port)
  85. }
  86. }
  87. newError("opening connection to ", destination).WriteToLog(session.ExportIDToError(ctx))
  88. input := link.Reader
  89. output := link.Writer
  90. var conn internet.Connection
  91. err := retry.ExponentialBackoff(5, 100).On(func() error {
  92. dialDest := destination
  93. if h.config.DomainStrategy == Config_USE_IP && dialDest.Address.Family().IsDomain() {
  94. ip := h.resolveIP(ctx, dialDest.Address.Domain())
  95. if ip != nil {
  96. dialDest = net.Destination{
  97. Network: dialDest.Network,
  98. Address: ip,
  99. Port: dialDest.Port,
  100. }
  101. newError("dialing to to ", dialDest).WriteToLog(session.ExportIDToError(ctx))
  102. }
  103. }
  104. rawConn, err := dialer.Dial(ctx, dialDest)
  105. if err != nil {
  106. return err
  107. }
  108. conn = rawConn
  109. return nil
  110. })
  111. if err != nil {
  112. return newError("failed to open connection to ", destination).Base(err)
  113. }
  114. defer conn.Close() // nolint: errcheck
  115. plcy := h.policy()
  116. ctx, cancel := context.WithCancel(ctx)
  117. timer := signal.CancelAfterInactivity(ctx, cancel, plcy.Timeouts.ConnectionIdle)
  118. requestDone := func() error {
  119. defer timer.SetTimeout(plcy.Timeouts.DownlinkOnly)
  120. var writer buf.Writer
  121. if destination.Network == net.Network_TCP {
  122. writer = buf.NewWriter(conn)
  123. } else {
  124. writer = &buf.SequentialWriter{Writer: conn}
  125. }
  126. if err := buf.Copy(input, writer, buf.UpdateActivity(timer)); err != nil {
  127. return newError("failed to process request").Base(err)
  128. }
  129. return nil
  130. }
  131. responseDone := func() error {
  132. defer timer.SetTimeout(plcy.Timeouts.UplinkOnly)
  133. if err := buf.Copy(buf.NewReader(conn), output, buf.UpdateActivity(timer)); err != nil {
  134. return newError("failed to process response").Base(err)
  135. }
  136. return nil
  137. }
  138. if err := task.Run(task.WithContext(ctx), task.Parallel(requestDone, task.Single(responseDone, task.OnSuccess(task.Close(output)))))(); err != nil {
  139. return newError("connection ends").Base(err)
  140. }
  141. return nil
  142. }
  143. func init() {
  144. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  145. return New(ctx, config.(*Config))
  146. }))
  147. }