freedom.go 7.6 KB

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