worker.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. nconns := len(conns)
  84. L:
  85. for i := 0; i < nconns; i++ {
  86. select {
  87. case conn := <-conns:
  88. conn.Close()
  89. default:
  90. break L
  91. }
  92. }
  93. return
  94. case conn := <-conns:
  95. go w.callback(conn)
  96. }
  97. }
  98. }
  99. func (w *tcpWorker) Close() {
  100. if w.hub != nil {
  101. w.cancel()
  102. }
  103. }
  104. func (w *tcpWorker) Port() v2net.Port {
  105. return w.port
  106. }
  107. type udpConn struct {
  108. lastActivityTime int64 // in seconds
  109. input chan *buf.Buffer
  110. output func([]byte) (int, error)
  111. remote net.Addr
  112. local net.Addr
  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. in, open := <-c.input
  120. if !open {
  121. return 0, io.EOF
  122. }
  123. defer in.Release()
  124. c.updateActivity()
  125. return copy(buf, in.Bytes()), nil
  126. }
  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. func (*udpConn) Reusable() bool {
  153. return false
  154. }
  155. func (*udpConn) SetReusable(bool) {}
  156. type udpWorker struct {
  157. sync.RWMutex
  158. proxy proxy.Inbound
  159. hub *udp.Hub
  160. address v2net.Address
  161. port v2net.Port
  162. recvOrigDest bool
  163. tag string
  164. dispatcher dispatcher.Interface
  165. ctx context.Context
  166. cancel context.CancelFunc
  167. activeConn map[v2net.Destination]*udpConn
  168. }
  169. func (w *udpWorker) getConnection(src v2net.Destination) (*udpConn, bool) {
  170. w.Lock()
  171. defer w.Unlock()
  172. if conn, found := w.activeConn[src]; 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, src)
  179. },
  180. remote: &net.UDPAddr{
  181. IP: src.Address.IP(),
  182. Port: int(src.Port),
  183. },
  184. local: &net.UDPAddr{
  185. IP: w.address.IP(),
  186. Port: int(w.port),
  187. },
  188. }
  189. w.activeConn[src] = conn
  190. conn.updateActivity()
  191. return conn, false
  192. }
  193. func (w *udpWorker) callback(b *buf.Buffer, source v2net.Destination, originalDest v2net.Destination) {
  194. conn, existing := w.getConnection(source)
  195. select {
  196. case conn.input <- b:
  197. default:
  198. b.Release()
  199. }
  200. if !existing {
  201. go func() {
  202. ctx := w.ctx
  203. ctx, cancel := context.WithCancel(ctx)
  204. conn.cancel = cancel
  205. if originalDest.IsValid() {
  206. ctx = proxy.ContextWithOriginalTarget(ctx, originalDest)
  207. }
  208. if len(w.tag) > 0 {
  209. ctx = proxy.ContextWithInboundTag(ctx, w.tag)
  210. }
  211. ctx = proxy.ContextWithSource(ctx, source)
  212. ctx = proxy.ContextWithInboundEntryPoint(ctx, v2net.UDPDestination(w.address, w.port))
  213. if err := w.proxy.Process(ctx, v2net.Network_UDP, conn, w.dispatcher); err != nil {
  214. err = errors.Base(err).Message("Proxyman|UDPWorker: Connection ends.")
  215. if errors.IsActionRequired(err) {
  216. log.Warning(err)
  217. } else {
  218. log.Info(err)
  219. }
  220. }
  221. w.removeConn(source)
  222. cancel()
  223. }()
  224. }
  225. }
  226. func (w *udpWorker) removeConn(src v2net.Destination) {
  227. w.Lock()
  228. delete(w.activeConn, src)
  229. w.Unlock()
  230. }
  231. func (w *udpWorker) Start() error {
  232. w.activeConn = make(map[v2net.Destination]*udpConn)
  233. ctx, cancel := context.WithCancel(context.Background())
  234. w.ctx = ctx
  235. w.cancel = cancel
  236. h, err := udp.ListenUDP(w.address, w.port, udp.ListenOption{
  237. Callback: w.callback,
  238. ReceiveOriginalDest: w.recvOrigDest,
  239. })
  240. if err != nil {
  241. return err
  242. }
  243. go w.monitor()
  244. w.hub = h
  245. return nil
  246. }
  247. func (w *udpWorker) Close() {
  248. if w.hub != nil {
  249. w.hub.Close()
  250. w.cancel()
  251. }
  252. }
  253. func (w *udpWorker) monitor() {
  254. for {
  255. select {
  256. case <-w.ctx.Done():
  257. return
  258. case <-time.After(time.Second * 16):
  259. nowSec := time.Now().Unix()
  260. w.Lock()
  261. for addr, conn := range w.activeConn {
  262. if nowSec-conn.lastActivityTime > 8 {
  263. delete(w.activeConn, addr)
  264. conn.cancel()
  265. }
  266. }
  267. w.Unlock()
  268. }
  269. }
  270. }
  271. func (w *udpWorker) Port() v2net.Port {
  272. return w.port
  273. }
  274. func (w *udpWorker) Proxy() proxy.Inbound {
  275. return w.proxy
  276. }