freedom.go 5.1 KB

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