freedom.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. package freedom
  2. //go:generate go run github.com/xtls/xray-core/common/errors/errorgen
  3. import (
  4. "context"
  5. "time"
  6. "github.com/xtls/xray-core/common"
  7. "github.com/xtls/xray-core/common/buf"
  8. "github.com/xtls/xray-core/common/dice"
  9. "github.com/xtls/xray-core/common/net"
  10. "github.com/xtls/xray-core/common/retry"
  11. "github.com/xtls/xray-core/common/session"
  12. "github.com/xtls/xray-core/common/signal"
  13. "github.com/xtls/xray-core/common/task"
  14. "github.com/xtls/xray-core/core"
  15. "github.com/xtls/xray-core/features/dns"
  16. "github.com/xtls/xray-core/features/policy"
  17. "github.com/xtls/xray-core/features/stats"
  18. "github.com/xtls/xray-core/transport"
  19. "github.com/xtls/xray-core/transport/internet"
  20. )
  21. func init() {
  22. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  23. h := new(Handler)
  24. if err := core.RequireFeatures(ctx, func(pm policy.Manager, d dns.Client) error {
  25. return h.Init(config.(*Config), pm, d)
  26. }); err != nil {
  27. return nil, err
  28. }
  29. return h, nil
  30. }))
  31. }
  32. // Handler handles Freedom connections.
  33. type Handler struct {
  34. policyManager policy.Manager
  35. dns dns.Client
  36. config *Config
  37. }
  38. // Init initializes the Handler with necessary parameters.
  39. func (h *Handler) Init(config *Config, pm policy.Manager, d dns.Client) error {
  40. h.config = config
  41. h.policyManager = pm
  42. h.dns = d
  43. return nil
  44. }
  45. func (h *Handler) policy() policy.Session {
  46. p := h.policyManager.ForLevel(h.config.UserLevel)
  47. if h.config.Timeout > 0 && h.config.UserLevel == 0 {
  48. p.Timeouts.ConnectionIdle = time.Duration(h.config.Timeout) * time.Second
  49. }
  50. return p
  51. }
  52. func (h *Handler) resolveIP(ctx context.Context, domain string, localAddr net.Address) net.Address {
  53. var opt = dns.LookupIP
  54. if h.config.DomainStrategy == Config_USE_IP4 || (localAddr != nil && localAddr.Family().IsIPv4()) {
  55. opt = dns.LookupIPv4
  56. } else if h.config.DomainStrategy == Config_USE_IP6 || (localAddr != nil && localAddr.Family().IsIPv6()) {
  57. opt = dns.LookupIPv6
  58. }
  59. opt.FakeEnable = true
  60. ips, err := h.dns.LookupOptions(domain, opt)
  61. if err != nil {
  62. newError("failed to get IP address for domain ", domain).Base(err).WriteToLog(session.ExportIDToError(ctx))
  63. }
  64. if len(ips) == 0 {
  65. return nil
  66. }
  67. return net.IPAddress(ips[dice.Roll(len(ips))])
  68. }
  69. func isValidAddress(addr *net.IPOrDomain) bool {
  70. if addr == nil {
  71. return false
  72. }
  73. a := addr.AsAddress()
  74. return a != net.AnyIP
  75. }
  76. // Process implements proxy.Outbound.
  77. func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
  78. outbound := session.OutboundFromContext(ctx)
  79. if outbound == nil || !outbound.Target.IsValid() {
  80. return newError("target not specified.")
  81. }
  82. destination := outbound.Target
  83. UDPOverride := net.UDPDestination(nil, 0)
  84. if h.config.DestinationOverride != nil {
  85. server := h.config.DestinationOverride.Server
  86. if isValidAddress(server.Address) {
  87. destination.Address = server.Address.AsAddress()
  88. UDPOverride.Address = destination.Address
  89. }
  90. if server.Port != 0 {
  91. destination.Port = net.Port(server.Port)
  92. UDPOverride.Port = destination.Port
  93. }
  94. }
  95. newError("opening connection to ", destination).WriteToLog(session.ExportIDToError(ctx))
  96. input := link.Reader
  97. output := link.Writer
  98. var conn internet.Connection
  99. err := retry.ExponentialBackoff(5, 100).On(func() error {
  100. dialDest := destination
  101. if h.config.useIP() && dialDest.Address.Family().IsDomain() {
  102. ip := h.resolveIP(ctx, dialDest.Address.Domain(), dialer.Address())
  103. if ip != nil {
  104. dialDest = net.Destination{
  105. Network: dialDest.Network,
  106. Address: ip,
  107. Port: dialDest.Port,
  108. }
  109. newError("dialing to ", dialDest).WriteToLog(session.ExportIDToError(ctx))
  110. }
  111. }
  112. rawConn, err := dialer.Dial(ctx, dialDest)
  113. if err != nil {
  114. return err
  115. }
  116. conn = rawConn
  117. return nil
  118. })
  119. if err != nil {
  120. return newError("failed to open connection to ", destination).Base(err)
  121. }
  122. defer conn.Close()
  123. plcy := h.policy()
  124. ctx, cancel := context.WithCancel(ctx)
  125. timer := signal.CancelAfterInactivity(ctx, cancel, plcy.Timeouts.ConnectionIdle)
  126. requestDone := func() error {
  127. defer timer.SetTimeout(plcy.Timeouts.DownlinkOnly)
  128. var writer buf.Writer
  129. if destination.Network == net.Network_TCP {
  130. writer = buf.NewWriter(conn)
  131. } else {
  132. writer = NewPacketWriter(conn, h, ctx, UDPOverride)
  133. }
  134. if err := buf.Copy(input, writer, buf.UpdateActivity(timer)); err != nil {
  135. return newError("failed to process request").Base(err)
  136. }
  137. return nil
  138. }
  139. responseDone := func() error {
  140. defer timer.SetTimeout(plcy.Timeouts.UplinkOnly)
  141. var reader buf.Reader
  142. if destination.Network == net.Network_TCP {
  143. reader = buf.NewReader(conn)
  144. } else {
  145. reader = NewPacketReader(conn, UDPOverride)
  146. }
  147. if err := buf.Copy(reader, output, buf.UpdateActivity(timer)); err != nil {
  148. return newError("failed to process response").Base(err)
  149. }
  150. return nil
  151. }
  152. if err := task.Run(ctx, requestDone, task.OnSuccess(responseDone, task.Close(output))); err != nil {
  153. return newError("connection ends").Base(err)
  154. }
  155. return nil
  156. }
  157. func NewPacketReader(conn net.Conn, UDPOverride net.Destination) buf.Reader {
  158. iConn := conn
  159. statConn, ok := iConn.(*internet.StatCouterConnection)
  160. if ok {
  161. iConn = statConn.Connection
  162. }
  163. var counter stats.Counter
  164. if statConn != nil {
  165. counter = statConn.ReadCounter
  166. }
  167. if c, ok := iConn.(*internet.PacketConnWrapper); ok && UDPOverride.Address == nil && UDPOverride.Port == 0 {
  168. return &PacketReader{
  169. PacketConnWrapper: c,
  170. Counter: counter,
  171. }
  172. }
  173. return &buf.PacketReader{Reader: conn}
  174. }
  175. type PacketReader struct {
  176. *internet.PacketConnWrapper
  177. stats.Counter
  178. }
  179. func (r *PacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
  180. b := buf.New()
  181. b.Resize(0, buf.Size)
  182. n, d, err := r.PacketConnWrapper.ReadFrom(b.Bytes())
  183. if err != nil {
  184. b.Release()
  185. return nil, err
  186. }
  187. b.Resize(0, int32(n))
  188. b.UDP = &net.Destination{
  189. Address: net.IPAddress(d.(*net.UDPAddr).IP),
  190. Port: net.Port(d.(*net.UDPAddr).Port),
  191. Network: net.Network_UDP,
  192. }
  193. if r.Counter != nil {
  194. r.Counter.Add(int64(n))
  195. }
  196. return buf.MultiBuffer{b}, nil
  197. }
  198. func NewPacketWriter(conn net.Conn, h *Handler, ctx context.Context, UDPOverride net.Destination) buf.Writer {
  199. iConn := conn
  200. statConn, ok := iConn.(*internet.StatCouterConnection)
  201. if ok {
  202. iConn = statConn.Connection
  203. }
  204. var counter stats.Counter
  205. if statConn != nil {
  206. counter = statConn.WriteCounter
  207. }
  208. if c, ok := iConn.(*internet.PacketConnWrapper); ok {
  209. return &PacketWriter{
  210. PacketConnWrapper: c,
  211. Counter: counter,
  212. Handler: h,
  213. Context: ctx,
  214. UDPOverride: UDPOverride,
  215. }
  216. }
  217. return &buf.SequentialWriter{Writer: conn}
  218. }
  219. type PacketWriter struct {
  220. *internet.PacketConnWrapper
  221. stats.Counter
  222. *Handler
  223. context.Context
  224. UDPOverride net.Destination
  225. }
  226. func (w *PacketWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
  227. for {
  228. mb2, b := buf.SplitFirst(mb)
  229. mb = mb2
  230. if b == nil {
  231. break
  232. }
  233. var n int
  234. var err error
  235. if b.UDP != nil {
  236. if w.UDPOverride.Address != nil {
  237. b.UDP.Address = w.UDPOverride.Address
  238. }
  239. if w.UDPOverride.Port != 0 {
  240. b.UDP.Port = w.UDPOverride.Port
  241. }
  242. if w.Handler.config.useIP() && b.UDP.Address.Family().IsDomain() {
  243. ip := w.Handler.resolveIP(w.Context, b.UDP.Address.Domain(), nil)
  244. if ip != nil {
  245. b.UDP.Address = ip
  246. }
  247. }
  248. destAddr, _ := net.ResolveUDPAddr("udp", b.UDP.NetAddr())
  249. if destAddr == nil {
  250. b.Release()
  251. continue
  252. }
  253. n, err = w.PacketConnWrapper.WriteTo(b.Bytes(), destAddr)
  254. } else {
  255. n, err = w.PacketConnWrapper.Write(b.Bytes())
  256. }
  257. b.Release()
  258. if err != nil {
  259. buf.ReleaseMulti(mb)
  260. return err
  261. }
  262. if w.Counter != nil {
  263. w.Counter.Add(int64(n))
  264. }
  265. }
  266. return nil
  267. }