freedom.go 4.3 KB

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