freedom.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. package freedom
  2. //go:generate errorgen
  3. import (
  4. "context"
  5. "time"
  6. "v2ray.com/core"
  7. "v2ray.com/core/common"
  8. "v2ray.com/core/common/buf"
  9. "v2ray.com/core/common/dice"
  10. "v2ray.com/core/common/net"
  11. "v2ray.com/core/common/retry"
  12. "v2ray.com/core/common/session"
  13. "v2ray.com/core/common/signal"
  14. "v2ray.com/core/common/task"
  15. "v2ray.com/core/common/vio"
  16. "v2ray.com/core/proxy"
  17. "v2ray.com/core/transport/internet"
  18. )
  19. // Handler handles Freedom connections.
  20. type Handler struct {
  21. policyManager core.PolicyManager
  22. dns core.DNSClient
  23. config Config
  24. }
  25. // New creates a new Freedom handler.
  26. func New(ctx context.Context, config *Config) (*Handler, error) {
  27. v := core.MustFromContext(ctx)
  28. f := &Handler{
  29. config: *config,
  30. policyManager: v.PolicyManager(),
  31. dns: v.DNSClient(),
  32. }
  33. return f, nil
  34. }
  35. func (h *Handler) policy() core.Policy {
  36. p := h.policyManager.ForLevel(h.config.UserLevel)
  37. if h.config.Timeout > 0 && h.config.UserLevel == 0 {
  38. p.Timeouts.ConnectionIdle = time.Duration(h.config.Timeout) * time.Second
  39. }
  40. return p
  41. }
  42. func (h *Handler) resolveIP(ctx context.Context, domain string) net.Address {
  43. if resolver, ok := proxy.ResolvedIPsFromContext(ctx); ok {
  44. ips := resolver.Resolve()
  45. if len(ips) == 0 {
  46. return nil
  47. }
  48. return ips[dice.Roll(len(ips))]
  49. }
  50. ips, err := h.dns.LookupIP(domain)
  51. if err != nil {
  52. newError("failed to get IP address for domain ", domain).Base(err).WriteToLog(session.ExportIDToError(ctx))
  53. }
  54. if len(ips) == 0 {
  55. return nil
  56. }
  57. return net.IPAddress(ips[dice.Roll(len(ips))])
  58. }
  59. func isValidAddress(addr *net.IPOrDomain) bool {
  60. if addr == nil {
  61. return false
  62. }
  63. a := addr.AsAddress()
  64. return a != net.AnyIP
  65. }
  66. // Process implements proxy.Outbound.
  67. func (h *Handler) Process(ctx context.Context, link *vio.Link, dialer proxy.Dialer) error {
  68. outbound := session.OutboundFromContext(ctx)
  69. if outbound == nil || !outbound.Target.IsValid() {
  70. return newError("target not specified.")
  71. }
  72. destination := outbound.Target
  73. if h.config.DestinationOverride != nil {
  74. server := h.config.DestinationOverride.Server
  75. if isValidAddress(server.Address) {
  76. destination.Address = server.Address.AsAddress()
  77. }
  78. if server.Port != 0 {
  79. destination.Port = net.Port(server.Port)
  80. }
  81. }
  82. newError("opening connection to ", destination).WriteToLog(session.ExportIDToError(ctx))
  83. input := link.Reader
  84. output := link.Writer
  85. var conn internet.Connection
  86. err := retry.ExponentialBackoff(5, 100).On(func() error {
  87. dialDest := destination
  88. if h.config.DomainStrategy == Config_USE_IP && dialDest.Address.Family().IsDomain() {
  89. ip := h.resolveIP(ctx, dialDest.Address.Domain())
  90. if ip != nil {
  91. dialDest = net.Destination{
  92. Network: dialDest.Network,
  93. Address: ip,
  94. Port: dialDest.Port,
  95. }
  96. newError("dialing to to ", dialDest).WriteToLog(session.ExportIDToError(ctx))
  97. }
  98. }
  99. rawConn, err := dialer.Dial(ctx, dialDest)
  100. if err != nil {
  101. return err
  102. }
  103. conn = rawConn
  104. return nil
  105. })
  106. if err != nil {
  107. return newError("failed to open connection to ", destination).Base(err)
  108. }
  109. defer conn.Close() // nolint: errcheck
  110. plcy := h.policy()
  111. ctx, cancel := context.WithCancel(ctx)
  112. timer := signal.CancelAfterInactivity(ctx, cancel, plcy.Timeouts.ConnectionIdle)
  113. requestDone := func() error {
  114. defer timer.SetTimeout(plcy.Timeouts.DownlinkOnly)
  115. var writer buf.Writer
  116. if destination.Network == net.Network_TCP {
  117. writer = buf.NewWriter(conn)
  118. } else {
  119. writer = &buf.SequentialWriter{Writer: conn}
  120. }
  121. if err := buf.Copy(input, writer, buf.UpdateActivity(timer)); err != nil {
  122. return newError("failed to process request").Base(err)
  123. }
  124. return nil
  125. }
  126. responseDone := func() error {
  127. defer timer.SetTimeout(plcy.Timeouts.UplinkOnly)
  128. if err := buf.Copy(buf.NewReader(conn), output, buf.UpdateActivity(timer)); err != nil {
  129. return newError("failed to process response").Base(err)
  130. }
  131. return nil
  132. }
  133. if err := task.Run(task.WithContext(ctx), task.Parallel(requestDone, task.Single(responseDone, task.OnSuccess(task.Close(output)))))(); err != nil {
  134. return newError("connection ends").Base(err)
  135. }
  136. return nil
  137. }
  138. func init() {
  139. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  140. return New(ctx, config.(*Config))
  141. }))
  142. }