freedom.go 11 KB

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