freedom.go 5.0 KB

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