worker.go 13 KB

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