portal.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. package reverse
  2. import (
  3. "context"
  4. "sync"
  5. "time"
  6. "github.com/golang/protobuf/proto"
  7. "v2ray.com/core/common"
  8. "v2ray.com/core/common/buf"
  9. "v2ray.com/core/common/mux"
  10. "v2ray.com/core/common/net"
  11. "v2ray.com/core/common/session"
  12. "v2ray.com/core/common/task"
  13. "v2ray.com/core/common/vio"
  14. "v2ray.com/core/features/outbound"
  15. "v2ray.com/core/transport/pipe"
  16. )
  17. type Portal struct {
  18. ohm outbound.Manager
  19. tag string
  20. domain string
  21. picker *StaticMuxPicker
  22. client *mux.ClientManager
  23. }
  24. func NewPortal(config *PortalConfig, ohm outbound.Manager) (*Portal, error) {
  25. if len(config.Tag) == 0 {
  26. return nil, newError("portal tag is empty")
  27. }
  28. if len(config.Domain) == 0 {
  29. return nil, newError("portal domain is empty")
  30. }
  31. picker, err := NewStaticMuxPicker()
  32. if err != nil {
  33. return nil, err
  34. }
  35. return &Portal{
  36. ohm: ohm,
  37. tag: config.Tag,
  38. domain: config.Domain,
  39. picker: picker,
  40. client: &mux.ClientManager{
  41. Picker: picker,
  42. },
  43. }, nil
  44. }
  45. func (p *Portal) Start() error {
  46. return p.ohm.AddHandler(context.Background(), &Outbound{
  47. portal: p,
  48. tag: p.tag,
  49. })
  50. }
  51. func (p *Portal) Close() error {
  52. return p.ohm.RemoveHandler(context.Background(), p.tag)
  53. }
  54. func (s *Portal) HandleConnection(ctx context.Context, link *vio.Link) error {
  55. outboundMeta := session.OutboundFromContext(ctx)
  56. if outboundMeta == nil {
  57. return newError("outbound metadata not found").AtError()
  58. }
  59. if isDomain(outboundMeta.Target, s.domain) {
  60. muxClient, err := mux.NewClientWorker(*link, mux.ClientStrategy{
  61. MaxConcurrency: 0,
  62. MaxConnection: 256,
  63. })
  64. if err != nil {
  65. return newError("failed to create mux client worker").Base(err).AtWarning()
  66. }
  67. worker, err := NewPortalWorker(muxClient)
  68. if err != nil {
  69. return newError("failed to create portal worker").Base(err)
  70. }
  71. s.picker.AddWorker(worker)
  72. return nil
  73. }
  74. return s.client.Dispatch(ctx, link)
  75. }
  76. type Outbound struct {
  77. portal *Portal
  78. tag string
  79. }
  80. func (o *Outbound) Tag() string {
  81. return o.tag
  82. }
  83. func (o *Outbound) Dispatch(ctx context.Context, link *vio.Link) {
  84. if err := o.portal.HandleConnection(ctx, link); err != nil {
  85. newError("failed to process reverse connection").Base(err).WriteToLog(session.ExportIDToError(ctx))
  86. pipe.CloseError(link.Writer)
  87. }
  88. }
  89. func (o *Outbound) Start() error {
  90. return nil
  91. }
  92. func (o *Outbound) Close() error {
  93. return nil
  94. }
  95. type StaticMuxPicker struct {
  96. access sync.Mutex
  97. workers []*PortalWorker
  98. cTask *task.Periodic
  99. }
  100. func NewStaticMuxPicker() (*StaticMuxPicker, error) {
  101. p := &StaticMuxPicker{}
  102. p.cTask = &task.Periodic{
  103. Execute: p.cleanup,
  104. Interval: time.Second * 30,
  105. }
  106. p.cTask.Start()
  107. return p, nil
  108. }
  109. func (p *StaticMuxPicker) cleanup() error {
  110. p.access.Lock()
  111. defer p.access.Unlock()
  112. var activeWorkers []*PortalWorker
  113. for _, w := range p.workers {
  114. if !w.Closed() {
  115. activeWorkers = append(activeWorkers, w)
  116. }
  117. }
  118. if len(activeWorkers) != len(p.workers) {
  119. p.workers = activeWorkers
  120. }
  121. return nil
  122. }
  123. func (p *StaticMuxPicker) PickAvailable() (*mux.ClientWorker, error) {
  124. p.access.Lock()
  125. defer p.access.Unlock()
  126. if len(p.workers) == 0 {
  127. return nil, newError("empty worker list")
  128. }
  129. var minIdx int = -1
  130. var minConn uint32 = 9999
  131. for i, w := range p.workers {
  132. if w.IsFull() {
  133. continue
  134. }
  135. if w.client.ActiveConnections() < minConn {
  136. minConn = w.client.ActiveConnections()
  137. minIdx = i
  138. }
  139. }
  140. if minIdx != -1 {
  141. return p.workers[minIdx].client, nil
  142. }
  143. return nil, newError("no mux client worker available")
  144. }
  145. func (p *StaticMuxPicker) AddWorker(worker *PortalWorker) {
  146. p.access.Lock()
  147. defer p.access.Unlock()
  148. p.workers = append(p.workers, worker)
  149. }
  150. type PortalWorker struct {
  151. client *mux.ClientWorker
  152. control *task.Periodic
  153. writer buf.Writer
  154. reader buf.Reader
  155. }
  156. func NewPortalWorker(client *mux.ClientWorker) (*PortalWorker, error) {
  157. opt := []pipe.Option{pipe.WithSizeLimit(16 * 1024)}
  158. uplinkReader, uplinkWriter := pipe.New(opt...)
  159. downlinkReader, downlinkWriter := pipe.New(opt...)
  160. ctx := context.Background()
  161. ctx = session.ContextWithOutbound(ctx, &session.Outbound{
  162. Target: net.UDPDestination(net.DomainAddress(internalDomain), 0),
  163. })
  164. f := client.Dispatch(ctx, &vio.Link{
  165. Reader: uplinkReader,
  166. Writer: downlinkWriter,
  167. })
  168. if !f {
  169. return nil, newError("unable to dispatch control connection")
  170. }
  171. w := &PortalWorker{
  172. client: client,
  173. reader: downlinkReader,
  174. writer: uplinkWriter,
  175. }
  176. w.control = &task.Periodic{
  177. Execute: w.heartbeat,
  178. Interval: time.Second * 2,
  179. }
  180. w.control.Start()
  181. return w, nil
  182. }
  183. func (w *PortalWorker) heartbeat() error {
  184. if w.client.Closed() {
  185. return newError("client worker stopped")
  186. }
  187. if w.writer == nil {
  188. return newError("already disposed")
  189. }
  190. msg := &Control{}
  191. msg.FillInRandom()
  192. if w.client.IsClosing() {
  193. msg.State = Control_DRAIN
  194. defer func() {
  195. common.Close(w.writer)
  196. pipe.CloseError(w.reader)
  197. w.writer = nil
  198. }()
  199. }
  200. b, err := proto.Marshal(msg)
  201. common.Must(err)
  202. var mb buf.MultiBuffer
  203. common.Must2(mb.Write(b))
  204. return w.writer.WriteMultiBuffer(mb)
  205. }
  206. func (w *PortalWorker) IsFull() bool {
  207. return w.client.IsFull()
  208. }
  209. func (w *PortalWorker) Closed() bool {
  210. return w.client.Closed()
  211. }