worker.go 6.3 KB

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