freedom.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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. DestinationOverride: simplifiedServer.DestinationOverride,
  35. ProtocolReplacement: simplifiedServer.ProtocolReplacement,
  36. }
  37. return common.CreateObject(ctx, fullConfig)
  38. }))
  39. }
  40. // Handler handles Freedom connections.
  41. type Handler struct {
  42. policyManager policy.Manager
  43. dns dns.Client
  44. config *Config
  45. }
  46. // Init initializes the Handler with necessary parameters.
  47. func (h *Handler) Init(config *Config, pm policy.Manager, d dns.Client) error {
  48. h.config = config
  49. h.policyManager = pm
  50. h.dns = d
  51. return nil
  52. }
  53. func (h *Handler) policy() policy.Session {
  54. p := h.policyManager.ForLevel(h.config.UserLevel)
  55. if h.config.Timeout > 0 && h.config.UserLevel == 0 {
  56. p.Timeouts.ConnectionIdle = time.Duration(h.config.Timeout) * time.Second
  57. }
  58. return p
  59. }
  60. func (h *Handler) resolveIP(ctx context.Context, domain string, localAddr net.Address) net.Address {
  61. ips, err := dns.LookupIPWithOption(h.dns, domain, dns.IPOption{
  62. IPv4Enable: h.config.DomainStrategy == Config_USE_IP || h.config.DomainStrategy == Config_USE_IP4 || (localAddr != nil && localAddr.Family().IsIPv4()),
  63. IPv6Enable: h.config.DomainStrategy == Config_USE_IP || h.config.DomainStrategy == Config_USE_IP6 || (localAddr != nil && localAddr.Family().IsIPv6()),
  64. FakeEnable: false,
  65. })
  66. if err != nil {
  67. newError("failed to get IP address for domain ", domain).Base(err).WriteToLog(session.ExportIDToError(ctx))
  68. }
  69. if len(ips) == 0 {
  70. return nil
  71. }
  72. return net.IPAddress(ips[dice.Roll(len(ips))])
  73. }
  74. func isValidAddress(addr *net.IPOrDomain) bool {
  75. if addr == nil {
  76. return false
  77. }
  78. a := addr.AsAddress()
  79. return a != net.AnyIP
  80. }
  81. // Process implements proxy.Outbound.
  82. func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
  83. outbound := session.OutboundFromContext(ctx)
  84. if outbound == nil || !outbound.Target.IsValid() {
  85. return newError("target not specified.")
  86. }
  87. destination := outbound.Target
  88. if h.config.DestinationOverride != nil {
  89. server := h.config.DestinationOverride.Server
  90. if isValidAddress(server.Address) {
  91. destination.Address = server.Address.AsAddress()
  92. }
  93. if server.Port != 0 {
  94. destination.Port = net.Port(server.Port)
  95. }
  96. }
  97. if h.config.ProtocolReplacement != ProtocolReplacement_IDENTITY {
  98. if h.config.ProtocolReplacement == ProtocolReplacement_FORCE_TCP {
  99. destination.Network = net.Network_TCP
  100. }
  101. if h.config.ProtocolReplacement == ProtocolReplacement_FORCE_UDP {
  102. destination.Network = net.Network_UDP
  103. }
  104. }
  105. if h.config.useIP() {
  106. outbound.Resolver = func(ctx context.Context, domain string) net.Address {
  107. return h.resolveIP(ctx, domain, dialer.Address())
  108. }
  109. }
  110. newError("opening connection to ", destination).WriteToLog(session.ExportIDToError(ctx))
  111. input := link.Reader
  112. output := link.Writer
  113. var conn internet.Connection
  114. err := retry.ExponentialBackoff(5, 100).On(func() error {
  115. rawConn, err := dialer.Dial(ctx, destination)
  116. if err != nil {
  117. return err
  118. }
  119. conn = rawConn
  120. return nil
  121. })
  122. if err != nil {
  123. return newError("failed to open connection to ", destination).Base(err)
  124. }
  125. defer conn.Close()
  126. plcy := h.policy()
  127. ctx, cancel := context.WithCancel(ctx)
  128. timer := signal.CancelAfterInactivity(ctx, cancel, plcy.Timeouts.ConnectionIdle)
  129. requestDone := func() error {
  130. defer timer.SetTimeout(plcy.Timeouts.DownlinkOnly)
  131. var writer buf.Writer
  132. if destination.Network == net.Network_TCP {
  133. writer = buf.NewWriter(conn)
  134. } else {
  135. writer = &buf.SequentialWriter{Writer: conn}
  136. }
  137. if err := buf.Copy(input, writer, buf.UpdateActivity(timer)); err != nil {
  138. return newError("failed to process request").Base(err)
  139. }
  140. return nil
  141. }
  142. responseDone := func() error {
  143. defer timer.SetTimeout(plcy.Timeouts.UplinkOnly)
  144. var reader buf.Reader
  145. if destination.Network == net.Network_TCP && h.config.ProtocolReplacement == ProtocolReplacement_IDENTITY {
  146. reader = buf.NewReader(conn)
  147. } else {
  148. reader = buf.NewPacketReader(conn)
  149. }
  150. if err := buf.Copy(reader, output, buf.UpdateActivity(timer)); err != nil {
  151. return newError("failed to process response").Base(err)
  152. }
  153. return nil
  154. }
  155. if err := task.Run(ctx, requestDone, task.OnSuccess(responseDone, task.Close(output))); err != nil {
  156. return newError("connection ends").Base(err)
  157. }
  158. return nil
  159. }