worker.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. package inbound
  2. import (
  3. "context"
  4. "sync"
  5. "sync/atomic"
  6. "time"
  7. "github.com/xtls/xray-core/app/proxyman"
  8. "github.com/xtls/xray-core/common"
  9. "github.com/xtls/xray-core/common/buf"
  10. c "github.com/xtls/xray-core/common/ctx"
  11. "github.com/xtls/xray-core/common/errors"
  12. "github.com/xtls/xray-core/common/net"
  13. "github.com/xtls/xray-core/common/serial"
  14. "github.com/xtls/xray-core/common/session"
  15. "github.com/xtls/xray-core/common/signal/done"
  16. "github.com/xtls/xray-core/common/task"
  17. "github.com/xtls/xray-core/features/routing"
  18. "github.com/xtls/xray-core/features/stats"
  19. "github.com/xtls/xray-core/proxy"
  20. "github.com/xtls/xray-core/transport/internet"
  21. "github.com/xtls/xray-core/transport/internet/stat"
  22. "github.com/xtls/xray-core/transport/internet/tcp"
  23. "github.com/xtls/xray-core/transport/internet/udp"
  24. "github.com/xtls/xray-core/transport/pipe"
  25. )
  26. type worker interface {
  27. Start() error
  28. Close() error
  29. Port() net.Port
  30. Proxy() proxy.Inbound
  31. }
  32. type tcpWorker struct {
  33. address net.Address
  34. port net.Port
  35. proxy proxy.Inbound
  36. stream *internet.MemoryStreamConfig
  37. recvOrigDest bool
  38. tag string
  39. dispatcher routing.Dispatcher
  40. sniffingConfig *proxyman.SniffingConfig
  41. uplinkCounter stats.Counter
  42. downlinkCounter stats.Counter
  43. hub internet.Listener
  44. ctx context.Context
  45. }
  46. func getTProxyType(s *internet.MemoryStreamConfig) internet.SocketConfig_TProxyMode {
  47. if s == nil || s.SocketSettings == nil {
  48. return internet.SocketConfig_Off
  49. }
  50. return s.SocketSettings.Tproxy
  51. }
  52. func (w *tcpWorker) callback(conn stat.Connection) {
  53. ctx, cancel := context.WithCancel(w.ctx)
  54. sid := session.NewID()
  55. ctx = c.ContextWithID(ctx, sid)
  56. outbounds := []*session.Outbound{{}}
  57. if w.recvOrigDest {
  58. var dest net.Destination
  59. switch getTProxyType(w.stream) {
  60. case internet.SocketConfig_Redirect:
  61. d, err := tcp.GetOriginalDestination(conn)
  62. if err != nil {
  63. errors.LogInfoInner(ctx, err, "failed to get original destination")
  64. } else {
  65. dest = d
  66. }
  67. case internet.SocketConfig_TProxy:
  68. dest = net.DestinationFromAddr(conn.LocalAddr())
  69. }
  70. if dest.IsValid() {
  71. // Check if try to connect to this inbound itself (can cause loopback)
  72. var isLoopBack bool
  73. if w.address == net.AnyIP || w.address == net.AnyIPv6 {
  74. if dest.Port.Value() == w.port.Value() && IsLocal(dest.Address.IP()) {
  75. isLoopBack = true
  76. }
  77. } else {
  78. if w.hub.Addr().String() == dest.NetAddr() {
  79. isLoopBack = true
  80. }
  81. }
  82. if isLoopBack {
  83. cancel()
  84. conn.Close()
  85. errors.LogError(ctx, errors.New("loopback connection detected"))
  86. return
  87. }
  88. outbounds[0].Target = dest
  89. }
  90. }
  91. ctx = session.ContextWithOutbounds(ctx, outbounds)
  92. if w.uplinkCounter != nil || w.downlinkCounter != nil {
  93. conn = &stat.CounterConnection{
  94. Connection: conn,
  95. ReadCounter: w.uplinkCounter,
  96. WriteCounter: w.downlinkCounter,
  97. }
  98. }
  99. ctx = session.ContextWithInbound(ctx, &session.Inbound{
  100. Source: net.DestinationFromAddr(conn.RemoteAddr()),
  101. Local: net.DestinationFromAddr(conn.LocalAddr()),
  102. Gateway: net.TCPDestination(w.address, w.port),
  103. Tag: w.tag,
  104. Conn: conn,
  105. })
  106. content := new(session.Content)
  107. if w.sniffingConfig != nil {
  108. content.SniffingRequest.Enabled = w.sniffingConfig.Enabled
  109. content.SniffingRequest.OverrideDestinationForProtocol = w.sniffingConfig.DestinationOverride
  110. content.SniffingRequest.ExcludeForDomain = w.sniffingConfig.DomainsExcluded
  111. content.SniffingRequest.MetadataOnly = w.sniffingConfig.MetadataOnly
  112. content.SniffingRequest.RouteOnly = w.sniffingConfig.RouteOnly
  113. }
  114. ctx = session.ContextWithContent(ctx, content)
  115. if err := w.proxy.Process(ctx, net.Network_TCP, conn, w.dispatcher); err != nil {
  116. errors.LogInfoInner(ctx, err, "connection ends")
  117. }
  118. cancel()
  119. conn.Close()
  120. }
  121. func (w *tcpWorker) Proxy() proxy.Inbound {
  122. return w.proxy
  123. }
  124. func (w *tcpWorker) Start() error {
  125. ctx := context.Background()
  126. hub, err := internet.ListenTCP(ctx, w.address, w.port, w.stream, func(conn stat.Connection) {
  127. go w.callback(conn)
  128. })
  129. if err != nil {
  130. return errors.New("failed to listen TCP on ", w.port).AtWarning().Base(err)
  131. }
  132. w.hub = hub
  133. return nil
  134. }
  135. func (w *tcpWorker) Close() error {
  136. var errs []interface{}
  137. if w.hub != nil {
  138. if err := common.Close(w.hub); err != nil {
  139. errs = append(errs, err)
  140. }
  141. if err := common.Close(w.proxy); err != nil {
  142. errs = append(errs, err)
  143. }
  144. }
  145. if len(errs) > 0 {
  146. return errors.New("failed to close all resources").Base(errors.New(serial.Concat(errs...)))
  147. }
  148. return nil
  149. }
  150. func (w *tcpWorker) Port() net.Port {
  151. return w.port
  152. }
  153. type udpConn struct {
  154. lastActivityTime int64 // in seconds
  155. reader buf.Reader
  156. writer buf.Writer
  157. output func([]byte) (int, error)
  158. remote net.Addr
  159. local net.Addr
  160. done *done.Instance
  161. uplink stats.Counter
  162. downlink stats.Counter
  163. inactive bool
  164. cancel context.CancelFunc
  165. }
  166. func (c *udpConn) setInactive() {
  167. c.inactive = true
  168. }
  169. func (c *udpConn) updateActivity() {
  170. atomic.StoreInt64(&c.lastActivityTime, time.Now().Unix())
  171. }
  172. // ReadMultiBuffer implements buf.Reader
  173. func (c *udpConn) ReadMultiBuffer() (buf.MultiBuffer, error) {
  174. mb, err := c.reader.ReadMultiBuffer()
  175. if err != nil {
  176. return nil, err
  177. }
  178. c.updateActivity()
  179. if c.uplink != nil {
  180. c.uplink.Add(int64(mb.Len()))
  181. }
  182. return mb, nil
  183. }
  184. func (c *udpConn) Read(buf []byte) (int, error) {
  185. panic("not implemented")
  186. }
  187. // Write implements io.Writer.
  188. func (c *udpConn) Write(buf []byte) (int, error) {
  189. n, err := c.output(buf)
  190. if c.downlink != nil {
  191. c.downlink.Add(int64(n))
  192. }
  193. if err == nil {
  194. c.updateActivity()
  195. }
  196. return n, err
  197. }
  198. func (c *udpConn) Close() error {
  199. if c.cancel != nil {
  200. c.cancel()
  201. }
  202. common.Must(c.done.Close())
  203. common.Must(common.Close(c.writer))
  204. return nil
  205. }
  206. func (c *udpConn) RemoteAddr() net.Addr {
  207. return c.remote
  208. }
  209. func (c *udpConn) LocalAddr() net.Addr {
  210. return c.local
  211. }
  212. func (*udpConn) SetDeadline(time.Time) error {
  213. return nil
  214. }
  215. func (*udpConn) SetReadDeadline(time.Time) error {
  216. return nil
  217. }
  218. func (*udpConn) SetWriteDeadline(time.Time) error {
  219. return nil
  220. }
  221. type connID struct {
  222. src net.Destination
  223. dest net.Destination
  224. }
  225. type udpWorker struct {
  226. sync.RWMutex
  227. proxy proxy.Inbound
  228. hub *udp.Hub
  229. address net.Address
  230. port net.Port
  231. tag string
  232. stream *internet.MemoryStreamConfig
  233. dispatcher routing.Dispatcher
  234. sniffingConfig *proxyman.SniffingConfig
  235. uplinkCounter stats.Counter
  236. downlinkCounter stats.Counter
  237. checker *task.Periodic
  238. activeConn map[connID]*udpConn
  239. ctx context.Context
  240. cone bool
  241. }
  242. func (w *udpWorker) getConnection(id connID) (*udpConn, bool) {
  243. w.Lock()
  244. defer w.Unlock()
  245. if conn, found := w.activeConn[id]; found && !conn.done.Done() {
  246. conn.updateActivity()
  247. return conn, true
  248. }
  249. pReader, pWriter := pipe.New(pipe.DiscardOverflow(), pipe.WithSizeLimit(16*1024))
  250. conn := &udpConn{
  251. reader: pReader,
  252. writer: pWriter,
  253. output: func(b []byte) (int, error) {
  254. return w.hub.WriteTo(b, id.src)
  255. },
  256. remote: &net.UDPAddr{
  257. IP: id.src.Address.IP(),
  258. Port: int(id.src.Port),
  259. },
  260. local: &net.UDPAddr{
  261. IP: w.address.IP(),
  262. Port: int(w.port),
  263. },
  264. done: done.New(),
  265. uplink: w.uplinkCounter,
  266. downlink: w.downlinkCounter,
  267. }
  268. w.activeConn[id] = conn
  269. conn.updateActivity()
  270. return conn, false
  271. }
  272. func (w *udpWorker) callback(b *buf.Buffer, source net.Destination, originalDest net.Destination) {
  273. id := connID{
  274. src: source,
  275. }
  276. if originalDest.IsValid() {
  277. if !w.cone {
  278. id.dest = originalDest
  279. }
  280. b.UDP = &originalDest
  281. }
  282. conn, existing := w.getConnection(id)
  283. // payload will be discarded in pipe is full.
  284. conn.writer.WriteMultiBuffer(buf.MultiBuffer{b})
  285. if !existing {
  286. common.Must(w.checker.Start())
  287. go func() {
  288. ctx, cancel := context.WithCancel(w.ctx)
  289. conn.cancel = cancel
  290. sid := session.NewID()
  291. ctx = c.ContextWithID(ctx, sid)
  292. outbounds := []*session.Outbound{{}}
  293. if originalDest.IsValid() {
  294. outbounds[0].Target = originalDest
  295. }
  296. ctx = session.ContextWithOutbounds(ctx, outbounds)
  297. local := net.DestinationFromAddr(w.hub.Addr())
  298. if local.Address == net.AnyIP || local.Address == net.AnyIPv6 {
  299. if source.Address.Family().IsIPv4() {
  300. local.Address = net.AnyIP
  301. } else if source.Address.Family().IsIPv6() {
  302. local.Address = net.AnyIPv6
  303. }
  304. }
  305. ctx = session.ContextWithInbound(ctx, &session.Inbound{
  306. Source: source,
  307. Local: local, // Due to some limitations, in UDP connections, localIP is always equal to listen interface IP
  308. Gateway: net.UDPDestination(w.address, w.port),
  309. Tag: w.tag,
  310. })
  311. content := new(session.Content)
  312. if w.sniffingConfig != nil {
  313. content.SniffingRequest.Enabled = w.sniffingConfig.Enabled
  314. content.SniffingRequest.OverrideDestinationForProtocol = w.sniffingConfig.DestinationOverride
  315. content.SniffingRequest.ExcludeForDomain = w.sniffingConfig.DomainsExcluded
  316. content.SniffingRequest.MetadataOnly = w.sniffingConfig.MetadataOnly
  317. content.SniffingRequest.RouteOnly = w.sniffingConfig.RouteOnly
  318. }
  319. ctx = session.ContextWithContent(ctx, content)
  320. if err := w.proxy.Process(ctx, net.Network_UDP, conn, w.dispatcher); err != nil {
  321. errors.LogInfoInner(ctx, err, "connection ends")
  322. }
  323. conn.Close()
  324. // conn not removed by checker TODO may be lock worker here is better
  325. if !conn.inactive {
  326. conn.setInactive()
  327. w.removeConn(id)
  328. }
  329. }()
  330. }
  331. }
  332. func (w *udpWorker) removeConn(id connID) {
  333. w.Lock()
  334. delete(w.activeConn, id)
  335. w.Unlock()
  336. }
  337. func (w *udpWorker) handlePackets() {
  338. receive := w.hub.Receive()
  339. for payload := range receive {
  340. w.callback(payload.Payload, payload.Source, payload.Target)
  341. }
  342. }
  343. func (w *udpWorker) clean() error {
  344. nowSec := time.Now().Unix()
  345. w.Lock()
  346. defer w.Unlock()
  347. if len(w.activeConn) == 0 {
  348. return errors.New("no more connections. stopping...")
  349. }
  350. for addr, conn := range w.activeConn {
  351. if nowSec-atomic.LoadInt64(&conn.lastActivityTime) > 2*60 {
  352. if !conn.inactive {
  353. conn.setInactive()
  354. delete(w.activeConn, addr)
  355. }
  356. conn.Close()
  357. }
  358. }
  359. if len(w.activeConn) == 0 {
  360. w.activeConn = make(map[connID]*udpConn, 16)
  361. }
  362. return nil
  363. }
  364. func (w *udpWorker) Start() error {
  365. w.activeConn = make(map[connID]*udpConn, 16)
  366. ctx := context.Background()
  367. h, err := udp.ListenUDP(ctx, w.address, w.port, w.stream, udp.HubCapacity(256))
  368. if err != nil {
  369. return err
  370. }
  371. w.cone = w.ctx.Value("cone").(bool)
  372. w.checker = &task.Periodic{
  373. Interval: time.Minute,
  374. Execute: w.clean,
  375. }
  376. w.hub = h
  377. go w.handlePackets()
  378. return nil
  379. }
  380. func (w *udpWorker) Close() error {
  381. w.Lock()
  382. defer w.Unlock()
  383. var errs []interface{}
  384. if w.hub != nil {
  385. if err := w.hub.Close(); err != nil {
  386. errs = append(errs, err)
  387. }
  388. }
  389. if w.checker != nil {
  390. if err := w.checker.Close(); err != nil {
  391. errs = append(errs, err)
  392. }
  393. }
  394. if err := common.Close(w.proxy); err != nil {
  395. errs = append(errs, err)
  396. }
  397. if len(errs) > 0 {
  398. return errors.New("failed to close all resources").Base(errors.New(serial.Concat(errs...)))
  399. }
  400. return nil
  401. }
  402. func (w *udpWorker) Port() net.Port {
  403. return w.port
  404. }
  405. func (w *udpWorker) Proxy() proxy.Inbound {
  406. return w.proxy
  407. }
  408. type dsWorker struct {
  409. address net.Address
  410. proxy proxy.Inbound
  411. stream *internet.MemoryStreamConfig
  412. tag string
  413. dispatcher routing.Dispatcher
  414. sniffingConfig *proxyman.SniffingConfig
  415. uplinkCounter stats.Counter
  416. downlinkCounter stats.Counter
  417. hub internet.Listener
  418. ctx context.Context
  419. }
  420. func (w *dsWorker) callback(conn stat.Connection) {
  421. ctx, cancel := context.WithCancel(w.ctx)
  422. sid := session.NewID()
  423. ctx = c.ContextWithID(ctx, sid)
  424. if w.uplinkCounter != nil || w.downlinkCounter != nil {
  425. conn = &stat.CounterConnection{
  426. Connection: conn,
  427. ReadCounter: w.uplinkCounter,
  428. WriteCounter: w.downlinkCounter,
  429. }
  430. }
  431. ctx = session.ContextWithInbound(ctx, &session.Inbound{
  432. Source: net.DestinationFromAddr(conn.RemoteAddr()),
  433. Local: net.DestinationFromAddr(conn.LocalAddr()),
  434. Gateway: net.UnixDestination(w.address),
  435. Tag: w.tag,
  436. Conn: conn,
  437. })
  438. content := new(session.Content)
  439. if w.sniffingConfig != nil {
  440. content.SniffingRequest.Enabled = w.sniffingConfig.Enabled
  441. content.SniffingRequest.OverrideDestinationForProtocol = w.sniffingConfig.DestinationOverride
  442. content.SniffingRequest.ExcludeForDomain = w.sniffingConfig.DomainsExcluded
  443. content.SniffingRequest.MetadataOnly = w.sniffingConfig.MetadataOnly
  444. content.SniffingRequest.RouteOnly = w.sniffingConfig.RouteOnly
  445. }
  446. ctx = session.ContextWithContent(ctx, content)
  447. if err := w.proxy.Process(ctx, net.Network_UNIX, conn, w.dispatcher); err != nil {
  448. errors.LogInfoInner(ctx, err, "connection ends")
  449. }
  450. cancel()
  451. if err := conn.Close(); err != nil {
  452. errors.LogInfoInner(ctx, err, "failed to close connection")
  453. }
  454. }
  455. func (w *dsWorker) Proxy() proxy.Inbound {
  456. return w.proxy
  457. }
  458. func (w *dsWorker) Port() net.Port {
  459. return net.Port(0)
  460. }
  461. func (w *dsWorker) Start() error {
  462. ctx := context.Background()
  463. hub, err := internet.ListenUnix(ctx, w.address, w.stream, func(conn stat.Connection) {
  464. go w.callback(conn)
  465. })
  466. if err != nil {
  467. return errors.New("failed to listen Unix Domain Socket on ", w.address).AtWarning().Base(err)
  468. }
  469. w.hub = hub
  470. return nil
  471. }
  472. func (w *dsWorker) Close() error {
  473. var errs []interface{}
  474. if w.hub != nil {
  475. if err := common.Close(w.hub); err != nil {
  476. errs = append(errs, err)
  477. }
  478. if err := common.Close(w.proxy); err != nil {
  479. errs = append(errs, err)
  480. }
  481. }
  482. if len(errs) > 0 {
  483. return errors.New("failed to close all resources").Base(errors.New(serial.Concat(errs...)))
  484. }
  485. return nil
  486. }
  487. func IsLocal(ip net.IP) bool {
  488. addrs, err := net.InterfaceAddrs()
  489. if err != nil {
  490. return false
  491. }
  492. for _, addr := range addrs {
  493. if ipnet, ok := addr.(*net.IPNet); ok {
  494. if ipnet.IP.Equal(ip) {
  495. return true
  496. }
  497. }
  498. }
  499. return false
  500. }