freedom.go 4.3 KB

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