freedom.go 5.2 KB

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