worker.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. package inbound
  2. import (
  3. "context"
  4. "io"
  5. "net"
  6. "sync"
  7. "sync/atomic"
  8. "time"
  9. "v2ray.com/core/app/dispatcher"
  10. "v2ray.com/core/app/log"
  11. "v2ray.com/core/common/buf"
  12. v2net "v2ray.com/core/common/net"
  13. "v2ray.com/core/proxy"
  14. "v2ray.com/core/transport/internet"
  15. "v2ray.com/core/transport/internet/tcp"
  16. "v2ray.com/core/transport/internet/udp"
  17. )
  18. type worker interface {
  19. Start() error
  20. Close()
  21. Port() v2net.Port
  22. Proxy() proxy.Inbound
  23. }
  24. type tcpWorker struct {
  25. address v2net.Address
  26. port v2net.Port
  27. proxy proxy.Inbound
  28. stream *internet.StreamConfig
  29. recvOrigDest bool
  30. tag string
  31. dispatcher dispatcher.Interface
  32. ctx context.Context
  33. cancel context.CancelFunc
  34. hub internet.Listener
  35. }
  36. func (w *tcpWorker) callback(conn internet.Connection) {
  37. ctx, cancel := context.WithCancel(w.ctx)
  38. if w.recvOrigDest {
  39. dest := tcp.GetOriginalDestination(conn)
  40. if dest.IsValid() {
  41. ctx = proxy.ContextWithOriginalTarget(ctx, dest)
  42. }
  43. }
  44. if len(w.tag) > 0 {
  45. ctx = proxy.ContextWithInboundTag(ctx, w.tag)
  46. }
  47. ctx = proxy.ContextWithInboundEntryPoint(ctx, v2net.TCPDestination(w.address, w.port))
  48. ctx = proxy.ContextWithSource(ctx, v2net.DestinationFromAddr(conn.RemoteAddr()))
  49. if err := w.proxy.Process(ctx, v2net.Network_TCP, conn, w.dispatcher); err != nil {
  50. log.Trace(newError("connection ends").Base(err))
  51. }
  52. cancel()
  53. conn.Close()
  54. }
  55. func (w *tcpWorker) Proxy() proxy.Inbound {
  56. return w.proxy
  57. }
  58. func (w *tcpWorker) Start() error {
  59. ctx, cancel := context.WithCancel(context.Background())
  60. w.ctx = ctx
  61. w.cancel = cancel
  62. ctx = internet.ContextWithStreamSettings(ctx, w.stream)
  63. conns := make(chan internet.Connection, 16)
  64. hub, err := internet.ListenTCP(ctx, w.address, w.port, conns)
  65. if err != nil {
  66. return err
  67. }
  68. go w.handleConnections(conns)
  69. w.hub = hub
  70. return nil
  71. }
  72. func (w *tcpWorker) handleConnections(conns <-chan internet.Connection) {
  73. for {
  74. select {
  75. case <-w.ctx.Done():
  76. w.hub.Close()
  77. L:
  78. for {
  79. select {
  80. case conn := <-conns:
  81. conn.Close()
  82. default:
  83. break L
  84. }
  85. }
  86. return
  87. case conn := <-conns:
  88. go w.callback(conn)
  89. }
  90. }
  91. }
  92. func (w *tcpWorker) Close() {
  93. if w.hub != nil {
  94. w.cancel()
  95. }
  96. }
  97. func (w *tcpWorker) Port() v2net.Port {
  98. return w.port
  99. }
  100. type udpConn struct {
  101. lastActivityTime int64 // in seconds
  102. input chan *buf.Buffer
  103. output func([]byte) (int, error)
  104. remote net.Addr
  105. local net.Addr
  106. cancel context.CancelFunc
  107. }
  108. func (c *udpConn) updateActivity() {
  109. atomic.StoreInt64(&c.lastActivityTime, time.Now().Unix())
  110. }
  111. func (c *udpConn) Read(buf []byte) (int, error) {
  112. in, open := <-c.input
  113. if !open {
  114. return 0, io.EOF
  115. }
  116. defer in.Release()
  117. c.updateActivity()
  118. return copy(buf, in.Bytes()), nil
  119. }
  120. func (c *udpConn) Write(buf []byte) (int, error) {
  121. n, err := c.output(buf)
  122. if err == nil {
  123. c.updateActivity()
  124. }
  125. return n, err
  126. }
  127. func (c *udpConn) Close() error {
  128. return nil
  129. }
  130. func (c *udpConn) RemoteAddr() net.Addr {
  131. return c.remote
  132. }
  133. func (c *udpConn) LocalAddr() net.Addr {
  134. return c.remote
  135. }
  136. func (*udpConn) SetDeadline(time.Time) error {
  137. return nil
  138. }
  139. func (*udpConn) SetReadDeadline(time.Time) error {
  140. return nil
  141. }
  142. func (*udpConn) SetWriteDeadline(time.Time) error {
  143. return nil
  144. }
  145. type udpWorker struct {
  146. sync.RWMutex
  147. proxy proxy.Inbound
  148. hub *udp.Hub
  149. address v2net.Address
  150. port v2net.Port
  151. recvOrigDest bool
  152. tag string
  153. dispatcher dispatcher.Interface
  154. ctx context.Context
  155. cancel context.CancelFunc
  156. activeConn map[v2net.Destination]*udpConn
  157. }
  158. func (w *udpWorker) getConnection(src v2net.Destination) (*udpConn, bool) {
  159. w.Lock()
  160. defer w.Unlock()
  161. if conn, found := w.activeConn[src]; found {
  162. return conn, true
  163. }
  164. conn := &udpConn{
  165. input: make(chan *buf.Buffer, 32),
  166. output: func(b []byte) (int, error) {
  167. return w.hub.WriteTo(b, src)
  168. },
  169. remote: &net.UDPAddr{
  170. IP: src.Address.IP(),
  171. Port: int(src.Port),
  172. },
  173. local: &net.UDPAddr{
  174. IP: w.address.IP(),
  175. Port: int(w.port),
  176. },
  177. }
  178. w.activeConn[src] = conn
  179. conn.updateActivity()
  180. return conn, false
  181. }
  182. func (w *udpWorker) callback(b *buf.Buffer, source v2net.Destination, originalDest v2net.Destination) {
  183. conn, existing := w.getConnection(source)
  184. select {
  185. case conn.input <- b:
  186. default:
  187. b.Release()
  188. }
  189. if !existing {
  190. go func() {
  191. ctx := w.ctx
  192. ctx, cancel := context.WithCancel(ctx)
  193. conn.cancel = cancel
  194. if originalDest.IsValid() {
  195. ctx = proxy.ContextWithOriginalTarget(ctx, originalDest)
  196. }
  197. if len(w.tag) > 0 {
  198. ctx = proxy.ContextWithInboundTag(ctx, w.tag)
  199. }
  200. ctx = proxy.ContextWithSource(ctx, source)
  201. ctx = proxy.ContextWithInboundEntryPoint(ctx, v2net.UDPDestination(w.address, w.port))
  202. if err := w.proxy.Process(ctx, v2net.Network_UDP, conn, w.dispatcher); err != nil {
  203. log.Trace(newError("connection ends").Base(err))
  204. }
  205. w.removeConn(source)
  206. cancel()
  207. }()
  208. }
  209. }
  210. func (w *udpWorker) removeConn(src v2net.Destination) {
  211. w.Lock()
  212. delete(w.activeConn, src)
  213. w.Unlock()
  214. }
  215. func (w *udpWorker) Start() error {
  216. w.activeConn = make(map[v2net.Destination]*udpConn)
  217. ctx, cancel := context.WithCancel(context.Background())
  218. w.ctx = ctx
  219. w.cancel = cancel
  220. h, err := udp.ListenUDP(w.address, w.port, udp.ListenOption{
  221. Callback: w.callback,
  222. ReceiveOriginalDest: w.recvOrigDest,
  223. })
  224. if err != nil {
  225. return err
  226. }
  227. go w.monitor()
  228. w.hub = h
  229. return nil
  230. }
  231. func (w *udpWorker) Close() {
  232. if w.hub != nil {
  233. w.hub.Close()
  234. w.cancel()
  235. }
  236. }
  237. func (w *udpWorker) monitor() {
  238. for {
  239. select {
  240. case <-w.ctx.Done():
  241. return
  242. case <-time.After(time.Second * 16):
  243. nowSec := time.Now().Unix()
  244. w.Lock()
  245. for addr, conn := range w.activeConn {
  246. if nowSec-atomic.LoadInt64(&conn.lastActivityTime) > 8 {
  247. delete(w.activeConn, addr)
  248. conn.cancel()
  249. }
  250. }
  251. w.Unlock()
  252. }
  253. }
  254. }
  255. func (w *udpWorker) Port() v2net.Port {
  256. return w.port
  257. }
  258. func (w *udpWorker) Proxy() proxy.Inbound {
  259. return w.proxy
  260. }