worker.go 6.1 KB

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