mux.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. package mux
  2. //go:generate go run $GOPATH/src/v2ray.com/core/tools/generrorgen/main.go -pkg mux -path App,Proxyman,Mux
  3. import (
  4. "context"
  5. "io"
  6. "sync"
  7. "time"
  8. "v2ray.com/core/app"
  9. "v2ray.com/core/app/dispatcher"
  10. "v2ray.com/core/app/log"
  11. "v2ray.com/core/app/proxyman"
  12. "v2ray.com/core/common/buf"
  13. "v2ray.com/core/common/errors"
  14. "v2ray.com/core/common/net"
  15. "v2ray.com/core/common/signal"
  16. "v2ray.com/core/proxy"
  17. "v2ray.com/core/transport/ray"
  18. )
  19. const (
  20. maxTotal = 128
  21. )
  22. type ClientManager struct {
  23. access sync.Mutex
  24. clients []*Client
  25. proxy proxy.Outbound
  26. dialer proxy.Dialer
  27. config *proxyman.MultiplexingConfig
  28. }
  29. func NewClientManager(p proxy.Outbound, d proxy.Dialer, c *proxyman.MultiplexingConfig) *ClientManager {
  30. return &ClientManager{
  31. proxy: p,
  32. dialer: d,
  33. config: c,
  34. }
  35. }
  36. func (m *ClientManager) Dispatch(ctx context.Context, outboundRay ray.OutboundRay) error {
  37. m.access.Lock()
  38. defer m.access.Unlock()
  39. for _, client := range m.clients {
  40. if client.Dispatch(ctx, outboundRay) {
  41. return nil
  42. }
  43. }
  44. client, err := NewClient(m.proxy, m.dialer, m)
  45. if err != nil {
  46. return newError("failed to create client").Base(err)
  47. }
  48. m.clients = append(m.clients, client)
  49. client.Dispatch(ctx, outboundRay)
  50. return nil
  51. }
  52. func (m *ClientManager) onClientFinish() {
  53. m.access.Lock()
  54. defer m.access.Unlock()
  55. activeClients := make([]*Client, 0, len(m.clients))
  56. for _, client := range m.clients {
  57. if !client.Closed() {
  58. activeClients = append(activeClients, client)
  59. }
  60. }
  61. m.clients = activeClients
  62. }
  63. type Client struct {
  64. sessionManager *SessionManager
  65. inboundRay ray.InboundRay
  66. ctx context.Context
  67. cancel context.CancelFunc
  68. manager *ClientManager
  69. concurrency uint32
  70. }
  71. var muxCoolDestination = net.TCPDestination(net.DomainAddress("v1.mux.cool"), net.Port(9527))
  72. // NewClient creates a new mux.Client.
  73. func NewClient(p proxy.Outbound, dialer proxy.Dialer, m *ClientManager) (*Client, error) {
  74. ctx, cancel := context.WithCancel(context.Background())
  75. ctx = proxy.ContextWithTarget(ctx, muxCoolDestination)
  76. pipe := ray.NewRay(ctx)
  77. go p.Process(ctx, pipe, dialer)
  78. c := &Client{
  79. sessionManager: NewSessionManager(),
  80. inboundRay: pipe,
  81. ctx: ctx,
  82. cancel: cancel,
  83. manager: m,
  84. concurrency: m.config.Concurrency,
  85. }
  86. go c.fetchOutput()
  87. go c.monitor()
  88. return c, nil
  89. }
  90. func (m *Client) Closed() bool {
  91. select {
  92. case <-m.ctx.Done():
  93. return true
  94. default:
  95. return false
  96. }
  97. }
  98. func (m *Client) monitor() {
  99. defer m.manager.onClientFinish()
  100. for {
  101. select {
  102. case <-m.ctx.Done():
  103. m.sessionManager.Close()
  104. m.inboundRay.InboundInput().Close()
  105. m.inboundRay.InboundOutput().CloseError()
  106. return
  107. case <-time.After(time.Second * 16):
  108. size := m.sessionManager.Size()
  109. if size == 0 && m.sessionManager.CloseIfNoSession() {
  110. m.cancel()
  111. }
  112. }
  113. }
  114. }
  115. func fetchInput(ctx context.Context, s *Session, output buf.Writer) {
  116. dest, _ := proxy.TargetFromContext(ctx)
  117. writer := &Writer{
  118. dest: dest,
  119. id: s.ID,
  120. writer: output,
  121. }
  122. defer writer.Close()
  123. defer s.CloseUplink()
  124. log.Trace(newError("dispatching request to ", dest))
  125. data, _ := s.input.ReadTimeout(time.Millisecond * 500)
  126. if err := writer.Write(data); err != nil {
  127. log.Trace(newError("failed to write first payload").Base(err))
  128. return
  129. }
  130. if err := buf.Copy(signal.BackgroundTimer(), s.input, writer); err != nil {
  131. log.Trace(newError("failed to fetch all input").Base(err))
  132. }
  133. }
  134. func (m *Client) Dispatch(ctx context.Context, outboundRay ray.OutboundRay) bool {
  135. sm := m.sessionManager
  136. if sm.Size() >= int(m.concurrency) || sm.Count() >= maxTotal {
  137. return false
  138. }
  139. select {
  140. case <-m.ctx.Done():
  141. return false
  142. default:
  143. }
  144. s := sm.Allocate()
  145. if s == nil {
  146. return false
  147. }
  148. s.input = outboundRay.OutboundInput()
  149. s.output = outboundRay.OutboundOutput()
  150. go fetchInput(ctx, s, m.inboundRay.InboundInput())
  151. return true
  152. }
  153. func drain(reader *Reader) error {
  154. buf.Copy(signal.BackgroundTimer(), reader, buf.Discard)
  155. return nil
  156. }
  157. func (m *Client) handleStatueKeepAlive(meta *FrameMetadata, reader *Reader) error {
  158. if meta.Option.Has(OptionData) {
  159. return drain(reader)
  160. }
  161. return nil
  162. }
  163. func (m *Client) handleStatusNew(meta *FrameMetadata, reader *Reader) error {
  164. if meta.Option.Has(OptionData) {
  165. return drain(reader)
  166. }
  167. return nil
  168. }
  169. func (m *Client) handleStatusKeep(meta *FrameMetadata, reader *Reader) error {
  170. if !meta.Option.Has(OptionData) {
  171. return nil
  172. }
  173. if s, found := m.sessionManager.Get(meta.SessionID); found {
  174. return buf.Copy(signal.BackgroundTimer(), reader, s.output, buf.IgnoreWriterError())
  175. }
  176. return drain(reader)
  177. }
  178. func (m *Client) handleStatusEnd(meta *FrameMetadata, reader *Reader) error {
  179. if s, found := m.sessionManager.Get(meta.SessionID); found {
  180. s.CloseDownlink()
  181. s.output.Close()
  182. }
  183. if meta.Option.Has(OptionData) {
  184. return drain(reader)
  185. }
  186. return nil
  187. }
  188. func (m *Client) fetchOutput() {
  189. defer m.cancel()
  190. reader := NewReader(m.inboundRay.InboundOutput())
  191. for {
  192. meta, err := reader.ReadMetadata()
  193. if err != nil {
  194. if errors.Cause(err) != io.EOF {
  195. log.Trace(newError("failed to read metadata").Base(err))
  196. }
  197. break
  198. }
  199. switch meta.SessionStatus {
  200. case SessionStatusKeepAlive:
  201. err = m.handleStatueKeepAlive(meta, reader)
  202. case SessionStatusEnd:
  203. err = m.handleStatusEnd(meta, reader)
  204. case SessionStatusNew:
  205. err = m.handleStatusNew(meta, reader)
  206. case SessionStatusKeep:
  207. err = m.handleStatusKeep(meta, reader)
  208. default:
  209. log.Trace(newError("unknown status: ", meta.SessionStatus).AtWarning())
  210. return
  211. }
  212. if err != nil {
  213. log.Trace(newError("failed to process data").Base(err))
  214. return
  215. }
  216. }
  217. }
  218. type Server struct {
  219. dispatcher dispatcher.Interface
  220. }
  221. // NewServer creates a new mux.Server.
  222. func NewServer(ctx context.Context) *Server {
  223. s := &Server{}
  224. space := app.SpaceFromContext(ctx)
  225. space.OnInitialize(func() error {
  226. d := dispatcher.FromSpace(space)
  227. if d == nil {
  228. return newError("no dispatcher in space")
  229. }
  230. s.dispatcher = d
  231. return nil
  232. })
  233. return s
  234. }
  235. func (s *Server) Dispatch(ctx context.Context, dest net.Destination) (ray.InboundRay, error) {
  236. if dest != muxCoolDestination {
  237. return s.dispatcher.Dispatch(ctx, dest)
  238. }
  239. ray := ray.NewRay(ctx)
  240. worker := &ServerWorker{
  241. dispatcher: s.dispatcher,
  242. outboundRay: ray,
  243. sessionManager: NewSessionManager(),
  244. }
  245. go worker.run(ctx)
  246. return ray, nil
  247. }
  248. type ServerWorker struct {
  249. dispatcher dispatcher.Interface
  250. outboundRay ray.OutboundRay
  251. sessionManager *SessionManager
  252. }
  253. func handle(ctx context.Context, s *Session, output buf.Writer) {
  254. writer := NewResponseWriter(s.ID, output)
  255. if err := buf.Copy(signal.BackgroundTimer(), s.input, writer); err != nil {
  256. log.Trace(newError("session ", s.ID, " ends: ").Base(err))
  257. }
  258. writer.Close()
  259. s.CloseDownlink()
  260. }
  261. func (w *ServerWorker) handleStatusKeepAlive(meta *FrameMetadata, reader *Reader) error {
  262. if meta.Option.Has(OptionData) {
  263. return drain(reader)
  264. }
  265. return nil
  266. }
  267. func (w *ServerWorker) handleStatusNew(ctx context.Context, meta *FrameMetadata, reader *Reader) error {
  268. log.Trace(newError("received request for ", meta.Target))
  269. inboundRay, err := w.dispatcher.Dispatch(ctx, meta.Target)
  270. if err != nil {
  271. if meta.Option.Has(OptionData) {
  272. drain(reader)
  273. }
  274. return newError("failed to dispatch request.").Base(err)
  275. }
  276. s := &Session{
  277. input: inboundRay.InboundOutput(),
  278. output: inboundRay.InboundInput(),
  279. parent: w.sessionManager,
  280. ID: meta.SessionID,
  281. }
  282. w.sessionManager.Add(s)
  283. go handle(ctx, s, w.outboundRay.OutboundOutput())
  284. if meta.Option.Has(OptionData) {
  285. return buf.Copy(signal.BackgroundTimer(), reader, s.output, buf.IgnoreWriterError())
  286. }
  287. return nil
  288. }
  289. func (w *ServerWorker) handleStatusKeep(meta *FrameMetadata, reader *Reader) error {
  290. if !meta.Option.Has(OptionData) {
  291. return nil
  292. }
  293. if s, found := w.sessionManager.Get(meta.SessionID); found {
  294. return buf.Copy(signal.BackgroundTimer(), reader, s.output, buf.IgnoreWriterError())
  295. }
  296. return drain(reader)
  297. }
  298. func (w *ServerWorker) handleStatusEnd(meta *FrameMetadata, reader *Reader) error {
  299. if s, found := w.sessionManager.Get(meta.SessionID); found {
  300. s.CloseUplink()
  301. s.output.Close()
  302. }
  303. if meta.Option.Has(OptionData) {
  304. return drain(reader)
  305. }
  306. return nil
  307. }
  308. func (w *ServerWorker) handleFrame(ctx context.Context, reader *Reader) error {
  309. meta, err := reader.ReadMetadata()
  310. if err != nil {
  311. return newError("failed to read metadata").Base(err)
  312. }
  313. switch meta.SessionStatus {
  314. case SessionStatusKeepAlive:
  315. err = w.handleStatusKeepAlive(meta, reader)
  316. case SessionStatusEnd:
  317. err = w.handleStatusEnd(meta, reader)
  318. case SessionStatusNew:
  319. err = w.handleStatusNew(ctx, meta, reader)
  320. case SessionStatusKeep:
  321. err = w.handleStatusKeep(meta, reader)
  322. default:
  323. return newError("unknown status: ", meta.SessionStatus).AtWarning()
  324. }
  325. if err != nil {
  326. return newError("failed to process data").Base(err)
  327. }
  328. return nil
  329. }
  330. func (w *ServerWorker) run(ctx context.Context) {
  331. input := w.outboundRay.OutboundInput()
  332. reader := NewReader(input)
  333. defer w.sessionManager.Close()
  334. for {
  335. select {
  336. case <-ctx.Done():
  337. return
  338. default:
  339. err := w.handleFrame(ctx, reader)
  340. if err != nil {
  341. if errors.Cause(err) != io.EOF {
  342. log.Trace(newError("unexpected EOF").Base(err))
  343. input.CloseError()
  344. }
  345. return
  346. }
  347. }
  348. }
  349. }