portal.go 5.5 KB

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