worker.go 6.1 KB

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