mux.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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/protocol"
  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 muxCoolAddress = net.DomainAddress("v1.mux.cool")
  72. var muxCoolPort = net.Port(9527)
  73. // NewClient creates a new mux.Client.
  74. func NewClient(p proxy.Outbound, dialer proxy.Dialer, m *ClientManager) (*Client, error) {
  75. ctx, cancel := context.WithCancel(context.Background())
  76. ctx = proxy.ContextWithTarget(ctx, net.TCPDestination(muxCoolAddress, muxCoolPort))
  77. pipe := ray.NewRay(ctx)
  78. go p.Process(ctx, pipe, dialer)
  79. c := &Client{
  80. sessionManager: NewSessionManager(),
  81. inboundRay: pipe,
  82. ctx: ctx,
  83. cancel: cancel,
  84. manager: m,
  85. concurrency: m.config.Concurrency,
  86. }
  87. go c.fetchOutput()
  88. go c.monitor()
  89. return c, nil
  90. }
  91. func (m *Client) Closed() bool {
  92. select {
  93. case <-m.ctx.Done():
  94. return true
  95. default:
  96. return false
  97. }
  98. }
  99. func (m *Client) monitor() {
  100. defer m.manager.onClientFinish()
  101. timer := time.NewTicker(time.Second * 16)
  102. defer timer.Stop()
  103. for {
  104. select {
  105. case <-m.ctx.Done():
  106. m.sessionManager.Close()
  107. m.inboundRay.InboundInput().Close()
  108. m.inboundRay.InboundOutput().CloseError()
  109. return
  110. case <-timer.C:
  111. size := m.sessionManager.Size()
  112. if size == 0 && m.sessionManager.CloseIfNoSession() {
  113. m.cancel()
  114. }
  115. }
  116. }
  117. }
  118. func fetchInput(ctx context.Context, s *Session, output buf.Writer) {
  119. dest, _ := proxy.TargetFromContext(ctx)
  120. transferType := protocol.TransferTypeStream
  121. if dest.Network == net.Network_UDP {
  122. transferType = protocol.TransferTypePacket
  123. }
  124. s.transferType = transferType
  125. writer := NewWriter(s.ID, dest, output, transferType)
  126. defer writer.Close()
  127. defer s.Close()
  128. log.Trace(newError("dispatching request to ", dest))
  129. data, _ := s.input.ReadTimeout(time.Millisecond * 500)
  130. if err := writer.Write(data); err != nil {
  131. log.Trace(newError("failed to write first payload").Base(err))
  132. return
  133. }
  134. if err := buf.Copy(s.input, writer); err != nil {
  135. log.Trace(newError("failed to fetch all input").Base(err))
  136. }
  137. }
  138. func (m *Client) Dispatch(ctx context.Context, outboundRay ray.OutboundRay) bool {
  139. sm := m.sessionManager
  140. if sm.Size() >= int(m.concurrency) || sm.Count() >= maxTotal {
  141. return false
  142. }
  143. select {
  144. case <-m.ctx.Done():
  145. return false
  146. default:
  147. }
  148. s := sm.Allocate()
  149. if s == nil {
  150. return false
  151. }
  152. s.input = outboundRay.OutboundInput()
  153. s.output = outboundRay.OutboundOutput()
  154. go fetchInput(ctx, s, m.inboundRay.InboundInput())
  155. return true
  156. }
  157. func drain(reader io.Reader) error {
  158. buf.Copy(NewStreamReader(reader), buf.Discard)
  159. return nil
  160. }
  161. func (m *Client) handleStatueKeepAlive(meta *FrameMetadata, reader io.Reader) error {
  162. if meta.Option.Has(OptionData) {
  163. return drain(reader)
  164. }
  165. return nil
  166. }
  167. func (m *Client) handleStatusNew(meta *FrameMetadata, reader io.Reader) error {
  168. if meta.Option.Has(OptionData) {
  169. return drain(reader)
  170. }
  171. return nil
  172. }
  173. func (m *Client) handleStatusKeep(meta *FrameMetadata, reader io.Reader) error {
  174. if !meta.Option.Has(OptionData) {
  175. return nil
  176. }
  177. if s, found := m.sessionManager.Get(meta.SessionID); found {
  178. return buf.Copy(s.NewReader(reader), s.output, buf.IgnoreWriterError())
  179. }
  180. return drain(reader)
  181. }
  182. func (m *Client) handleStatusEnd(meta *FrameMetadata, reader io.Reader) error {
  183. if s, found := m.sessionManager.Get(meta.SessionID); found {
  184. s.Close()
  185. }
  186. if meta.Option.Has(OptionData) {
  187. return drain(reader)
  188. }
  189. return nil
  190. }
  191. func (m *Client) fetchOutput() {
  192. defer m.cancel()
  193. reader := buf.ToBytesReader(m.inboundRay.InboundOutput())
  194. metaReader := NewMetadataReader(reader)
  195. for {
  196. meta, err := metaReader.Read()
  197. if err != nil {
  198. if errors.Cause(err) != io.EOF {
  199. log.Trace(newError("failed to read metadata").Base(err))
  200. }
  201. break
  202. }
  203. switch meta.SessionStatus {
  204. case SessionStatusKeepAlive:
  205. err = m.handleStatueKeepAlive(meta, reader)
  206. case SessionStatusEnd:
  207. err = m.handleStatusEnd(meta, reader)
  208. case SessionStatusNew:
  209. err = m.handleStatusNew(meta, reader)
  210. case SessionStatusKeep:
  211. err = m.handleStatusKeep(meta, reader)
  212. default:
  213. log.Trace(newError("unknown status: ", meta.SessionStatus).AtWarning())
  214. return
  215. }
  216. if err != nil {
  217. log.Trace(newError("failed to process data").Base(err))
  218. return
  219. }
  220. }
  221. }
  222. type Server struct {
  223. dispatcher dispatcher.Interface
  224. }
  225. // NewServer creates a new mux.Server.
  226. func NewServer(ctx context.Context) *Server {
  227. s := &Server{}
  228. space := app.SpaceFromContext(ctx)
  229. space.OnInitialize(func() error {
  230. d := dispatcher.FromSpace(space)
  231. if d == nil {
  232. return newError("no dispatcher in space")
  233. }
  234. s.dispatcher = d
  235. return nil
  236. })
  237. return s
  238. }
  239. func (s *Server) Dispatch(ctx context.Context, dest net.Destination) (ray.InboundRay, error) {
  240. if dest.Address != muxCoolAddress {
  241. return s.dispatcher.Dispatch(ctx, dest)
  242. }
  243. ray := ray.NewRay(ctx)
  244. worker := &ServerWorker{
  245. dispatcher: s.dispatcher,
  246. outboundRay: ray,
  247. sessionManager: NewSessionManager(),
  248. }
  249. go worker.run(ctx)
  250. return ray, nil
  251. }
  252. type ServerWorker struct {
  253. dispatcher dispatcher.Interface
  254. outboundRay ray.OutboundRay
  255. sessionManager *SessionManager
  256. }
  257. func handle(ctx context.Context, s *Session, output buf.Writer) {
  258. writer := NewResponseWriter(s.ID, output, s.transferType)
  259. if err := buf.Copy(s.input, writer); err != nil {
  260. log.Trace(newError("session ", s.ID, " ends: ").Base(err))
  261. }
  262. writer.Close()
  263. s.Close()
  264. }
  265. func (w *ServerWorker) handleStatusKeepAlive(meta *FrameMetadata, reader io.Reader) error {
  266. if meta.Option.Has(OptionData) {
  267. return drain(reader)
  268. }
  269. return nil
  270. }
  271. func (w *ServerWorker) handleStatusNew(ctx context.Context, meta *FrameMetadata, reader io.Reader) error {
  272. log.Trace(newError("received request for ", meta.Target))
  273. inboundRay, err := w.dispatcher.Dispatch(ctx, meta.Target)
  274. if err != nil {
  275. if meta.Option.Has(OptionData) {
  276. drain(reader)
  277. }
  278. return newError("failed to dispatch request.").Base(err)
  279. }
  280. s := &Session{
  281. input: inboundRay.InboundOutput(),
  282. output: inboundRay.InboundInput(),
  283. parent: w.sessionManager,
  284. ID: meta.SessionID,
  285. transferType: protocol.TransferTypeStream,
  286. }
  287. if meta.Target.Network == net.Network_UDP {
  288. s.transferType = protocol.TransferTypePacket
  289. }
  290. w.sessionManager.Add(s)
  291. go handle(ctx, s, w.outboundRay.OutboundOutput())
  292. if meta.Option.Has(OptionData) {
  293. return buf.Copy(s.NewReader(reader), s.output, buf.IgnoreWriterError())
  294. }
  295. return nil
  296. }
  297. func (w *ServerWorker) handleStatusKeep(meta *FrameMetadata, reader io.Reader) error {
  298. if !meta.Option.Has(OptionData) {
  299. return nil
  300. }
  301. if s, found := w.sessionManager.Get(meta.SessionID); found {
  302. return buf.Copy(s.NewReader(reader), s.output, buf.IgnoreWriterError())
  303. }
  304. return drain(reader)
  305. }
  306. func (w *ServerWorker) handleStatusEnd(meta *FrameMetadata, reader io.Reader) error {
  307. if s, found := w.sessionManager.Get(meta.SessionID); found {
  308. s.Close()
  309. }
  310. if meta.Option.Has(OptionData) {
  311. return drain(reader)
  312. }
  313. return nil
  314. }
  315. func (w *ServerWorker) handleFrame(ctx context.Context, reader io.Reader) error {
  316. metaReader := NewMetadataReader(reader)
  317. meta, err := metaReader.Read()
  318. if err != nil {
  319. return newError("failed to read metadata").Base(err)
  320. }
  321. switch meta.SessionStatus {
  322. case SessionStatusKeepAlive:
  323. err = w.handleStatusKeepAlive(meta, reader)
  324. case SessionStatusEnd:
  325. err = w.handleStatusEnd(meta, reader)
  326. case SessionStatusNew:
  327. err = w.handleStatusNew(ctx, meta, reader)
  328. case SessionStatusKeep:
  329. err = w.handleStatusKeep(meta, reader)
  330. default:
  331. return newError("unknown status: ", meta.SessionStatus).AtWarning()
  332. }
  333. if err != nil {
  334. return newError("failed to process data").Base(err)
  335. }
  336. return nil
  337. }
  338. func (w *ServerWorker) run(ctx context.Context) {
  339. input := w.outboundRay.OutboundInput()
  340. reader := buf.ToBytesReader(input)
  341. defer w.sessionManager.Close()
  342. for {
  343. select {
  344. case <-ctx.Done():
  345. return
  346. default:
  347. err := w.handleFrame(ctx, reader)
  348. if err != nil {
  349. if errors.Cause(err) != io.EOF {
  350. log.Trace(newError("unexpected EOF").Base(err))
  351. input.CloseError()
  352. }
  353. return
  354. }
  355. }
  356. }
  357. }