worker.go 5.9 KB

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