freedom.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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. destination, _ := proxy.TargetFromContext(ctx)
  68. if h.config.DestinationOverride != nil {
  69. server := h.config.DestinationOverride.Server
  70. if isValidAddress(server.Address) {
  71. destination.Address = server.Address.AsAddress()
  72. }
  73. if server.Port != 0 {
  74. destination.Port = net.Port(server.Port)
  75. }
  76. }
  77. newError("opening connection to ", destination).WriteToLog(session.ExportIDToError(ctx))
  78. input := link.Reader
  79. output := link.Writer
  80. var conn internet.Connection
  81. err := retry.ExponentialBackoff(5, 100).On(func() error {
  82. dialDest := destination
  83. if h.config.DomainStrategy == Config_USE_IP && dialDest.Address.Family().IsDomain() {
  84. ip := h.resolveIP(ctx, dialDest.Address.Domain())
  85. if ip != nil {
  86. dialDest = net.Destination{
  87. Network: dialDest.Network,
  88. Address: ip,
  89. Port: dialDest.Port,
  90. }
  91. newError("dialing to to ", dialDest).WriteToLog(session.ExportIDToError(ctx))
  92. }
  93. }
  94. rawConn, err := dialer.Dial(ctx, dialDest)
  95. if err != nil {
  96. return err
  97. }
  98. conn = rawConn
  99. return nil
  100. })
  101. if err != nil {
  102. return newError("failed to open connection to ", destination).Base(err)
  103. }
  104. defer conn.Close() // nolint: errcheck
  105. plcy := h.policy()
  106. ctx, cancel := context.WithCancel(ctx)
  107. timer := signal.CancelAfterInactivity(ctx, cancel, plcy.Timeouts.ConnectionIdle)
  108. requestDone := func() error {
  109. defer timer.SetTimeout(plcy.Timeouts.DownlinkOnly)
  110. var writer buf.Writer
  111. if destination.Network == net.Network_TCP {
  112. writer = buf.NewWriter(conn)
  113. } else {
  114. writer = &buf.SequentialWriter{Writer: conn}
  115. }
  116. if err := buf.Copy(input, writer, buf.UpdateActivity(timer)); err != nil {
  117. return newError("failed to process request").Base(err)
  118. }
  119. return nil
  120. }
  121. responseDone := func() error {
  122. defer timer.SetTimeout(plcy.Timeouts.UplinkOnly)
  123. if err := buf.Copy(buf.NewReader(conn), output, buf.UpdateActivity(timer)); err != nil {
  124. return newError("failed to process response").Base(err)
  125. }
  126. return nil
  127. }
  128. if err := task.Run(task.WithContext(ctx), task.Parallel(requestDone, task.Single(responseDone, task.OnSuccess(task.Close(output)))))(); err != nil {
  129. return newError("connection ends").Base(err)
  130. }
  131. return nil
  132. }
  133. func init() {
  134. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  135. return New(ctx, config.(*Config))
  136. }))
  137. }