worker.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. package inbound
  2. import (
  3. "context"
  4. "sync"
  5. "sync/atomic"
  6. "time"
  7. "v2ray.com/core"
  8. "v2ray.com/core/app/proxyman"
  9. "v2ray.com/core/common"
  10. "v2ray.com/core/common/buf"
  11. "v2ray.com/core/common/net"
  12. "v2ray.com/core/common/serial"
  13. "v2ray.com/core/common/session"
  14. "v2ray.com/core/common/signal/done"
  15. "v2ray.com/core/common/task"
  16. "v2ray.com/core/proxy"
  17. "v2ray.com/core/transport/internet"
  18. "v2ray.com/core/transport/internet/tcp"
  19. "v2ray.com/core/transport/internet/udp"
  20. "v2ray.com/core/transport/pipe"
  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.MemoryStreamConfig
  33. recvOrigDest bool
  34. tag string
  35. dispatcher core.Dispatcher
  36. sniffingConfig *proxyman.SniffingConfig
  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").Base(err).WriteToLog(session.ExportIDToError(ctx))
  49. }
  50. if dest.IsValid() {
  51. ctx = session.ContextWithOutbound(ctx, &session.Outbound{
  52. Target: dest,
  53. })
  54. }
  55. }
  56. ctx = session.ContextWithInbound(ctx, &session.Inbound{
  57. Source: net.DestinationFromAddr(conn.RemoteAddr()),
  58. Gateway: net.TCPDestination(w.address, w.port),
  59. Tag: w.tag,
  60. })
  61. if w.sniffingConfig != nil {
  62. ctx = proxyman.ContextWithSniffingConfig(ctx, w.sniffingConfig)
  63. }
  64. if w.uplinkCounter != nil || w.downlinkCounter != nil {
  65. conn = &internet.StatCouterConnection{
  66. Connection: conn,
  67. Uplink: w.uplinkCounter,
  68. Downlink: w.downlinkCounter,
  69. }
  70. }
  71. if err := w.proxy.Process(ctx, net.Network_TCP, conn, w.dispatcher); err != nil {
  72. newError("connection ends").Base(err).WriteToLog(session.ExportIDToError(ctx))
  73. }
  74. cancel()
  75. if err := conn.Close(); err != nil {
  76. newError("failed to close connection").Base(err).WriteToLog(session.ExportIDToError(ctx))
  77. }
  78. }
  79. func (w *tcpWorker) Proxy() proxy.Inbound {
  80. return w.proxy
  81. }
  82. func (w *tcpWorker) Start() error {
  83. ctx := internet.ContextWithStreamSettings(context.Background(), w.stream)
  84. hub, err := internet.ListenTCP(ctx, w.address, w.port, func(conn internet.Connection) {
  85. go w.callback(conn)
  86. })
  87. if err != nil {
  88. return newError("failed to listen TCP on ", w.port).AtWarning().Base(err)
  89. }
  90. w.hub = hub
  91. return nil
  92. }
  93. func (w *tcpWorker) Close() error {
  94. var errors []interface{}
  95. if w.hub != nil {
  96. if err := common.Close(w.hub); err != nil {
  97. errors = append(errors, err)
  98. }
  99. if err := common.Close(w.proxy); err != nil {
  100. errors = append(errors, err)
  101. }
  102. }
  103. if len(errors) > 0 {
  104. return newError("failed to close all resources").Base(newError(serial.Concat(errors...)))
  105. }
  106. return nil
  107. }
  108. func (w *tcpWorker) Port() net.Port {
  109. return w.port
  110. }
  111. type udpConn struct {
  112. lastActivityTime int64 // in seconds
  113. reader buf.Reader
  114. writer buf.Writer
  115. output func([]byte) (int, error)
  116. remote net.Addr
  117. local net.Addr
  118. done *done.Instance
  119. uplink core.StatCounter
  120. downlink core.StatCounter
  121. }
  122. func (c *udpConn) updateActivity() {
  123. atomic.StoreInt64(&c.lastActivityTime, time.Now().Unix())
  124. }
  125. // ReadMultiBuffer implements buf.Reader
  126. func (c *udpConn) ReadMultiBuffer() (buf.MultiBuffer, error) {
  127. mb, err := c.reader.ReadMultiBuffer()
  128. if err != nil {
  129. return nil, err
  130. }
  131. c.updateActivity()
  132. if c.uplink != nil {
  133. c.uplink.Add(int64(mb.Len()))
  134. }
  135. return mb, nil
  136. }
  137. func (c *udpConn) Read(buf []byte) (int, error) {
  138. panic("not implemented")
  139. }
  140. // Write implements io.Writer.
  141. func (c *udpConn) Write(buf []byte) (int, error) {
  142. n, err := c.output(buf)
  143. if c.downlink != nil {
  144. c.downlink.Add(int64(n))
  145. }
  146. if err == nil {
  147. c.updateActivity()
  148. }
  149. return n, err
  150. }
  151. func (c *udpConn) Close() error {
  152. common.Must(c.done.Close())
  153. common.Must(common.Close(c.writer))
  154. return nil
  155. }
  156. func (c *udpConn) RemoteAddr() net.Addr {
  157. return c.remote
  158. }
  159. func (c *udpConn) LocalAddr() net.Addr {
  160. return c.remote
  161. }
  162. func (*udpConn) SetDeadline(time.Time) error {
  163. return nil
  164. }
  165. func (*udpConn) SetReadDeadline(time.Time) error {
  166. return nil
  167. }
  168. func (*udpConn) SetWriteDeadline(time.Time) error {
  169. return nil
  170. }
  171. type connID struct {
  172. src net.Destination
  173. dest net.Destination
  174. }
  175. type udpWorker struct {
  176. sync.RWMutex
  177. proxy proxy.Inbound
  178. hub *udp.Hub
  179. address net.Address
  180. port net.Port
  181. tag string
  182. stream *internet.MemoryStreamConfig
  183. dispatcher core.Dispatcher
  184. uplinkCounter core.StatCounter
  185. downlinkCounter core.StatCounter
  186. checker *task.Periodic
  187. activeConn map[connID]*udpConn
  188. }
  189. func (w *udpWorker) getConnection(id connID) (*udpConn, bool) {
  190. w.Lock()
  191. defer w.Unlock()
  192. if conn, found := w.activeConn[id]; found && !conn.done.Done() {
  193. return conn, true
  194. }
  195. pReader, pWriter := pipe.New(pipe.DiscardOverflow(), pipe.WithSizeLimit(16*1024))
  196. conn := &udpConn{
  197. reader: pReader,
  198. writer: pWriter,
  199. output: func(b []byte) (int, error) {
  200. return w.hub.WriteTo(b, id.src)
  201. },
  202. remote: &net.UDPAddr{
  203. IP: id.src.Address.IP(),
  204. Port: int(id.src.Port),
  205. },
  206. local: &net.UDPAddr{
  207. IP: w.address.IP(),
  208. Port: int(w.port),
  209. },
  210. done: done.New(),
  211. uplink: w.uplinkCounter,
  212. downlink: w.downlinkCounter,
  213. }
  214. w.activeConn[id] = conn
  215. conn.updateActivity()
  216. return conn, false
  217. }
  218. func (w *udpWorker) callback(b *buf.Buffer, source net.Destination, originalDest net.Destination) {
  219. id := connID{
  220. src: source,
  221. }
  222. if originalDest.IsValid() {
  223. id.dest = originalDest
  224. }
  225. conn, existing := w.getConnection(id)
  226. // payload will be discarded in pipe is full.
  227. conn.writer.WriteMultiBuffer(buf.NewMultiBufferValue(b)) // nolint: errcheck
  228. if !existing {
  229. common.Must(w.checker.Start())
  230. go func() {
  231. ctx := context.Background()
  232. sid := session.NewID()
  233. ctx = session.ContextWithID(ctx, sid)
  234. if originalDest.IsValid() {
  235. ctx = session.ContextWithOutbound(ctx, &session.Outbound{
  236. Target: originalDest,
  237. })
  238. }
  239. ctx = session.ContextWithInbound(ctx, &session.Inbound{
  240. Source: source,
  241. Gateway: net.UDPDestination(w.address, w.port),
  242. Tag: w.tag,
  243. })
  244. if err := w.proxy.Process(ctx, net.Network_UDP, conn, w.dispatcher); err != nil {
  245. newError("connection ends").Base(err).WriteToLog(session.ExportIDToError(ctx))
  246. }
  247. conn.Close() // nolint: errcheck
  248. w.removeConn(id)
  249. }()
  250. }
  251. }
  252. func (w *udpWorker) removeConn(id connID) {
  253. w.Lock()
  254. delete(w.activeConn, id)
  255. w.Unlock()
  256. }
  257. func (w *udpWorker) handlePackets() {
  258. receive := w.hub.Receive()
  259. for payload := range receive {
  260. w.callback(payload.Content, payload.Source, payload.OriginalDestination)
  261. }
  262. }
  263. func (w *udpWorker) clean() error {
  264. nowSec := time.Now().Unix()
  265. w.Lock()
  266. defer w.Unlock()
  267. if len(w.activeConn) == 0 {
  268. return newError("no more connections. stopping...")
  269. }
  270. for addr, conn := range w.activeConn {
  271. if nowSec-atomic.LoadInt64(&conn.lastActivityTime) > 8 {
  272. delete(w.activeConn, addr)
  273. conn.Close() // nolint: errcheck
  274. }
  275. }
  276. if len(w.activeConn) == 0 {
  277. w.activeConn = make(map[connID]*udpConn, 16)
  278. }
  279. return nil
  280. }
  281. func (w *udpWorker) Start() error {
  282. w.activeConn = make(map[connID]*udpConn, 16)
  283. ctx := internet.ContextWithStreamSettings(context.Background(), w.stream)
  284. h, err := udp.ListenUDP(ctx, w.address, w.port, udp.HubCapacity(256))
  285. if err != nil {
  286. return err
  287. }
  288. w.checker = &task.Periodic{
  289. Interval: time.Second * 16,
  290. Execute: w.clean,
  291. }
  292. w.hub = h
  293. go w.handlePackets()
  294. return nil
  295. }
  296. func (w *udpWorker) Close() error {
  297. w.Lock()
  298. defer w.Unlock()
  299. var errors []interface{}
  300. if w.hub != nil {
  301. if err := w.hub.Close(); err != nil {
  302. errors = append(errors, err)
  303. }
  304. }
  305. if w.checker != nil {
  306. if err := w.checker.Close(); err != nil {
  307. errors = append(errors, err)
  308. }
  309. }
  310. if err := common.Close(w.proxy); err != nil {
  311. errors = append(errors, err)
  312. }
  313. if len(errors) > 0 {
  314. return newError("failed to close all resources").Base(newError(serial.Concat(errors...)))
  315. }
  316. return nil
  317. }
  318. func (w *udpWorker) Port() net.Port {
  319. return w.port
  320. }
  321. func (w *udpWorker) Proxy() proxy.Inbound {
  322. return w.proxy
  323. }