freedom.go 4.3 KB

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