worker.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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. 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 = 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 w.sniffingConfig != nil {
  60. ctx = proxyman.ContextWithSniffingConfig(ctx, w.sniffingConfig)
  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).WriteToLog(session.ExportIDToError(ctx))
  71. }
  72. cancel()
  73. if err := conn.Close(); err != nil {
  74. newError("failed to close connection").Base(err).WriteToLog(session.ExportIDToError(ctx))
  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. c.updateActivity()
  146. if c.uplink != nil {
  147. c.uplink.Add(int64(payload.Len()))
  148. }
  149. return payload, nil
  150. }
  151. func (c *udpConn) Read(buf []byte) (int, error) {
  152. select {
  153. case in := <-c.input:
  154. defer in.Release()
  155. c.updateActivity()
  156. nBytes := copy(buf, in.Bytes())
  157. if c.uplink != nil {
  158. c.uplink.Add(int64(nBytes))
  159. }
  160. return nBytes, nil
  161. case <-c.done.Wait():
  162. return 0, io.EOF
  163. }
  164. }
  165. // Write implements io.Writer.
  166. func (c *udpConn) Write(buf []byte) (int, error) {
  167. n, err := c.output(buf)
  168. if c.downlink != nil {
  169. c.downlink.Add(int64(n))
  170. }
  171. if err == nil {
  172. c.updateActivity()
  173. }
  174. return n, err
  175. }
  176. func (c *udpConn) Close() error {
  177. common.Must(c.done.Close())
  178. return nil
  179. }
  180. func (c *udpConn) RemoteAddr() net.Addr {
  181. return c.remote
  182. }
  183. func (c *udpConn) LocalAddr() net.Addr {
  184. return c.remote
  185. }
  186. func (*udpConn) SetDeadline(time.Time) error {
  187. return nil
  188. }
  189. func (*udpConn) SetReadDeadline(time.Time) error {
  190. return nil
  191. }
  192. func (*udpConn) SetWriteDeadline(time.Time) error {
  193. return nil
  194. }
  195. type connID struct {
  196. src net.Destination
  197. dest net.Destination
  198. }
  199. type udpWorker struct {
  200. sync.RWMutex
  201. proxy proxy.Inbound
  202. hub *udp.Hub
  203. address net.Address
  204. port net.Port
  205. recvOrigDest bool
  206. tag string
  207. dispatcher core.Dispatcher
  208. uplinkCounter core.StatCounter
  209. downlinkCounter core.StatCounter
  210. checker *task.Periodic
  211. activeConn map[connID]*udpConn
  212. }
  213. func (w *udpWorker) getConnection(id connID) (*udpConn, bool) {
  214. w.Lock()
  215. defer w.Unlock()
  216. if conn, found := w.activeConn[id]; found && !conn.done.Done() {
  217. return conn, true
  218. }
  219. conn := &udpConn{
  220. input: make(chan *buf.Buffer, 32),
  221. output: func(b []byte) (int, error) {
  222. return w.hub.WriteTo(b, id.src)
  223. },
  224. remote: &net.UDPAddr{
  225. IP: id.src.Address.IP(),
  226. Port: int(id.src.Port),
  227. },
  228. local: &net.UDPAddr{
  229. IP: w.address.IP(),
  230. Port: int(w.port),
  231. },
  232. done: done.New(),
  233. uplink: w.uplinkCounter,
  234. downlink: w.downlinkCounter,
  235. }
  236. w.activeConn[id] = conn
  237. conn.updateActivity()
  238. return conn, false
  239. }
  240. func (w *udpWorker) callback(b *buf.Buffer, source net.Destination, originalDest net.Destination) {
  241. id := connID{
  242. src: source,
  243. }
  244. if originalDest.IsValid() {
  245. id.dest = originalDest
  246. }
  247. conn, existing := w.getConnection(id)
  248. select {
  249. case conn.input <- b:
  250. case <-conn.done.Wait():
  251. b.Release()
  252. default:
  253. b.Release()
  254. }
  255. if !existing {
  256. common.Must(w.checker.Start())
  257. go func() {
  258. ctx := context.Background()
  259. sid := session.NewID()
  260. ctx = session.ContextWithID(ctx, sid)
  261. if originalDest.IsValid() {
  262. ctx = proxy.ContextWithOriginalTarget(ctx, originalDest)
  263. }
  264. if len(w.tag) > 0 {
  265. ctx = proxy.ContextWithInboundTag(ctx, w.tag)
  266. }
  267. ctx = proxy.ContextWithSource(ctx, source)
  268. ctx = proxy.ContextWithInboundEntryPoint(ctx, net.UDPDestination(w.address, w.port))
  269. if err := w.proxy.Process(ctx, net.Network_UDP, conn, w.dispatcher); err != nil {
  270. newError("connection ends").Base(err).WriteToLog()
  271. }
  272. conn.Close() // nolint: errcheck
  273. w.removeConn(id)
  274. }()
  275. }
  276. }
  277. func (w *udpWorker) removeConn(id connID) {
  278. w.Lock()
  279. delete(w.activeConn, id)
  280. w.Unlock()
  281. }
  282. func (w *udpWorker) handlePackets() {
  283. receive := w.hub.Receive()
  284. for payload := range receive {
  285. w.callback(payload.Content, payload.Source, payload.OriginalDestination)
  286. }
  287. }
  288. func (w *udpWorker) clean() error {
  289. nowSec := time.Now().Unix()
  290. w.Lock()
  291. defer w.Unlock()
  292. if len(w.activeConn) == 0 {
  293. return newError("no more connections. stopping...")
  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. func (w *udpWorker) Start() error {
  307. w.activeConn = make(map[connID]*udpConn, 16)
  308. h, err := udp.ListenUDP(w.address, w.port, udp.HubReceiveOriginalDestination(w.recvOrigDest), udp.HubCapacity(256))
  309. if err != nil {
  310. return err
  311. }
  312. w.checker = &task.Periodic{
  313. Interval: time.Second * 16,
  314. Execute: w.clean,
  315. }
  316. w.hub = h
  317. go w.handlePackets()
  318. return nil
  319. }
  320. func (w *udpWorker) Close() error {
  321. w.Lock()
  322. defer w.Unlock()
  323. var errors []interface{}
  324. if w.hub != nil {
  325. if err := w.hub.Close(); err != nil {
  326. errors = append(errors, err)
  327. }
  328. }
  329. if w.checker != nil {
  330. if err := w.checker.Close(); err != nil {
  331. errors = append(errors, err)
  332. }
  333. }
  334. if err := common.Close(w.proxy); err != nil {
  335. errors = append(errors, err)
  336. }
  337. if len(errors) > 0 {
  338. return newError("failed to close all resources").Base(newError(serial.Concat(errors...)))
  339. }
  340. return nil
  341. }
  342. func (w *udpWorker) Port() net.Port {
  343. return w.port
  344. }
  345. func (w *udpWorker) Proxy() proxy.Inbound {
  346. return w.proxy
  347. }