freedom.go 4.6 KB

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