worker.go 8.2 KB

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