worker.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. // Write implements io.Writer.
  124. func (c *udpConn) Write(buf []byte) (int, error) {
  125. n, err := c.output(buf)
  126. if err == nil {
  127. c.updateActivity()
  128. }
  129. return n, err
  130. }
  131. func (c *udpConn) Close() error {
  132. return nil
  133. }
  134. func (c *udpConn) RemoteAddr() net.Addr {
  135. return c.remote
  136. }
  137. func (c *udpConn) LocalAddr() net.Addr {
  138. return c.remote
  139. }
  140. func (*udpConn) SetDeadline(time.Time) error {
  141. return nil
  142. }
  143. func (*udpConn) SetReadDeadline(time.Time) error {
  144. return nil
  145. }
  146. func (*udpConn) SetWriteDeadline(time.Time) error {
  147. return nil
  148. }
  149. type udpWorker struct {
  150. sync.RWMutex
  151. proxy proxy.Inbound
  152. hub *udp.Hub
  153. address v2net.Address
  154. port v2net.Port
  155. recvOrigDest bool
  156. tag string
  157. dispatcher dispatcher.Interface
  158. ctx context.Context
  159. cancel context.CancelFunc
  160. activeConn map[v2net.Destination]*udpConn
  161. }
  162. func (w *udpWorker) getConnection(src v2net.Destination) (*udpConn, bool) {
  163. w.Lock()
  164. defer w.Unlock()
  165. if conn, found := w.activeConn[src]; found {
  166. return conn, true
  167. }
  168. conn := &udpConn{
  169. input: make(chan *buf.Buffer, 32),
  170. output: func(b []byte) (int, error) {
  171. return w.hub.WriteTo(b, src)
  172. },
  173. remote: &net.UDPAddr{
  174. IP: src.Address.IP(),
  175. Port: int(src.Port),
  176. },
  177. local: &net.UDPAddr{
  178. IP: w.address.IP(),
  179. Port: int(w.port),
  180. },
  181. }
  182. w.activeConn[src] = conn
  183. conn.updateActivity()
  184. return conn, false
  185. }
  186. func (w *udpWorker) callback(b *buf.Buffer, source v2net.Destination, originalDest v2net.Destination) {
  187. conn, existing := w.getConnection(source)
  188. select {
  189. case conn.input <- b:
  190. default:
  191. b.Release()
  192. }
  193. if !existing {
  194. go func() {
  195. ctx := w.ctx
  196. ctx, cancel := context.WithCancel(ctx)
  197. conn.cancel = cancel
  198. if originalDest.IsValid() {
  199. ctx = proxy.ContextWithOriginalTarget(ctx, originalDest)
  200. }
  201. if len(w.tag) > 0 {
  202. ctx = proxy.ContextWithInboundTag(ctx, w.tag)
  203. }
  204. ctx = proxy.ContextWithSource(ctx, source)
  205. ctx = proxy.ContextWithInboundEntryPoint(ctx, v2net.UDPDestination(w.address, w.port))
  206. if err := w.proxy.Process(ctx, v2net.Network_UDP, conn, w.dispatcher); err != nil {
  207. log.Trace(newError("connection ends").Base(err))
  208. }
  209. w.removeConn(source)
  210. cancel()
  211. }()
  212. }
  213. }
  214. func (w *udpWorker) removeConn(src v2net.Destination) {
  215. w.Lock()
  216. delete(w.activeConn, src)
  217. w.Unlock()
  218. }
  219. func (w *udpWorker) Start() error {
  220. w.activeConn = make(map[v2net.Destination]*udpConn)
  221. ctx, cancel := context.WithCancel(context.Background())
  222. w.ctx = ctx
  223. w.cancel = cancel
  224. h, err := udp.ListenUDP(w.address, w.port, udp.ListenOption{
  225. Callback: w.callback,
  226. ReceiveOriginalDest: w.recvOrigDest,
  227. })
  228. if err != nil {
  229. return err
  230. }
  231. go w.monitor()
  232. w.hub = h
  233. return nil
  234. }
  235. func (w *udpWorker) Close() {
  236. if w.hub != nil {
  237. w.hub.Close()
  238. w.cancel()
  239. }
  240. }
  241. func (w *udpWorker) monitor() {
  242. for {
  243. select {
  244. case <-w.ctx.Done():
  245. return
  246. case <-time.After(time.Second * 16):
  247. nowSec := time.Now().Unix()
  248. w.Lock()
  249. for addr, conn := range w.activeConn {
  250. if nowSec-atomic.LoadInt64(&conn.lastActivityTime) > 8 {
  251. delete(w.activeConn, addr)
  252. conn.cancel()
  253. }
  254. }
  255. w.Unlock()
  256. }
  257. }
  258. }
  259. func (w *udpWorker) Port() v2net.Port {
  260. return w.port
  261. }
  262. func (w *udpWorker) Proxy() proxy.Inbound {
  263. return w.proxy
  264. }