freedom.go 5.2 KB

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