freedom.go 5.2 KB

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