freedom.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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 option dns.IPOption = dns.IPOption{
  54. IPv4Enable: true,
  55. IPv6Enable: true,
  56. FakeEnable: false,
  57. }
  58. if h.config.DomainStrategy == Config_USE_IP4 || (localAddr != nil && localAddr.Family().IsIPv4()) {
  59. option = dns.IPOption{
  60. IPv4Enable: true,
  61. IPv6Enable: false,
  62. FakeEnable: false,
  63. }
  64. } else if h.config.DomainStrategy == Config_USE_IP6 || (localAddr != nil && localAddr.Family().IsIPv6()) {
  65. option = dns.IPOption{
  66. IPv4Enable: false,
  67. IPv6Enable: true,
  68. FakeEnable: false,
  69. }
  70. }
  71. ips, err := h.dns.LookupIP(domain, option)
  72. if err != nil {
  73. newError("failed to get IP address for domain ", domain).Base(err).WriteToLog(session.ExportIDToError(ctx))
  74. }
  75. if len(ips) == 0 {
  76. return nil
  77. }
  78. return net.IPAddress(ips[dice.Roll(len(ips))])
  79. }
  80. func isValidAddress(addr *net.IPOrDomain) bool {
  81. if addr == nil {
  82. return false
  83. }
  84. a := addr.AsAddress()
  85. return a != net.AnyIP
  86. }
  87. // Process implements proxy.Outbound.
  88. func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
  89. outbound := session.OutboundFromContext(ctx)
  90. if outbound == nil || !outbound.Target.IsValid() {
  91. return newError("target not specified.")
  92. }
  93. destination := outbound.Target
  94. UDPOverride := net.UDPDestination(nil, 0)
  95. if h.config.DestinationOverride != nil {
  96. server := h.config.DestinationOverride.Server
  97. if isValidAddress(server.Address) {
  98. destination.Address = server.Address.AsAddress()
  99. UDPOverride.Address = destination.Address
  100. }
  101. if server.Port != 0 {
  102. destination.Port = net.Port(server.Port)
  103. UDPOverride.Port = destination.Port
  104. }
  105. }
  106. newError("opening connection to ", destination).WriteToLog(session.ExportIDToError(ctx))
  107. input := link.Reader
  108. output := link.Writer
  109. var conn internet.Connection
  110. err := retry.ExponentialBackoff(5, 100).On(func() error {
  111. dialDest := destination
  112. if h.config.useIP() && dialDest.Address.Family().IsDomain() {
  113. ip := h.resolveIP(ctx, dialDest.Address.Domain(), dialer.Address())
  114. if ip != nil {
  115. dialDest = net.Destination{
  116. Network: dialDest.Network,
  117. Address: ip,
  118. Port: dialDest.Port,
  119. }
  120. newError("dialing to ", dialDest).WriteToLog(session.ExportIDToError(ctx))
  121. }
  122. }
  123. rawConn, err := dialer.Dial(ctx, dialDest)
  124. if err != nil {
  125. return err
  126. }
  127. conn = rawConn
  128. return nil
  129. })
  130. if err != nil {
  131. return newError("failed to open connection to ", destination).Base(err)
  132. }
  133. defer conn.Close()
  134. plcy := h.policy()
  135. ctx, cancel := context.WithCancel(ctx)
  136. timer := signal.CancelAfterInactivity(ctx, cancel, plcy.Timeouts.ConnectionIdle)
  137. requestDone := func() error {
  138. defer timer.SetTimeout(plcy.Timeouts.DownlinkOnly)
  139. var writer buf.Writer
  140. if destination.Network == net.Network_TCP {
  141. writer = buf.NewWriter(conn)
  142. } else {
  143. writer = NewPacketWriter(conn, h, ctx, UDPOverride)
  144. }
  145. if err := buf.Copy(input, writer, buf.UpdateActivity(timer)); err != nil {
  146. return newError("failed to process request").Base(err)
  147. }
  148. return nil
  149. }
  150. responseDone := func() error {
  151. defer timer.SetTimeout(plcy.Timeouts.UplinkOnly)
  152. var reader buf.Reader
  153. if destination.Network == net.Network_TCP {
  154. reader = buf.NewReader(conn)
  155. } else {
  156. reader = NewPacketReader(conn, UDPOverride)
  157. }
  158. if err := buf.Copy(reader, output, buf.UpdateActivity(timer)); err != nil {
  159. return newError("failed to process response").Base(err)
  160. }
  161. return nil
  162. }
  163. if err := task.Run(ctx, requestDone, task.OnSuccess(responseDone, task.Close(output))); err != nil {
  164. return newError("connection ends").Base(err)
  165. }
  166. return nil
  167. }
  168. func NewPacketReader(conn net.Conn, UDPOverride net.Destination) buf.Reader {
  169. iConn := conn
  170. statConn, ok := iConn.(*internet.StatCouterConnection)
  171. if ok {
  172. iConn = statConn.Connection
  173. }
  174. var counter stats.Counter
  175. if statConn != nil {
  176. counter = statConn.ReadCounter
  177. }
  178. if c, ok := iConn.(*internet.PacketConnWrapper); ok && UDPOverride.Address == nil && UDPOverride.Port == 0 {
  179. return &PacketReader{
  180. PacketConnWrapper: c,
  181. Counter: counter,
  182. }
  183. }
  184. return &buf.PacketReader{Reader: conn}
  185. }
  186. type PacketReader struct {
  187. *internet.PacketConnWrapper
  188. stats.Counter
  189. }
  190. func (r *PacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
  191. b := buf.New()
  192. b.Resize(0, buf.Size)
  193. n, d, err := r.PacketConnWrapper.ReadFrom(b.Bytes())
  194. if err != nil {
  195. b.Release()
  196. return nil, err
  197. }
  198. b.Resize(0, int32(n))
  199. b.UDP = &net.Destination{
  200. Address: net.IPAddress(d.(*net.UDPAddr).IP),
  201. Port: net.Port(d.(*net.UDPAddr).Port),
  202. Network: net.Network_UDP,
  203. }
  204. if r.Counter != nil {
  205. r.Counter.Add(int64(n))
  206. }
  207. return buf.MultiBuffer{b}, nil
  208. }
  209. func NewPacketWriter(conn net.Conn, h *Handler, ctx context.Context, UDPOverride net.Destination) buf.Writer {
  210. iConn := conn
  211. statConn, ok := iConn.(*internet.StatCouterConnection)
  212. if ok {
  213. iConn = statConn.Connection
  214. }
  215. var counter stats.Counter
  216. if statConn != nil {
  217. counter = statConn.WriteCounter
  218. }
  219. if c, ok := iConn.(*internet.PacketConnWrapper); ok {
  220. return &PacketWriter{
  221. PacketConnWrapper: c,
  222. Counter: counter,
  223. Handler: h,
  224. Context: ctx,
  225. UDPOverride: UDPOverride,
  226. }
  227. }
  228. return &buf.SequentialWriter{Writer: conn}
  229. }
  230. type PacketWriter struct {
  231. *internet.PacketConnWrapper
  232. stats.Counter
  233. *Handler
  234. context.Context
  235. UDPOverride net.Destination
  236. }
  237. func (w *PacketWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
  238. for {
  239. mb2, b := buf.SplitFirst(mb)
  240. mb = mb2
  241. if b == nil {
  242. break
  243. }
  244. var n int
  245. var err error
  246. if b.UDP != nil {
  247. if w.UDPOverride.Address != nil {
  248. b.UDP.Address = w.UDPOverride.Address
  249. }
  250. if w.UDPOverride.Port != 0 {
  251. b.UDP.Port = w.UDPOverride.Port
  252. }
  253. if w.Handler.config.useIP() && b.UDP.Address.Family().IsDomain() {
  254. ip := w.Handler.resolveIP(w.Context, b.UDP.Address.Domain(), nil)
  255. if ip != nil {
  256. b.UDP.Address = ip
  257. }
  258. }
  259. destAddr, _ := net.ResolveUDPAddr("udp", b.UDP.NetAddr())
  260. if destAddr == nil {
  261. b.Release()
  262. continue
  263. }
  264. n, err = w.PacketConnWrapper.WriteTo(b.Bytes(), destAddr)
  265. } else {
  266. n, err = w.PacketConnWrapper.Write(b.Bytes())
  267. }
  268. b.Release()
  269. if err != nil {
  270. buf.ReleaseMulti(mb)
  271. return err
  272. }
  273. if w.Counter != nil {
  274. w.Counter.Add(int64(n))
  275. }
  276. }
  277. return nil
  278. }