worker.go 6.2 KB

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