freedom.go 4.4 KB

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