freedom.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. // +build !confonly
  2. package freedom
  3. //go:generate go run v2ray.com/core/common/errors/errorgen
  4. import (
  5. "context"
  6. "time"
  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/features/dns"
  17. "v2ray.com/core/features/policy"
  18. "v2ray.com/core/transport"
  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, localAddr net.Address) net.Address {
  53. var lookupFunc func(string) ([]net.IP, error) = h.dns.LookupIP
  54. if h.config.DomainStrategy == Config_USE_IP4 || (localAddr != nil && localAddr.Family().IsIPv4()) {
  55. if lookupIPv4, ok := h.dns.(dns.IPv4Lookup); ok {
  56. lookupFunc = lookupIPv4.LookupIPv4
  57. }
  58. } else if h.config.DomainStrategy == Config_USE_IP6 || (localAddr != nil && localAddr.Family().IsIPv6()) {
  59. if lookupIPv6, ok := h.dns.(dns.IPv6Lookup); ok {
  60. lookupFunc = lookupIPv6.LookupIPv6
  61. }
  62. }
  63. ips, err := lookupFunc(domain)
  64. if err != nil {
  65. newError("failed to get IP address for domain ", domain).Base(err).WriteToLog(session.ExportIDToError(ctx))
  66. }
  67. if len(ips) == 0 {
  68. return nil
  69. }
  70. return net.IPAddress(ips[dice.Roll(len(ips))])
  71. }
  72. func isValidAddress(addr *net.IPOrDomain) bool {
  73. if addr == nil {
  74. return false
  75. }
  76. a := addr.AsAddress()
  77. return a != net.AnyIP
  78. }
  79. // Process implements proxy.Outbound.
  80. func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
  81. outbound := session.OutboundFromContext(ctx)
  82. if outbound == nil || !outbound.Target.IsValid() {
  83. return newError("target not specified.")
  84. }
  85. destination := outbound.Target
  86. if h.config.DestinationOverride != nil {
  87. server := h.config.DestinationOverride.Server
  88. if isValidAddress(server.Address) {
  89. destination.Address = server.Address.AsAddress()
  90. }
  91. if server.Port != 0 {
  92. destination.Port = net.Port(server.Port)
  93. }
  94. }
  95. newError("opening connection to ", destination).WriteToLog(session.ExportIDToError(ctx))
  96. input := link.Reader
  97. output := link.Writer
  98. var conn internet.Connection
  99. err := retry.ExponentialBackoff(5, 100).On(func() error {
  100. dialDest := destination
  101. if h.config.useIP() && dialDest.Address.Family().IsDomain() {
  102. ip := h.resolveIP(ctx, dialDest.Address.Domain(), dialer.Address())
  103. if ip != nil {
  104. dialDest = net.Destination{
  105. Network: dialDest.Network,
  106. Address: ip,
  107. Port: dialDest.Port,
  108. }
  109. newError("dialing to to ", dialDest).WriteToLog(session.ExportIDToError(ctx))
  110. }
  111. }
  112. rawConn, err := dialer.Dial(ctx, dialDest)
  113. if err != nil {
  114. return err
  115. }
  116. conn = rawConn
  117. return nil
  118. })
  119. if err != nil {
  120. return newError("failed to open connection to ", destination).Base(err)
  121. }
  122. defer conn.Close()
  123. plcy := h.policy()
  124. ctx, cancel := context.WithCancel(ctx)
  125. timer := signal.CancelAfterInactivity(ctx, cancel, plcy.Timeouts.ConnectionIdle)
  126. requestDone := func() error {
  127. defer timer.SetTimeout(plcy.Timeouts.DownlinkOnly)
  128. var writer buf.Writer
  129. if destination.Network == net.Network_TCP {
  130. writer = buf.NewWriter(conn)
  131. } else {
  132. writer = &buf.SequentialWriter{Writer: conn}
  133. }
  134. if err := buf.Copy(input, writer, buf.UpdateActivity(timer)); err != nil {
  135. return newError("failed to process request").Base(err)
  136. }
  137. return nil
  138. }
  139. responseDone := func() error {
  140. defer timer.SetTimeout(plcy.Timeouts.UplinkOnly)
  141. var reader buf.Reader
  142. if destination.Network == net.Network_TCP {
  143. reader = buf.NewReader(conn)
  144. } else {
  145. reader = buf.NewPacketReader(conn)
  146. }
  147. if err := buf.Copy(reader, output, buf.UpdateActivity(timer)); err != nil {
  148. return newError("failed to process response").Base(err)
  149. }
  150. return nil
  151. }
  152. if err := task.Run(ctx, requestDone, task.OnSuccess(responseDone, task.Close(output))); err != nil {
  153. return newError("connection ends").Base(err)
  154. }
  155. return nil
  156. }