worker.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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/session"
  14. "v2ray.com/core/common/signal/done"
  15. "v2ray.com/core/proxy"
  16. "v2ray.com/core/transport/internet"
  17. "v2ray.com/core/transport/internet/tcp"
  18. "v2ray.com/core/transport/internet/udp"
  19. )
  20. type worker interface {
  21. Start() error
  22. Close() error
  23. Port() net.Port
  24. Proxy() proxy.Inbound
  25. }
  26. type tcpWorker struct {
  27. address net.Address
  28. port net.Port
  29. proxy proxy.Inbound
  30. stream *internet.StreamConfig
  31. recvOrigDest bool
  32. tag string
  33. dispatcher core.Dispatcher
  34. sniffers []proxyman.KnownProtocols
  35. uplinkCounter core.StatCounter
  36. downlinkCounter core.StatCounter
  37. hub internet.Listener
  38. }
  39. func (w *tcpWorker) callback(conn internet.Connection) {
  40. ctx, cancel := context.WithCancel(context.Background())
  41. sid := session.NewID()
  42. ctx = session.ContextWithID(ctx, sid)
  43. if w.recvOrigDest {
  44. dest, err := tcp.GetOriginalDestination(conn)
  45. if err != nil {
  46. newError("failed to get original destination").WithContext(ctx).Base(err).WriteToLog()
  47. }
  48. if dest.IsValid() {
  49. ctx = proxy.ContextWithOriginalTarget(ctx, dest)
  50. }
  51. }
  52. if len(w.tag) > 0 {
  53. ctx = proxy.ContextWithInboundTag(ctx, w.tag)
  54. }
  55. ctx = proxy.ContextWithInboundEntryPoint(ctx, net.TCPDestination(w.address, w.port))
  56. ctx = proxy.ContextWithSource(ctx, net.DestinationFromAddr(conn.RemoteAddr()))
  57. if len(w.sniffers) > 0 {
  58. ctx = proxyman.ContextWithProtocolSniffers(ctx, w.sniffers)
  59. }
  60. if w.uplinkCounter != nil || w.downlinkCounter != nil {
  61. conn = &internet.StatCouterConnection{
  62. Connection: conn,
  63. Uplink: w.uplinkCounter,
  64. Downlink: w.downlinkCounter,
  65. }
  66. }
  67. if err := w.proxy.Process(ctx, net.Network_TCP, conn, w.dispatcher); err != nil {
  68. newError("connection ends").Base(err).WithContext(ctx).WriteToLog()
  69. }
  70. cancel()
  71. if err := conn.Close(); err != nil {
  72. newError("failed to close connection").Base(err).WithContext(ctx).WriteToLog()
  73. }
  74. }
  75. func (w *tcpWorker) Proxy() proxy.Inbound {
  76. return w.proxy
  77. }
  78. func (w *tcpWorker) Start() error {
  79. ctx := internet.ContextWithStreamSettings(context.Background(), w.stream)
  80. hub, err := internet.ListenTCP(ctx, w.address, w.port, func(conn internet.Connection) {
  81. go w.callback(conn)
  82. })
  83. if err != nil {
  84. return newError("failed to listen TCP on ", w.port).AtWarning().Base(err)
  85. }
  86. w.hub = hub
  87. return nil
  88. }
  89. func (w *tcpWorker) Close() error {
  90. if w.hub != nil {
  91. common.Close(w.hub)
  92. common.Close(w.proxy)
  93. }
  94. return nil
  95. }
  96. func (w *tcpWorker) Port() net.Port {
  97. return w.port
  98. }
  99. type udpConn struct {
  100. lastActivityTime int64 // in seconds
  101. input chan *buf.Buffer
  102. output func([]byte) (int, error)
  103. remote net.Addr
  104. local net.Addr
  105. done *done.Instance
  106. uplink core.StatCounter
  107. downlink core.StatCounter
  108. }
  109. func (c *udpConn) updateActivity() {
  110. atomic.StoreInt64(&c.lastActivityTime, time.Now().Unix())
  111. }
  112. // ReadMultiBuffer implements buf.Reader
  113. func (c *udpConn) ReadMultiBuffer() (buf.MultiBuffer, error) {
  114. var payload buf.MultiBuffer
  115. select {
  116. case in := <-c.input:
  117. payload.Append(in)
  118. default:
  119. select {
  120. case in := <-c.input:
  121. payload.Append(in)
  122. case <-c.done.Wait():
  123. return nil, io.EOF
  124. }
  125. }
  126. L:
  127. for {
  128. select {
  129. case in := <-c.input:
  130. payload.Append(in)
  131. default:
  132. break L
  133. }
  134. }
  135. if c.uplink != nil {
  136. c.uplink.Add(int64(payload.Len()))
  137. }
  138. return payload, nil
  139. }
  140. func (c *udpConn) Read(buf []byte) (int, error) {
  141. select {
  142. case in := <-c.input:
  143. defer in.Release()
  144. c.updateActivity()
  145. nBytes := copy(buf, in.Bytes())
  146. if c.uplink != nil {
  147. c.uplink.Add(int64(nBytes))
  148. }
  149. return nBytes, nil
  150. case <-c.done.Wait():
  151. return 0, io.EOF
  152. }
  153. }
  154. // Write implements io.Writer.
  155. func (c *udpConn) Write(buf []byte) (int, error) {
  156. n, err := c.output(buf)
  157. if c.downlink != nil {
  158. c.downlink.Add(int64(n))
  159. }
  160. if err == nil {
  161. c.updateActivity()
  162. }
  163. return n, err
  164. }
  165. func (c *udpConn) Close() error {
  166. common.Must(c.done.Close())
  167. return nil
  168. }
  169. func (c *udpConn) RemoteAddr() net.Addr {
  170. return c.remote
  171. }
  172. func (c *udpConn) LocalAddr() net.Addr {
  173. return c.remote
  174. }
  175. func (*udpConn) SetDeadline(time.Time) error {
  176. return nil
  177. }
  178. func (*udpConn) SetReadDeadline(time.Time) error {
  179. return nil
  180. }
  181. func (*udpConn) SetWriteDeadline(time.Time) error {
  182. return nil
  183. }
  184. type connID struct {
  185. src net.Destination
  186. dest net.Destination
  187. }
  188. type udpWorker struct {
  189. sync.RWMutex
  190. proxy proxy.Inbound
  191. hub *udp.Hub
  192. address net.Address
  193. port net.Port
  194. recvOrigDest bool
  195. tag string
  196. dispatcher core.Dispatcher
  197. uplinkCounter core.StatCounter
  198. downlinkCounter core.StatCounter
  199. done *done.Instance
  200. activeConn map[connID]*udpConn
  201. }
  202. func (w *udpWorker) getConnection(id connID) (*udpConn, bool) {
  203. w.Lock()
  204. defer w.Unlock()
  205. if conn, found := w.activeConn[id]; found && !conn.done.Done() {
  206. return conn, true
  207. }
  208. conn := &udpConn{
  209. input: make(chan *buf.Buffer, 32),
  210. output: func(b []byte) (int, error) {
  211. return w.hub.WriteTo(b, id.src)
  212. },
  213. remote: &net.UDPAddr{
  214. IP: id.src.Address.IP(),
  215. Port: int(id.src.Port),
  216. },
  217. local: &net.UDPAddr{
  218. IP: w.address.IP(),
  219. Port: int(w.port),
  220. },
  221. done: done.New(),
  222. uplink: w.uplinkCounter,
  223. downlink: w.downlinkCounter,
  224. }
  225. w.activeConn[id] = conn
  226. conn.updateActivity()
  227. return conn, false
  228. }
  229. func (w *udpWorker) callback(b *buf.Buffer, source net.Destination, originalDest net.Destination) {
  230. id := connID{
  231. src: source,
  232. }
  233. if originalDest.IsValid() {
  234. id.dest = originalDest
  235. }
  236. conn, existing := w.getConnection(id)
  237. select {
  238. case conn.input <- b:
  239. case <-conn.done.Wait():
  240. b.Release()
  241. default:
  242. b.Release()
  243. }
  244. if !existing {
  245. go func() {
  246. ctx := context.Background()
  247. sid := session.NewID()
  248. ctx = session.ContextWithID(ctx, sid)
  249. if originalDest.IsValid() {
  250. ctx = proxy.ContextWithOriginalTarget(ctx, originalDest)
  251. }
  252. if len(w.tag) > 0 {
  253. ctx = proxy.ContextWithInboundTag(ctx, w.tag)
  254. }
  255. ctx = proxy.ContextWithSource(ctx, source)
  256. ctx = proxy.ContextWithInboundEntryPoint(ctx, net.UDPDestination(w.address, w.port))
  257. if err := w.proxy.Process(ctx, net.Network_UDP, conn, w.dispatcher); err != nil {
  258. newError("connection ends").Base(err).WriteToLog()
  259. }
  260. conn.Close()
  261. w.removeConn(id)
  262. }()
  263. }
  264. }
  265. func (w *udpWorker) removeConn(id connID) {
  266. w.Lock()
  267. delete(w.activeConn, id)
  268. w.Unlock()
  269. }
  270. func (w *udpWorker) Start() error {
  271. w.activeConn = make(map[connID]*udpConn, 16)
  272. w.done = done.New()
  273. h, err := udp.ListenUDP(w.address, w.port, w.callback, udp.HubReceiveOriginalDestination(w.recvOrigDest), udp.HubCapacity(256))
  274. if err != nil {
  275. return err
  276. }
  277. go w.monitor()
  278. w.hub = h
  279. return nil
  280. }
  281. func (w *udpWorker) Close() error {
  282. w.Lock()
  283. defer w.Unlock()
  284. if w.hub != nil {
  285. w.hub.Close()
  286. }
  287. if w.done != nil {
  288. common.Must(w.done.Close())
  289. }
  290. common.Close(w.proxy)
  291. return nil
  292. }
  293. func (w *udpWorker) monitor() {
  294. timer := time.NewTicker(time.Second * 16)
  295. defer timer.Stop()
  296. for {
  297. select {
  298. case <-w.done.Wait():
  299. return
  300. case <-timer.C:
  301. nowSec := time.Now().Unix()
  302. w.Lock()
  303. for addr, conn := range w.activeConn {
  304. if nowSec-atomic.LoadInt64(&conn.lastActivityTime) > 8 {
  305. delete(w.activeConn, addr)
  306. conn.Close()
  307. }
  308. }
  309. w.Unlock()
  310. }
  311. }
  312. }
  313. func (w *udpWorker) Port() net.Port {
  314. return w.port
  315. }
  316. func (w *udpWorker) Proxy() proxy.Inbound {
  317. return w.proxy
  318. }