worker.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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. err := errors.Base(err).Message("Proxyman|TCPWorker: Connection ends.")
  52. if errors.IsActionRequired(err) {
  53. log.Warning(err)
  54. } else {
  55. log.Info(err)
  56. }
  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 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() v2net.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. func (c *udpConn) Write(buf []byte) (int, error) {
  127. n, err := c.output(buf)
  128. if err == nil {
  129. c.updateActivity()
  130. }
  131. return n, err
  132. }
  133. func (c *udpConn) Close() error {
  134. return nil
  135. }
  136. func (c *udpConn) RemoteAddr() net.Addr {
  137. return c.remote
  138. }
  139. func (c *udpConn) LocalAddr() net.Addr {
  140. return c.remote
  141. }
  142. func (*udpConn) SetDeadline(time.Time) error {
  143. return nil
  144. }
  145. func (*udpConn) SetReadDeadline(time.Time) error {
  146. return nil
  147. }
  148. func (*udpConn) SetWriteDeadline(time.Time) error {
  149. return nil
  150. }
  151. func (*udpConn) Reusable() bool {
  152. return false
  153. }
  154. func (*udpConn) SetReusable(bool) {}
  155. type udpWorker struct {
  156. sync.RWMutex
  157. proxy proxy.Inbound
  158. hub *udp.Hub
  159. address v2net.Address
  160. port v2net.Port
  161. recvOrigDest bool
  162. tag string
  163. dispatcher dispatcher.Interface
  164. ctx context.Context
  165. cancel context.CancelFunc
  166. activeConn map[v2net.Destination]*udpConn
  167. }
  168. func (w *udpWorker) getConnection(src v2net.Destination) (*udpConn, bool) {
  169. w.Lock()
  170. defer w.Unlock()
  171. if conn, found := w.activeConn[src]; found {
  172. return conn, true
  173. }
  174. conn := &udpConn{
  175. input: make(chan *buf.Buffer, 32),
  176. output: func(b []byte) (int, error) {
  177. return w.hub.WriteTo(b, src)
  178. },
  179. remote: &net.UDPAddr{
  180. IP: src.Address.IP(),
  181. Port: int(src.Port),
  182. },
  183. local: &net.UDPAddr{
  184. IP: w.address.IP(),
  185. Port: int(w.port),
  186. },
  187. }
  188. w.activeConn[src] = conn
  189. conn.updateActivity()
  190. return conn, false
  191. }
  192. func (w *udpWorker) callback(b *buf.Buffer, source v2net.Destination, originalDest v2net.Destination) {
  193. conn, existing := w.getConnection(source)
  194. select {
  195. case conn.input <- b:
  196. default:
  197. b.Release()
  198. }
  199. if !existing {
  200. go func() {
  201. ctx := w.ctx
  202. ctx, cancel := context.WithCancel(ctx)
  203. conn.cancel = cancel
  204. if originalDest.IsValid() {
  205. ctx = proxy.ContextWithOriginalTarget(ctx, originalDest)
  206. }
  207. if len(w.tag) > 0 {
  208. ctx = proxy.ContextWithInboundTag(ctx, w.tag)
  209. }
  210. ctx = proxy.ContextWithSource(ctx, source)
  211. ctx = proxy.ContextWithInboundEntryPoint(ctx, v2net.UDPDestination(w.address, w.port))
  212. if err := w.proxy.Process(ctx, v2net.Network_UDP, conn, w.dispatcher); err != nil {
  213. err = errors.Base(err).Message("Proxyman|UDPWorker: Connection ends.")
  214. if errors.IsActionRequired(err) {
  215. log.Warning(err)
  216. } else {
  217. log.Info(err)
  218. }
  219. }
  220. w.removeConn(source)
  221. cancel()
  222. }()
  223. }
  224. }
  225. func (w *udpWorker) removeConn(src v2net.Destination) {
  226. w.Lock()
  227. delete(w.activeConn, src)
  228. w.Unlock()
  229. }
  230. func (w *udpWorker) Start() error {
  231. w.activeConn = make(map[v2net.Destination]*udpConn)
  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. for {
  254. select {
  255. case <-w.ctx.Done():
  256. return
  257. case <-time.After(time.Second * 16):
  258. nowSec := time.Now().Unix()
  259. w.Lock()
  260. for addr, conn := range w.activeConn {
  261. if nowSec-atomic.LoadInt64(&conn.lastActivityTime) > 8 {
  262. delete(w.activeConn, addr)
  263. conn.cancel()
  264. }
  265. }
  266. w.Unlock()
  267. }
  268. }
  269. }
  270. func (w *udpWorker) Port() v2net.Port {
  271. return w.port
  272. }
  273. func (w *udpWorker) Proxy() proxy.Inbound {
  274. return w.proxy
  275. }