freedom.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. input := link.Reader
  108. output := link.Writer
  109. var conn stat.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. newError("connection opened to ", destination, ", local endpoint ", conn.LocalAddr(), ", remote endpoint ", conn.RemoteAddr()).WriteToLog(session.ExportIDToError(ctx))
  135. var newCtx context.Context
  136. var newCancel context.CancelFunc
  137. if session.TimeoutOnlyFromContext(ctx) {
  138. newCtx, newCancel = context.WithCancel(context.Background())
  139. }
  140. plcy := h.policy()
  141. ctx, cancel := context.WithCancel(ctx)
  142. timer := signal.CancelAfterInactivity(ctx, func() {
  143. cancel()
  144. if newCancel != nil {
  145. newCancel()
  146. }
  147. }, plcy.Timeouts.ConnectionIdle)
  148. requestDone := func() error {
  149. defer timer.SetTimeout(plcy.Timeouts.DownlinkOnly)
  150. var writer buf.Writer
  151. if destination.Network == net.Network_TCP {
  152. writer = buf.NewWriter(conn)
  153. } else {
  154. writer = NewPacketWriter(conn, h, ctx, UDPOverride)
  155. }
  156. if err := buf.Copy(input, writer, buf.UpdateActivity(timer)); err != nil {
  157. return newError("failed to process request").Base(err)
  158. }
  159. return nil
  160. }
  161. responseDone := func() error {
  162. defer timer.SetTimeout(plcy.Timeouts.UplinkOnly)
  163. var reader buf.Reader
  164. if destination.Network == net.Network_TCP {
  165. reader = buf.NewReader(conn)
  166. } else {
  167. reader = NewPacketReader(conn, UDPOverride)
  168. }
  169. if err := buf.Copy(reader, output, buf.UpdateActivity(timer)); err != nil {
  170. return newError("failed to process response").Base(err)
  171. }
  172. return nil
  173. }
  174. if newCtx != nil {
  175. ctx = newCtx
  176. }
  177. if err := task.Run(ctx, requestDone, task.OnSuccess(responseDone, task.Close(output))); err != nil {
  178. return newError("connection ends").Base(err)
  179. }
  180. return nil
  181. }
  182. func NewPacketReader(conn net.Conn, UDPOverride net.Destination) buf.Reader {
  183. iConn := conn
  184. statConn, ok := iConn.(*stat.CounterConnection)
  185. if ok {
  186. iConn = statConn.Connection
  187. }
  188. var counter stats.Counter
  189. if statConn != nil {
  190. counter = statConn.ReadCounter
  191. }
  192. if c, ok := iConn.(*internet.PacketConnWrapper); ok && UDPOverride.Address == nil && UDPOverride.Port == 0 {
  193. return &PacketReader{
  194. PacketConnWrapper: c,
  195. Counter: counter,
  196. }
  197. }
  198. return &buf.PacketReader{Reader: conn}
  199. }
  200. type PacketReader struct {
  201. *internet.PacketConnWrapper
  202. stats.Counter
  203. }
  204. func (r *PacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
  205. b := buf.New()
  206. b.Resize(0, buf.Size)
  207. n, d, err := r.PacketConnWrapper.ReadFrom(b.Bytes())
  208. if err != nil {
  209. b.Release()
  210. return nil, err
  211. }
  212. b.Resize(0, int32(n))
  213. b.UDP = &net.Destination{
  214. Address: net.IPAddress(d.(*net.UDPAddr).IP),
  215. Port: net.Port(d.(*net.UDPAddr).Port),
  216. Network: net.Network_UDP,
  217. }
  218. if r.Counter != nil {
  219. r.Counter.Add(int64(n))
  220. }
  221. return buf.MultiBuffer{b}, nil
  222. }
  223. func NewPacketWriter(conn net.Conn, h *Handler, ctx context.Context, UDPOverride net.Destination) buf.Writer {
  224. iConn := conn
  225. statConn, ok := iConn.(*stat.CounterConnection)
  226. if ok {
  227. iConn = statConn.Connection
  228. }
  229. var counter stats.Counter
  230. if statConn != nil {
  231. counter = statConn.WriteCounter
  232. }
  233. if c, ok := iConn.(*internet.PacketConnWrapper); ok {
  234. return &PacketWriter{
  235. PacketConnWrapper: c,
  236. Counter: counter,
  237. Handler: h,
  238. Context: ctx,
  239. UDPOverride: UDPOverride,
  240. }
  241. }
  242. return &buf.SequentialWriter{Writer: conn}
  243. }
  244. type PacketWriter struct {
  245. *internet.PacketConnWrapper
  246. stats.Counter
  247. *Handler
  248. context.Context
  249. UDPOverride net.Destination
  250. }
  251. func (w *PacketWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
  252. for {
  253. mb2, b := buf.SplitFirst(mb)
  254. mb = mb2
  255. if b == nil {
  256. break
  257. }
  258. var n int
  259. var err error
  260. if b.UDP != nil {
  261. if w.UDPOverride.Address != nil {
  262. b.UDP.Address = w.UDPOverride.Address
  263. }
  264. if w.UDPOverride.Port != 0 {
  265. b.UDP.Port = w.UDPOverride.Port
  266. }
  267. if w.Handler.config.useIP() && b.UDP.Address.Family().IsDomain() {
  268. ip := w.Handler.resolveIP(w.Context, b.UDP.Address.Domain(), nil)
  269. if ip != nil {
  270. b.UDP.Address = ip
  271. }
  272. }
  273. destAddr, _ := net.ResolveUDPAddr("udp", b.UDP.NetAddr())
  274. if destAddr == nil {
  275. b.Release()
  276. continue
  277. }
  278. n, err = w.PacketConnWrapper.WriteTo(b.Bytes(), destAddr)
  279. } else {
  280. n, err = w.PacketConnWrapper.Write(b.Bytes())
  281. }
  282. b.Release()
  283. if err != nil {
  284. buf.ReleaseMulti(mb)
  285. return err
  286. }
  287. if w.Counter != nil {
  288. w.Counter.Add(int64(n))
  289. }
  290. }
  291. return nil
  292. }