worker.go 6.2 KB

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