freedom.go 5.4 KB

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