mux.go 9.5 KB

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