worker.go 14 KB

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