freedom.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. package freedom
  2. //go:generate go run github.com/xtls/xray-core/common/errors/errorgen
  3. import (
  4. "context"
  5. "crypto/rand"
  6. "io"
  7. "math/big"
  8. "time"
  9. "github.com/xtls/xray-core/common"
  10. "github.com/xtls/xray-core/common/buf"
  11. "github.com/xtls/xray-core/common/dice"
  12. "github.com/xtls/xray-core/common/net"
  13. "github.com/xtls/xray-core/common/platform"
  14. "github.com/xtls/xray-core/common/retry"
  15. "github.com/xtls/xray-core/common/session"
  16. "github.com/xtls/xray-core/common/signal"
  17. "github.com/xtls/xray-core/common/task"
  18. "github.com/xtls/xray-core/core"
  19. "github.com/xtls/xray-core/features/dns"
  20. "github.com/xtls/xray-core/features/policy"
  21. "github.com/xtls/xray-core/features/stats"
  22. "github.com/xtls/xray-core/proxy"
  23. "github.com/xtls/xray-core/transport"
  24. "github.com/xtls/xray-core/transport/internet"
  25. "github.com/xtls/xray-core/transport/internet/stat"
  26. )
  27. var useSplice bool
  28. func init() {
  29. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  30. h := new(Handler)
  31. if err := core.RequireFeatures(ctx, func(pm policy.Manager, d dns.Client) error {
  32. return h.Init(config.(*Config), pm, d)
  33. }); err != nil {
  34. return nil, err
  35. }
  36. return h, nil
  37. }))
  38. const defaultFlagValue = "NOT_DEFINED_AT_ALL"
  39. value := platform.NewEnvFlag(platform.UseFreedomSplice).GetValue(func() string { return defaultFlagValue })
  40. switch value {
  41. case defaultFlagValue, "auto", "enable":
  42. useSplice = true
  43. }
  44. }
  45. // Handler handles Freedom connections.
  46. type Handler struct {
  47. policyManager policy.Manager
  48. dns dns.Client
  49. config *Config
  50. }
  51. // Init initializes the Handler with necessary parameters.
  52. func (h *Handler) Init(config *Config, pm policy.Manager, d dns.Client) error {
  53. h.config = config
  54. h.policyManager = pm
  55. h.dns = d
  56. return nil
  57. }
  58. func (h *Handler) policy() policy.Session {
  59. p := h.policyManager.ForLevel(h.config.UserLevel)
  60. if h.config.Timeout > 0 && h.config.UserLevel == 0 {
  61. p.Timeouts.ConnectionIdle = time.Duration(h.config.Timeout) * time.Second
  62. }
  63. return p
  64. }
  65. func (h *Handler) resolveIP(ctx context.Context, domain string, localAddr net.Address) net.Address {
  66. ips, err := h.dns.LookupIP(domain, dns.IPOption{
  67. IPv4Enable: (localAddr == nil || localAddr.Family().IsIPv4()) && h.config.preferIP4(),
  68. IPv6Enable: (localAddr == nil || localAddr.Family().IsIPv6()) && h.config.preferIP6(),
  69. })
  70. { // Resolve fallback
  71. if (len(ips) == 0 || err != nil) && h.config.hasFallback() && localAddr == nil {
  72. ips, err = h.dns.LookupIP(domain, dns.IPOption{
  73. IPv4Enable: h.config.fallbackIP4(),
  74. IPv6Enable: h.config.fallbackIP6(),
  75. })
  76. }
  77. }
  78. if err != nil {
  79. newError("failed to get IP address for domain ", domain).Base(err).WriteToLog(session.ExportIDToError(ctx))
  80. }
  81. if len(ips) == 0 {
  82. return nil
  83. }
  84. return net.IPAddress(ips[dice.Roll(len(ips))])
  85. }
  86. func isValidAddress(addr *net.IPOrDomain) bool {
  87. if addr == nil {
  88. return false
  89. }
  90. a := addr.AsAddress()
  91. return a != net.AnyIP
  92. }
  93. // Process implements proxy.Outbound.
  94. func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error {
  95. outbound := session.OutboundFromContext(ctx)
  96. if outbound == nil || !outbound.Target.IsValid() {
  97. return newError("target not specified.")
  98. }
  99. outbound.Name = "freedom"
  100. inbound := session.InboundFromContext(ctx)
  101. if inbound != nil {
  102. inbound.SetCanSpliceCopy(1)
  103. }
  104. destination := outbound.Target
  105. UDPOverride := net.UDPDestination(nil, 0)
  106. if h.config.DestinationOverride != nil {
  107. server := h.config.DestinationOverride.Server
  108. if isValidAddress(server.Address) {
  109. destination.Address = server.Address.AsAddress()
  110. UDPOverride.Address = destination.Address
  111. }
  112. if server.Port != 0 {
  113. destination.Port = net.Port(server.Port)
  114. UDPOverride.Port = destination.Port
  115. }
  116. }
  117. input := link.Reader
  118. output := link.Writer
  119. var conn stat.Connection
  120. err := retry.ExponentialBackoff(5, 100).On(func() error {
  121. dialDest := destination
  122. if h.config.hasStrategy() && dialDest.Address.Family().IsDomain() {
  123. ip := h.resolveIP(ctx, dialDest.Address.Domain(), dialer.Address())
  124. if ip != nil {
  125. dialDest = net.Destination{
  126. Network: dialDest.Network,
  127. Address: ip,
  128. Port: dialDest.Port,
  129. }
  130. newError("dialing to ", dialDest).WriteToLog(session.ExportIDToError(ctx))
  131. } else if h.config.forceIP() {
  132. return dns.ErrEmptyResponse
  133. }
  134. }
  135. rawConn, err := dialer.Dial(ctx, dialDest)
  136. if err != nil {
  137. return err
  138. }
  139. conn = rawConn
  140. return nil
  141. })
  142. if err != nil {
  143. return newError("failed to open connection to ", destination).Base(err)
  144. }
  145. defer conn.Close()
  146. newError("connection opened to ", destination, ", local endpoint ", conn.LocalAddr(), ", remote endpoint ", conn.RemoteAddr()).WriteToLog(session.ExportIDToError(ctx))
  147. var newCtx context.Context
  148. var newCancel context.CancelFunc
  149. if session.TimeoutOnlyFromContext(ctx) {
  150. newCtx, newCancel = context.WithCancel(context.Background())
  151. }
  152. plcy := h.policy()
  153. ctx, cancel := context.WithCancel(ctx)
  154. timer := signal.CancelAfterInactivity(ctx, func() {
  155. cancel()
  156. if newCancel != nil {
  157. newCancel()
  158. }
  159. }, plcy.Timeouts.ConnectionIdle)
  160. requestDone := func() error {
  161. defer timer.SetTimeout(plcy.Timeouts.DownlinkOnly)
  162. var writer buf.Writer
  163. if destination.Network == net.Network_TCP {
  164. if h.config.Fragment != nil {
  165. newError("FRAGMENT", h.config.Fragment.PacketsFrom, h.config.Fragment.PacketsTo, h.config.Fragment.LengthMin, h.config.Fragment.LengthMax,
  166. h.config.Fragment.IntervalMin, h.config.Fragment.IntervalMax).AtDebug().WriteToLog(session.ExportIDToError(ctx))
  167. writer = buf.NewWriter(&FragmentWriter{
  168. fragment: h.config.Fragment,
  169. writer: conn,
  170. })
  171. } else {
  172. writer = buf.NewWriter(conn)
  173. }
  174. } else {
  175. writer = NewPacketWriter(conn, h, ctx, UDPOverride)
  176. }
  177. if err := buf.Copy(input, writer, buf.UpdateActivity(timer)); err != nil {
  178. return newError("failed to process request").Base(err)
  179. }
  180. return nil
  181. }
  182. responseDone := func() error {
  183. defer timer.SetTimeout(plcy.Timeouts.UplinkOnly)
  184. if destination.Network == net.Network_TCP {
  185. var writeConn net.Conn
  186. if inbound := session.InboundFromContext(ctx); inbound != nil && inbound.Conn != nil && useSplice {
  187. writeConn = inbound.Conn
  188. }
  189. return proxy.CopyRawConnIfExist(ctx, conn, writeConn, link.Writer, timer)
  190. }
  191. reader := NewPacketReader(conn, UDPOverride)
  192. if err := buf.Copy(reader, output, buf.UpdateActivity(timer)); err != nil {
  193. return newError("failed to process response").Base(err)
  194. }
  195. return nil
  196. }
  197. if newCtx != nil {
  198. ctx = newCtx
  199. }
  200. if err := task.Run(ctx, requestDone, task.OnSuccess(responseDone, task.Close(output))); err != nil {
  201. return newError("connection ends").Base(err)
  202. }
  203. return nil
  204. }
  205. func NewPacketReader(conn net.Conn, UDPOverride net.Destination) buf.Reader {
  206. iConn := conn
  207. statConn, ok := iConn.(*stat.CounterConnection)
  208. if ok {
  209. iConn = statConn.Connection
  210. }
  211. var counter stats.Counter
  212. if statConn != nil {
  213. counter = statConn.ReadCounter
  214. }
  215. if c, ok := iConn.(*internet.PacketConnWrapper); ok && UDPOverride.Address == nil && UDPOverride.Port == 0 {
  216. return &PacketReader{
  217. PacketConnWrapper: c,
  218. Counter: counter,
  219. }
  220. }
  221. return &buf.PacketReader{Reader: conn}
  222. }
  223. type PacketReader struct {
  224. *internet.PacketConnWrapper
  225. stats.Counter
  226. }
  227. func (r *PacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
  228. b := buf.New()
  229. b.Resize(0, buf.Size)
  230. n, d, err := r.PacketConnWrapper.ReadFrom(b.Bytes())
  231. if err != nil {
  232. b.Release()
  233. return nil, err
  234. }
  235. b.Resize(0, int32(n))
  236. b.UDP = &net.Destination{
  237. Address: net.IPAddress(d.(*net.UDPAddr).IP),
  238. Port: net.Port(d.(*net.UDPAddr).Port),
  239. Network: net.Network_UDP,
  240. }
  241. if r.Counter != nil {
  242. r.Counter.Add(int64(n))
  243. }
  244. return buf.MultiBuffer{b}, nil
  245. }
  246. func NewPacketWriter(conn net.Conn, h *Handler, ctx context.Context, UDPOverride net.Destination) buf.Writer {
  247. iConn := conn
  248. statConn, ok := iConn.(*stat.CounterConnection)
  249. if ok {
  250. iConn = statConn.Connection
  251. }
  252. var counter stats.Counter
  253. if statConn != nil {
  254. counter = statConn.WriteCounter
  255. }
  256. if c, ok := iConn.(*internet.PacketConnWrapper); ok {
  257. return &PacketWriter{
  258. PacketConnWrapper: c,
  259. Counter: counter,
  260. Handler: h,
  261. Context: ctx,
  262. UDPOverride: UDPOverride,
  263. }
  264. }
  265. return &buf.SequentialWriter{Writer: conn}
  266. }
  267. type PacketWriter struct {
  268. *internet.PacketConnWrapper
  269. stats.Counter
  270. *Handler
  271. context.Context
  272. UDPOverride net.Destination
  273. }
  274. func (w *PacketWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
  275. for {
  276. mb2, b := buf.SplitFirst(mb)
  277. mb = mb2
  278. if b == nil {
  279. break
  280. }
  281. var n int
  282. var err error
  283. if b.UDP != nil {
  284. if w.UDPOverride.Address != nil {
  285. b.UDP.Address = w.UDPOverride.Address
  286. }
  287. if w.UDPOverride.Port != 0 {
  288. b.UDP.Port = w.UDPOverride.Port
  289. }
  290. if w.Handler.config.hasStrategy() && b.UDP.Address.Family().IsDomain() {
  291. ip := w.Handler.resolveIP(w.Context, b.UDP.Address.Domain(), nil)
  292. if ip != nil {
  293. b.UDP.Address = ip
  294. }
  295. }
  296. destAddr, _ := net.ResolveUDPAddr("udp", b.UDP.NetAddr())
  297. if destAddr == nil {
  298. b.Release()
  299. continue
  300. }
  301. n, err = w.PacketConnWrapper.WriteTo(b.Bytes(), destAddr)
  302. } else {
  303. n, err = w.PacketConnWrapper.Write(b.Bytes())
  304. }
  305. b.Release()
  306. if err != nil {
  307. buf.ReleaseMulti(mb)
  308. return err
  309. }
  310. if w.Counter != nil {
  311. w.Counter.Add(int64(n))
  312. }
  313. }
  314. return nil
  315. }
  316. type FragmentWriter struct {
  317. fragment *Fragment
  318. writer io.Writer
  319. count uint64
  320. }
  321. func (f *FragmentWriter) Write(b []byte) (int, error) {
  322. f.count++
  323. if f.fragment.PacketsFrom == 0 && f.fragment.PacketsTo == 1 {
  324. if f.count != 1 || len(b) <= 5 || b[0] != 22 {
  325. return f.writer.Write(b)
  326. }
  327. recordLen := 5 + ((int(b[3]) << 8) | int(b[4]))
  328. data := b[5:recordLen]
  329. buf := make([]byte, 1024)
  330. for from := 0; ; {
  331. to := from + int(randBetween(int64(f.fragment.LengthMin), int64(f.fragment.LengthMax)))
  332. if to > len(data) {
  333. to = len(data)
  334. }
  335. copy(buf[:3], b)
  336. copy(buf[5:], data[from:to])
  337. l := to - from
  338. from = to
  339. buf[3] = byte(l >> 8)
  340. buf[4] = byte(l)
  341. _, err := f.writer.Write(buf[:5+l])
  342. time.Sleep(time.Duration(randBetween(int64(f.fragment.IntervalMin), int64(f.fragment.IntervalMax))) * time.Millisecond)
  343. if err != nil {
  344. return 0, err
  345. }
  346. if from == len(data) {
  347. if len(b) > recordLen {
  348. n, err := f.writer.Write(b[recordLen:])
  349. if err != nil {
  350. return recordLen + n, err
  351. }
  352. }
  353. return len(b), nil
  354. }
  355. }
  356. }
  357. if f.fragment.PacketsFrom != 0 && (f.count < f.fragment.PacketsFrom || f.count > f.fragment.PacketsTo) {
  358. return f.writer.Write(b)
  359. }
  360. for from := 0; ; {
  361. to := from + int(randBetween(int64(f.fragment.LengthMin), int64(f.fragment.LengthMax)))
  362. if to > len(b) {
  363. to = len(b)
  364. }
  365. n, err := f.writer.Write(b[from:to])
  366. from += n
  367. time.Sleep(time.Duration(randBetween(int64(f.fragment.IntervalMin), int64(f.fragment.IntervalMax))) * time.Millisecond)
  368. if err != nil {
  369. return from, err
  370. }
  371. if from >= len(b) {
  372. return from, nil
  373. }
  374. }
  375. }
  376. // stolen from github.com/xtls/xray-core/transport/internet/reality
  377. func randBetween(left int64, right int64) int64 {
  378. if left == right {
  379. return left
  380. }
  381. bigInt, _ := rand.Int(rand.Reader, big.NewInt(right-left))
  382. return left + bigInt.Int64()
  383. }