freedom.go 7.9 KB

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