worker.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. package inbound
  2. import (
  3. "context"
  4. "strings"
  5. "sync"
  6. "sync/atomic"
  7. "time"
  8. "github.com/xtls/xray-core/app/proxyman"
  9. "github.com/xtls/xray-core/common"
  10. "github.com/xtls/xray-core/common/buf"
  11. c "github.com/xtls/xray-core/common/ctx"
  12. "github.com/xtls/xray-core/common/errors"
  13. "github.com/xtls/xray-core/common/net"
  14. "github.com/xtls/xray-core/common/serial"
  15. "github.com/xtls/xray-core/common/session"
  16. "github.com/xtls/xray-core/common/signal/done"
  17. "github.com/xtls/xray-core/common/task"
  18. "github.com/xtls/xray-core/features/routing"
  19. "github.com/xtls/xray-core/features/stats"
  20. "github.com/xtls/xray-core/proxy"
  21. "github.com/xtls/xray-core/transport/internet"
  22. "github.com/xtls/xray-core/transport/internet/stat"
  23. "github.com/xtls/xray-core/transport/internet/tcp"
  24. "github.com/xtls/xray-core/transport/internet/udp"
  25. "github.com/xtls/xray-core/transport/pipe"
  26. )
  27. type worker interface {
  28. Start() error
  29. Close() error
  30. Port() net.Port
  31. Proxy() proxy.Inbound
  32. }
  33. type tcpWorker struct {
  34. address net.Address
  35. port net.Port
  36. proxy proxy.Inbound
  37. stream *internet.MemoryStreamConfig
  38. recvOrigDest bool
  39. tag string
  40. dispatcher routing.Dispatcher
  41. sniffingConfig *proxyman.SniffingConfig
  42. uplinkCounter stats.Counter
  43. downlinkCounter stats.Counter
  44. hub internet.Listener
  45. ctx context.Context
  46. }
  47. func getTProxyType(s *internet.MemoryStreamConfig) internet.SocketConfig_TProxyMode {
  48. if s == nil || s.SocketSettings == nil {
  49. return internet.SocketConfig_Off
  50. }
  51. return s.SocketSettings.Tproxy
  52. }
  53. func (w *tcpWorker) callback(conn stat.Connection) {
  54. ctx, cancel := context.WithCancel(w.ctx)
  55. sid := session.NewID()
  56. ctx = c.ContextWithID(ctx, sid)
  57. outbounds := []*session.Outbound{{}}
  58. if w.recvOrigDest {
  59. var dest net.Destination
  60. switch getTProxyType(w.stream) {
  61. case internet.SocketConfig_Redirect:
  62. d, err := tcp.GetOriginalDestination(conn)
  63. if err != nil {
  64. errors.LogInfoInner(ctx, err, "failed to get original destination")
  65. } else {
  66. dest = d
  67. }
  68. case internet.SocketConfig_TProxy:
  69. dest = net.DestinationFromAddr(conn.LocalAddr())
  70. }
  71. if dest.IsValid() {
  72. outbounds[0].Target = dest
  73. }
  74. }
  75. ctx = session.ContextWithOutbounds(ctx, outbounds)
  76. if w.uplinkCounter != nil || w.downlinkCounter != nil {
  77. conn = &stat.CounterConnection{
  78. Connection: conn,
  79. ReadCounter: w.uplinkCounter,
  80. WriteCounter: w.downlinkCounter,
  81. }
  82. }
  83. ctx = session.ContextWithInbound(ctx, &session.Inbound{
  84. Source: net.DestinationFromAddr(conn.RemoteAddr()),
  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. ctx = session.ContextWithInbound(ctx, &session.Inbound{
  275. Source: source,
  276. Gateway: net.UDPDestination(w.address, w.port),
  277. Tag: w.tag,
  278. })
  279. content := new(session.Content)
  280. if w.sniffingConfig != nil {
  281. content.SniffingRequest.Enabled = w.sniffingConfig.Enabled
  282. content.SniffingRequest.OverrideDestinationForProtocol = w.sniffingConfig.DestinationOverride
  283. content.SniffingRequest.MetadataOnly = w.sniffingConfig.MetadataOnly
  284. content.SniffingRequest.RouteOnly = w.sniffingConfig.RouteOnly
  285. }
  286. ctx = session.ContextWithContent(ctx, content)
  287. if err := w.proxy.Process(ctx, net.Network_UDP, conn, w.dispatcher); err != nil {
  288. errors.LogInfoInner(ctx, err, "connection ends")
  289. }
  290. conn.Close()
  291. // conn not removed by checker TODO may be lock worker here is better
  292. if !conn.inactive {
  293. conn.setInactive()
  294. w.removeConn(id)
  295. }
  296. }()
  297. }
  298. }
  299. func (w *udpWorker) removeConn(id connID) {
  300. w.Lock()
  301. delete(w.activeConn, id)
  302. w.Unlock()
  303. }
  304. func (w *udpWorker) handlePackets() {
  305. receive := w.hub.Receive()
  306. for payload := range receive {
  307. w.callback(payload.Payload, payload.Source, payload.Target)
  308. }
  309. }
  310. func (w *udpWorker) clean() error {
  311. nowSec := time.Now().Unix()
  312. w.Lock()
  313. defer w.Unlock()
  314. if len(w.activeConn) == 0 {
  315. return errors.New("no more connections. stopping...")
  316. }
  317. for addr, conn := range w.activeConn {
  318. if nowSec-atomic.LoadInt64(&conn.lastActivityTime) > 2*60 {
  319. if !conn.inactive {
  320. conn.setInactive()
  321. delete(w.activeConn, addr)
  322. }
  323. conn.Close()
  324. }
  325. }
  326. if len(w.activeConn) == 0 {
  327. w.activeConn = make(map[connID]*udpConn, 16)
  328. }
  329. return nil
  330. }
  331. func (w *udpWorker) Start() error {
  332. w.activeConn = make(map[connID]*udpConn, 16)
  333. ctx := context.Background()
  334. h, err := udp.ListenUDP(ctx, w.address, w.port, w.stream, udp.HubCapacity(256))
  335. if err != nil {
  336. return err
  337. }
  338. w.cone = w.ctx.Value("cone").(bool)
  339. w.checker = &task.Periodic{
  340. Interval: time.Minute,
  341. Execute: w.clean,
  342. }
  343. w.hub = h
  344. go w.handlePackets()
  345. return nil
  346. }
  347. func (w *udpWorker) Close() error {
  348. w.Lock()
  349. defer w.Unlock()
  350. var errs []interface{}
  351. if w.hub != nil {
  352. if err := w.hub.Close(); err != nil {
  353. errs = append(errs, err)
  354. }
  355. }
  356. if w.checker != nil {
  357. if err := w.checker.Close(); err != nil {
  358. errs = append(errs, err)
  359. }
  360. }
  361. if err := common.Close(w.proxy); err != nil {
  362. errs = append(errs, err)
  363. }
  364. if len(errs) > 0 {
  365. return errors.New("failed to close all resources").Base(errors.New(serial.Concat(errs...)))
  366. }
  367. return nil
  368. }
  369. func (w *udpWorker) Port() net.Port {
  370. return w.port
  371. }
  372. func (w *udpWorker) Proxy() proxy.Inbound {
  373. return w.proxy
  374. }
  375. type dsWorker struct {
  376. address net.Address
  377. proxy proxy.Inbound
  378. stream *internet.MemoryStreamConfig
  379. tag string
  380. dispatcher routing.Dispatcher
  381. sniffingConfig *proxyman.SniffingConfig
  382. uplinkCounter stats.Counter
  383. downlinkCounter stats.Counter
  384. hub internet.Listener
  385. ctx context.Context
  386. }
  387. func (w *dsWorker) callback(conn stat.Connection) {
  388. ctx, cancel := context.WithCancel(w.ctx)
  389. sid := session.NewID()
  390. ctx = c.ContextWithID(ctx, sid)
  391. if w.uplinkCounter != nil || w.downlinkCounter != nil {
  392. conn = &stat.CounterConnection{
  393. Connection: conn,
  394. ReadCounter: w.uplinkCounter,
  395. WriteCounter: w.downlinkCounter,
  396. }
  397. }
  398. // For most of time, unix obviously have no source addr. But if we leave it empty, it will cause panic.
  399. // So we use gateway as source for log.
  400. // However, there are some special situations where a valid source address might be available.
  401. // Such as the source address parsed from X-Forwarded-For in websocket.
  402. // In that case, we keep it.
  403. var source net.Destination
  404. if !strings.Contains(conn.RemoteAddr().String(), "unix") {
  405. source = net.DestinationFromAddr(conn.RemoteAddr())
  406. } else {
  407. source = net.UnixDestination(w.address)
  408. }
  409. ctx = session.ContextWithInbound(ctx, &session.Inbound{
  410. Source: source,
  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. }