worker.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. package inbound
  2. import (
  3. "context"
  4. "sync"
  5. "sync/atomic"
  6. "time"
  7. "v2ray.com/core/app/proxyman"
  8. "v2ray.com/core/common"
  9. "v2ray.com/core/common/buf"
  10. "v2ray.com/core/common/net"
  11. "v2ray.com/core/common/serial"
  12. "v2ray.com/core/common/session"
  13. "v2ray.com/core/common/signal/done"
  14. "v2ray.com/core/common/task"
  15. "v2ray.com/core/features/routing"
  16. "v2ray.com/core/features/stats"
  17. "v2ray.com/core/proxy"
  18. "v2ray.com/core/transport/internet"
  19. "v2ray.com/core/transport/internet/tcp"
  20. "v2ray.com/core/transport/internet/udp"
  21. "v2ray.com/core/transport/pipe"
  22. )
  23. type worker interface {
  24. Start() error
  25. Close() error
  26. Port() net.Port
  27. Proxy() proxy.Inbound
  28. }
  29. type tcpWorker struct {
  30. address net.Address
  31. port net.Port
  32. proxy proxy.Inbound
  33. stream *internet.MemoryStreamConfig
  34. recvOrigDest bool
  35. tag string
  36. dispatcher routing.Dispatcher
  37. sniffingConfig *proxyman.SniffingConfig
  38. uplinkCounter stats.Counter
  39. downlinkCounter stats.Counter
  40. hub internet.Listener
  41. ctx context.Context
  42. }
  43. func getTProxyType(s *internet.MemoryStreamConfig) internet.SocketConfig_TProxyMode {
  44. if s == nil || s.SocketSettings == nil {
  45. return internet.SocketConfig_Off
  46. }
  47. return s.SocketSettings.Tproxy
  48. }
  49. func (w *tcpWorker) callback(conn internet.Connection) {
  50. ctx, cancel := context.WithCancel(w.ctx)
  51. sid := session.NewID()
  52. ctx = session.ContextWithID(ctx, sid)
  53. if w.recvOrigDest {
  54. var dest net.Destination
  55. switch getTProxyType(w.stream) {
  56. case internet.SocketConfig_Redirect:
  57. d, err := tcp.GetOriginalDestination(conn)
  58. if err != nil {
  59. newError("failed to get original destination").Base(err).WriteToLog(session.ExportIDToError(ctx))
  60. } else {
  61. dest = d
  62. }
  63. case internet.SocketConfig_TProxy:
  64. dest = net.DestinationFromAddr(conn.LocalAddr())
  65. }
  66. if dest.IsValid() {
  67. ctx = session.ContextWithOutbound(ctx, &session.Outbound{
  68. Target: dest,
  69. })
  70. }
  71. }
  72. ctx = session.ContextWithInbound(ctx, &session.Inbound{
  73. Source: net.DestinationFromAddr(conn.RemoteAddr()),
  74. Gateway: net.TCPDestination(w.address, w.port),
  75. Tag: w.tag,
  76. })
  77. content := new(session.Content)
  78. if w.sniffingConfig != nil {
  79. content.SniffingRequest.Enabled = w.sniffingConfig.Enabled
  80. content.SniffingRequest.OverrideDestinationForProtocol = w.sniffingConfig.DestinationOverride
  81. content.SniffingRequest.MetadataOnly = w.sniffingConfig.MetadataOnly
  82. }
  83. ctx = session.ContextWithContent(ctx, content)
  84. if w.uplinkCounter != nil || w.downlinkCounter != nil {
  85. conn = &internet.StatCouterConnection{
  86. Connection: conn,
  87. ReadCounter: w.uplinkCounter,
  88. WriteCounter: w.downlinkCounter,
  89. }
  90. }
  91. if err := w.proxy.Process(ctx, net.Network_TCP, conn, w.dispatcher); err != nil {
  92. newError("connection ends").Base(err).WriteToLog(session.ExportIDToError(ctx))
  93. }
  94. cancel()
  95. if err := conn.Close(); err != nil {
  96. newError("failed to close connection").Base(err).WriteToLog(session.ExportIDToError(ctx))
  97. }
  98. }
  99. func (w *tcpWorker) Proxy() proxy.Inbound {
  100. return w.proxy
  101. }
  102. func (w *tcpWorker) Start() error {
  103. ctx := context.Background()
  104. hub, err := internet.ListenTCP(ctx, w.address, w.port, w.stream, func(conn internet.Connection) {
  105. go w.callback(conn)
  106. })
  107. if err != nil {
  108. return newError("failed to listen TCP on ", w.port).AtWarning().Base(err)
  109. }
  110. w.hub = hub
  111. return nil
  112. }
  113. func (w *tcpWorker) Close() error {
  114. var errors []interface{}
  115. if w.hub != nil {
  116. if err := common.Close(w.hub); err != nil {
  117. errors = append(errors, err)
  118. }
  119. if err := common.Close(w.proxy); err != nil {
  120. errors = append(errors, err)
  121. }
  122. }
  123. if len(errors) > 0 {
  124. return newError("failed to close all resources").Base(newError(serial.Concat(errors...)))
  125. }
  126. return nil
  127. }
  128. func (w *tcpWorker) Port() net.Port {
  129. return w.port
  130. }
  131. type udpConn struct {
  132. lastActivityTime int64 // in seconds
  133. reader buf.Reader
  134. writer buf.Writer
  135. output func([]byte) (int, error)
  136. remote net.Addr
  137. local net.Addr
  138. done *done.Instance
  139. uplink stats.Counter
  140. downlink stats.Counter
  141. }
  142. func (c *udpConn) updateActivity() {
  143. atomic.StoreInt64(&c.lastActivityTime, time.Now().Unix())
  144. }
  145. // ReadMultiBuffer implements buf.Reader
  146. func (c *udpConn) ReadMultiBuffer() (buf.MultiBuffer, error) {
  147. mb, err := c.reader.ReadMultiBuffer()
  148. if err != nil {
  149. return nil, err
  150. }
  151. c.updateActivity()
  152. if c.uplink != nil {
  153. c.uplink.Add(int64(mb.Len()))
  154. }
  155. return mb, nil
  156. }
  157. func (c *udpConn) Read(buf []byte) (int, error) {
  158. panic("not implemented")
  159. }
  160. // Write implements io.Writer.
  161. func (c *udpConn) Write(buf []byte) (int, error) {
  162. n, err := c.output(buf)
  163. if c.downlink != nil {
  164. c.downlink.Add(int64(n))
  165. }
  166. if err == nil {
  167. c.updateActivity()
  168. }
  169. return n, err
  170. }
  171. func (c *udpConn) Close() error {
  172. common.Must(c.done.Close())
  173. common.Must(common.Close(c.writer))
  174. return nil
  175. }
  176. func (c *udpConn) RemoteAddr() net.Addr {
  177. return c.remote
  178. }
  179. func (c *udpConn) LocalAddr() net.Addr {
  180. return c.local
  181. }
  182. func (*udpConn) SetDeadline(time.Time) error {
  183. return nil
  184. }
  185. func (*udpConn) SetReadDeadline(time.Time) error {
  186. return nil
  187. }
  188. func (*udpConn) SetWriteDeadline(time.Time) error {
  189. return nil
  190. }
  191. type connID struct {
  192. src net.Destination
  193. dest net.Destination
  194. }
  195. type udpWorker struct {
  196. sync.RWMutex
  197. proxy proxy.Inbound
  198. hub *udp.Hub
  199. address net.Address
  200. port net.Port
  201. tag string
  202. stream *internet.MemoryStreamConfig
  203. dispatcher routing.Dispatcher
  204. sniffingConfig *proxyman.SniffingConfig
  205. uplinkCounter stats.Counter
  206. downlinkCounter stats.Counter
  207. checker *task.Periodic
  208. activeConn map[connID]*udpConn
  209. ctx context.Context
  210. }
  211. func (w *udpWorker) getConnection(id connID) (*udpConn, bool) {
  212. w.Lock()
  213. defer w.Unlock()
  214. if conn, found := w.activeConn[id]; found && !conn.done.Done() {
  215. return conn, true
  216. }
  217. pReader, pWriter := pipe.New(pipe.DiscardOverflow(), pipe.WithSizeLimit(16*1024))
  218. conn := &udpConn{
  219. reader: pReader,
  220. writer: pWriter,
  221. output: func(b []byte) (int, error) {
  222. return w.hub.WriteTo(b, id.src)
  223. },
  224. remote: &net.UDPAddr{
  225. IP: id.src.Address.IP(),
  226. Port: int(id.src.Port),
  227. },
  228. local: &net.UDPAddr{
  229. IP: w.address.IP(),
  230. Port: int(w.port),
  231. },
  232. done: done.New(),
  233. uplink: w.uplinkCounter,
  234. downlink: w.downlinkCounter,
  235. }
  236. w.activeConn[id] = conn
  237. conn.updateActivity()
  238. return conn, false
  239. }
  240. func (w *udpWorker) callback(b *buf.Buffer, source net.Destination, originalDest net.Destination) {
  241. id := connID{
  242. src: source,
  243. }
  244. if originalDest.IsValid() {
  245. id.dest = originalDest
  246. }
  247. conn, existing := w.getConnection(id)
  248. // payload will be discarded in pipe is full.
  249. conn.writer.WriteMultiBuffer(buf.MultiBuffer{b})
  250. if !existing {
  251. common.Must(w.checker.Start())
  252. go func() {
  253. ctx := w.ctx
  254. sid := session.NewID()
  255. ctx = session.ContextWithID(ctx, sid)
  256. if originalDest.IsValid() {
  257. ctx = session.ContextWithOutbound(ctx, &session.Outbound{
  258. Target: originalDest,
  259. })
  260. }
  261. ctx = session.ContextWithInbound(ctx, &session.Inbound{
  262. Source: source,
  263. Gateway: net.UDPDestination(w.address, w.port),
  264. Tag: w.tag,
  265. })
  266. content := new(session.Content)
  267. if w.sniffingConfig != nil {
  268. content.SniffingRequest.Enabled = w.sniffingConfig.Enabled
  269. content.SniffingRequest.OverrideDestinationForProtocol = w.sniffingConfig.DestinationOverride
  270. content.SniffingRequest.MetadataOnly = w.sniffingConfig.MetadataOnly
  271. }
  272. ctx = session.ContextWithContent(ctx, content)
  273. if err := w.proxy.Process(ctx, net.Network_UDP, conn, w.dispatcher); err != nil {
  274. newError("connection ends").Base(err).WriteToLog(session.ExportIDToError(ctx))
  275. }
  276. conn.Close()
  277. w.removeConn(id)
  278. }()
  279. }
  280. }
  281. func (w *udpWorker) removeConn(id connID) {
  282. w.Lock()
  283. delete(w.activeConn, id)
  284. w.Unlock()
  285. }
  286. func (w *udpWorker) handlePackets() {
  287. receive := w.hub.Receive()
  288. for payload := range receive {
  289. w.callback(payload.Payload, payload.Source, payload.Target)
  290. }
  291. }
  292. func (w *udpWorker) clean() error {
  293. nowSec := time.Now().Unix()
  294. w.Lock()
  295. defer w.Unlock()
  296. if len(w.activeConn) == 0 {
  297. return newError("no more connections. stopping...")
  298. }
  299. for addr, conn := range w.activeConn {
  300. if nowSec-atomic.LoadInt64(&conn.lastActivityTime) > 8 { // TODO Timeout too small
  301. delete(w.activeConn, addr)
  302. conn.Close()
  303. }
  304. }
  305. if len(w.activeConn) == 0 {
  306. w.activeConn = make(map[connID]*udpConn, 16)
  307. }
  308. return nil
  309. }
  310. func (w *udpWorker) Start() error {
  311. w.activeConn = make(map[connID]*udpConn, 16)
  312. ctx := context.Background()
  313. h, err := udp.ListenUDP(ctx, w.address, w.port, w.stream, udp.HubCapacity(256))
  314. if err != nil {
  315. return err
  316. }
  317. w.checker = &task.Periodic{
  318. Interval: time.Second * 16,
  319. Execute: w.clean,
  320. }
  321. w.hub = h
  322. go w.handlePackets()
  323. return nil
  324. }
  325. func (w *udpWorker) Close() error {
  326. w.Lock()
  327. defer w.Unlock()
  328. var errors []interface{}
  329. if w.hub != nil {
  330. if err := w.hub.Close(); err != nil {
  331. errors = append(errors, err)
  332. }
  333. }
  334. if w.checker != nil {
  335. if err := w.checker.Close(); err != nil {
  336. errors = append(errors, err)
  337. }
  338. }
  339. if err := common.Close(w.proxy); err != nil {
  340. errors = append(errors, err)
  341. }
  342. if len(errors) > 0 {
  343. return newError("failed to close all resources").Base(newError(serial.Concat(errors...)))
  344. }
  345. return nil
  346. }
  347. func (w *udpWorker) Port() net.Port {
  348. return w.port
  349. }
  350. func (w *udpWorker) Proxy() proxy.Inbound {
  351. return w.proxy
  352. }
  353. type dsWorker struct {
  354. address net.Address
  355. proxy proxy.Inbound
  356. stream *internet.MemoryStreamConfig
  357. tag string
  358. dispatcher routing.Dispatcher
  359. sniffingConfig *proxyman.SniffingConfig
  360. uplinkCounter stats.Counter
  361. downlinkCounter stats.Counter
  362. hub internet.Listener
  363. ctx context.Context
  364. }
  365. func (w *dsWorker) callback(conn internet.Connection) {
  366. ctx, cancel := context.WithCancel(w.ctx)
  367. sid := session.NewID()
  368. ctx = session.ContextWithID(ctx, sid)
  369. ctx = session.ContextWithInbound(ctx, &session.Inbound{
  370. Source: net.DestinationFromAddr(conn.RemoteAddr()),
  371. Gateway: net.UnixDestination(w.address),
  372. Tag: w.tag,
  373. })
  374. content := new(session.Content)
  375. if w.sniffingConfig != nil {
  376. content.SniffingRequest.Enabled = w.sniffingConfig.Enabled
  377. content.SniffingRequest.OverrideDestinationForProtocol = w.sniffingConfig.DestinationOverride
  378. content.SniffingRequest.MetadataOnly = w.sniffingConfig.MetadataOnly
  379. }
  380. ctx = session.ContextWithContent(ctx, content)
  381. if w.uplinkCounter != nil || w.downlinkCounter != nil {
  382. conn = &internet.StatCouterConnection{
  383. Connection: conn,
  384. ReadCounter: w.uplinkCounter,
  385. WriteCounter: w.downlinkCounter,
  386. }
  387. }
  388. if err := w.proxy.Process(ctx, net.Network_UNIX, conn, w.dispatcher); err != nil {
  389. newError("connection ends").Base(err).WriteToLog(session.ExportIDToError(ctx))
  390. }
  391. cancel()
  392. if err := conn.Close(); err != nil {
  393. newError("failed to close connection").Base(err).WriteToLog(session.ExportIDToError(ctx))
  394. }
  395. }
  396. func (w *dsWorker) Proxy() proxy.Inbound {
  397. return w.proxy
  398. }
  399. func (w *dsWorker) Port() net.Port {
  400. return net.Port(0)
  401. }
  402. func (w *dsWorker) Start() error {
  403. ctx := context.Background()
  404. hub, err := internet.ListenUnix(ctx, w.address, w.stream, func(conn internet.Connection) {
  405. go w.callback(conn)
  406. })
  407. if err != nil {
  408. return newError("failed to listen Unix Domain Socket on ", w.address).AtWarning().Base(err)
  409. }
  410. w.hub = hub
  411. return nil
  412. }
  413. func (w *dsWorker) Close() error {
  414. var errors []interface{}
  415. if w.hub != nil {
  416. if err := common.Close(w.hub); err != nil {
  417. errors = append(errors, err)
  418. }
  419. if err := common.Close(w.proxy); err != nil {
  420. errors = append(errors, err)
  421. }
  422. }
  423. if len(errors) > 0 {
  424. return newError("failed to close all resources").Base(newError(serial.Concat(errors...)))
  425. }
  426. return nil
  427. }