worker.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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 connId struct {
  154. src net.Destination
  155. dest net.Destination
  156. }
  157. type udpWorker struct {
  158. sync.RWMutex
  159. proxy proxy.Inbound
  160. hub *udp.Hub
  161. address net.Address
  162. port net.Port
  163. recvOrigDest bool
  164. tag string
  165. dispatcher dispatcher.Interface
  166. ctx context.Context
  167. cancel context.CancelFunc
  168. activeConn map[connId]*udpConn
  169. }
  170. func (w *udpWorker) getConnection(id connId) (*udpConn, bool) {
  171. w.Lock()
  172. defer w.Unlock()
  173. if conn, found := w.activeConn[id]; found {
  174. return conn, true
  175. }
  176. conn := &udpConn{
  177. input: make(chan *buf.Buffer, 32),
  178. output: func(b []byte) (int, error) {
  179. return w.hub.WriteTo(b, id.src)
  180. },
  181. remote: &net.UDPAddr{
  182. IP: id.src.Address.IP(),
  183. Port: int(id.src.Port),
  184. },
  185. local: &net.UDPAddr{
  186. IP: w.address.IP(),
  187. Port: int(w.port),
  188. },
  189. }
  190. w.activeConn[id] = conn
  191. conn.updateActivity()
  192. return conn, false
  193. }
  194. func (w *udpWorker) callback(b *buf.Buffer, source net.Destination, originalDest net.Destination) {
  195. id := connId{
  196. src: source,
  197. dest: originalDest,
  198. }
  199. conn, existing := w.getConnection(id)
  200. select {
  201. case conn.input <- b:
  202. default:
  203. b.Release()
  204. }
  205. if !existing {
  206. go func() {
  207. ctx := w.ctx
  208. ctx, cancel := context.WithCancel(ctx)
  209. conn.cancel = cancel
  210. if originalDest.IsValid() {
  211. ctx = proxy.ContextWithOriginalTarget(ctx, originalDest)
  212. }
  213. if len(w.tag) > 0 {
  214. ctx = proxy.ContextWithInboundTag(ctx, w.tag)
  215. }
  216. ctx = proxy.ContextWithSource(ctx, source)
  217. ctx = proxy.ContextWithInboundEntryPoint(ctx, net.UDPDestination(w.address, w.port))
  218. if err := w.proxy.Process(ctx, net.Network_UDP, conn, w.dispatcher); err != nil {
  219. log.Trace(newError("connection ends").Base(err))
  220. }
  221. w.removeConn(id)
  222. cancel()
  223. }()
  224. }
  225. }
  226. func (w *udpWorker) removeConn(id connId) {
  227. w.Lock()
  228. delete(w.activeConn, id)
  229. w.Unlock()
  230. }
  231. func (w *udpWorker) Start() error {
  232. w.activeConn = make(map[connId]*udpConn, 16)
  233. ctx, cancel := context.WithCancel(context.Background())
  234. w.ctx = ctx
  235. w.cancel = cancel
  236. h, err := udp.ListenUDP(w.address, w.port, udp.ListenOption{
  237. Callback: w.callback,
  238. ReceiveOriginalDest: w.recvOrigDest,
  239. })
  240. if err != nil {
  241. return err
  242. }
  243. go w.monitor()
  244. w.hub = h
  245. return nil
  246. }
  247. func (w *udpWorker) Close() {
  248. if w.hub != nil {
  249. w.hub.Close()
  250. w.cancel()
  251. }
  252. }
  253. func (w *udpWorker) monitor() {
  254. timer := time.NewTicker(time.Second * 16)
  255. defer timer.Stop()
  256. for {
  257. select {
  258. case <-w.ctx.Done():
  259. return
  260. case <-timer.C:
  261. nowSec := time.Now().Unix()
  262. w.Lock()
  263. for addr, conn := range w.activeConn {
  264. if nowSec-atomic.LoadInt64(&conn.lastActivityTime) > 8 {
  265. delete(w.activeConn, addr)
  266. conn.cancel()
  267. }
  268. }
  269. w.Unlock()
  270. }
  271. }
  272. }
  273. func (w *udpWorker) Port() net.Port {
  274. return w.port
  275. }
  276. func (w *udpWorker) Proxy() proxy.Inbound {
  277. return w.proxy
  278. }