worker.go 6.0 KB

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