worker.go 6.0 KB

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