worker.go 13 KB

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