worker.go 6.4 KB

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