worker.go 12 KB

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