v2ray-core/app/proxyman/mux/mux.go

373 lines
8.0 KiB
Go
Raw Normal View History

2017-02-07 20:11:47 +00:00
package mux
2017-04-08 23:43:25 +00:00
//go:generate go run $GOPATH/src/v2ray.com/core/tools/generrorgen/main.go -pkg mux -path App,Proxyman,Mux
2017-03-31 22:53:01 +00:00
import (
"context"
"sync"
"time"
2017-04-02 12:06:20 +00:00
"v2ray.com/core/app"
2017-04-02 07:48:30 +00:00
"v2ray.com/core/app/dispatcher"
"v2ray.com/core/app/log"
2017-04-12 08:40:21 +00:00
"v2ray.com/core/app/proxyman"
2017-03-31 22:53:01 +00:00
"v2ray.com/core/common/buf"
2017-04-02 07:48:30 +00:00
"v2ray.com/core/common/net"
2017-03-31 22:53:01 +00:00
"v2ray.com/core/common/signal"
"v2ray.com/core/proxy"
"v2ray.com/core/transport/ray"
)
2017-02-07 20:11:47 +00:00
2017-03-26 23:47:01 +00:00
const (
2017-04-12 08:40:21 +00:00
maxTotal = 128
2017-03-26 23:47:01 +00:00
)
2017-04-02 19:30:21 +00:00
type ClientManager struct {
access sync.Mutex
clients []*Client
proxy proxy.Outbound
dialer proxy.Dialer
2017-04-12 08:40:21 +00:00
config *proxyman.MultiplexingConfig
2017-04-02 19:30:21 +00:00
}
2017-04-12 08:40:21 +00:00
func NewClientManager(p proxy.Outbound, d proxy.Dialer, c *proxyman.MultiplexingConfig) *ClientManager {
2017-04-02 19:30:21 +00:00
return &ClientManager{
proxy: p,
dialer: d,
2017-04-12 08:40:21 +00:00
config: c,
2017-04-02 19:30:21 +00:00
}
}
func (m *ClientManager) Dispatch(ctx context.Context, outboundRay ray.OutboundRay) error {
m.access.Lock()
defer m.access.Unlock()
for _, client := range m.clients {
if client.Dispatch(ctx, outboundRay) {
return nil
}
}
client, err := NewClient(m.proxy, m.dialer, m)
if err != nil {
2017-04-08 23:43:25 +00:00
return newError("failed to create client").Base(err)
2017-04-02 19:30:21 +00:00
}
m.clients = append(m.clients, client)
client.Dispatch(ctx, outboundRay)
return nil
}
func (m *ClientManager) onClientFinish() {
m.access.Lock()
defer m.access.Unlock()
2017-04-03 21:43:33 +00:00
if len(m.clients) < 10 {
return
}
activeClients := make([]*Client, 0, len(m.clients))
for _, client := range m.clients {
if !client.Closed() {
activeClients = append(activeClients, client)
2017-04-02 19:30:21 +00:00
}
}
2017-04-03 21:43:33 +00:00
m.clients = activeClients
2017-04-02 19:30:21 +00:00
}
2017-03-31 22:53:01 +00:00
type Client struct {
sessionManager *SessionManager
2017-04-05 12:13:26 +00:00
inboundRay ray.InboundRay
ctx context.Context
cancel context.CancelFunc
manager *ClientManager
session2Remove chan uint16
2017-04-12 08:40:21 +00:00
concurrency uint32
2017-03-31 22:53:01 +00:00
}
2017-04-02 07:48:30 +00:00
var muxCoolDestination = net.TCPDestination(net.DomainAddress("v1.mux.cool"), net.Port(9527))
2017-03-31 22:53:01 +00:00
2017-04-02 19:30:21 +00:00
func NewClient(p proxy.Outbound, dialer proxy.Dialer, m *ClientManager) (*Client, error) {
2017-04-02 07:48:30 +00:00
ctx, cancel := context.WithCancel(context.Background())
ctx = proxy.ContextWithTarget(ctx, muxCoolDestination)
pipe := ray.NewRay(ctx)
2017-04-03 10:55:46 +00:00
go p.Process(ctx, pipe, dialer)
c := &Client{
sessionManager: NewSessionManager(),
2017-04-05 12:13:26 +00:00
inboundRay: pipe,
ctx: ctx,
cancel: cancel,
manager: m,
session2Remove: make(chan uint16, 16),
2017-04-12 08:40:21 +00:00
concurrency: m.config.Concurrency,
2017-04-03 10:55:46 +00:00
}
go c.fetchOutput()
2017-04-05 12:13:26 +00:00
go c.monitor()
2017-04-03 10:55:46 +00:00
return c, nil
2017-02-07 20:11:47 +00:00
}
2017-04-02 07:48:30 +00:00
func (m *Client) Closed() bool {
select {
case <-m.ctx.Done():
return true
default:
return false
}
2017-03-26 23:47:01 +00:00
}
2017-04-05 12:13:26 +00:00
func (m *Client) monitor() {
2017-04-05 12:26:20 +00:00
defer m.manager.onClientFinish()
2017-04-05 12:13:26 +00:00
for {
select {
case <-m.ctx.Done():
m.sessionManager.Close()
m.inboundRay.InboundInput().Close()
m.inboundRay.InboundOutput().CloseError()
2017-04-05 12:13:26 +00:00
return
case <-time.After(time.Second * 6):
size := m.sessionManager.Size()
if size == 0 {
2017-04-05 13:22:21 +00:00
m.cancel()
}
2017-04-05 12:13:26 +00:00
}
}
}
func fetchInput(ctx context.Context, s *Session, output buf.Writer) {
2017-03-31 22:53:01 +00:00
dest, _ := proxy.TargetFromContext(ctx)
2017-04-02 11:43:24 +00:00
writer := &Writer{
2017-03-31 22:53:01 +00:00
dest: dest,
id: s.ID,
2017-04-03 10:55:46 +00:00
writer: output,
}
defer writer.Close()
defer s.CloseUplink()
2017-04-03 10:55:46 +00:00
2017-04-08 23:43:25 +00:00
log.Trace(newError("dispatching request to ", dest))
2017-04-03 10:55:46 +00:00
data, _ := s.input.ReadTimeout(time.Millisecond * 500)
if data != nil {
if err := writer.Write(data); err != nil {
2017-04-08 23:43:25 +00:00
log.Trace(newError("failed to write first payload").Base(err))
2017-04-03 10:55:46 +00:00
return
}
2017-03-31 22:53:01 +00:00
}
2017-04-04 08:24:38 +00:00
if err := buf.PipeUntilEOF(signal.BackgroundTimer(), s.input, writer); err != nil {
2017-04-08 23:43:25 +00:00
log.Trace(newError("failed to fetch all input").Base(err))
2017-04-02 19:30:21 +00:00
}
2017-03-31 22:53:01 +00:00
}
2017-04-02 07:48:30 +00:00
func (m *Client) Dispatch(ctx context.Context, outboundRay ray.OutboundRay) bool {
numSession := m.sessionManager.Size()
if numSession >= int(m.concurrency) || numSession >= maxTotal {
2017-04-02 07:48:30 +00:00
return false
}
select {
case <-m.ctx.Done():
return false
default:
}
s := &Session{
2017-04-02 07:48:30 +00:00
input: outboundRay.OutboundInput(),
output: outboundRay.OutboundOutput(),
parent: m.sessionManager,
2017-03-31 22:53:01 +00:00
}
m.sessionManager.Allocate(s)
2017-04-03 10:55:46 +00:00
go fetchInput(ctx, s, m.inboundRay.InboundInput())
2017-04-02 07:48:30 +00:00
return true
2017-03-31 22:53:01 +00:00
}
2017-04-03 21:43:33 +00:00
func drain(reader *Reader) error {
for {
data, more, err := reader.Read()
if err != nil {
return err
}
data.Release()
if !more {
return nil
}
}
}
func pipe(reader *Reader, writer buf.Writer) error {
for {
data, more, err := reader.Read()
if err != nil {
return err
}
if err := writer.Write(data); err != nil {
return err
}
if !more {
return nil
}
}
}
2017-03-31 22:53:01 +00:00
func (m *Client) fetchOutput() {
2017-04-05 12:13:26 +00:00
defer m.cancel()
2017-03-31 22:53:01 +00:00
reader := NewReader(m.inboundRay.InboundOutput())
2017-04-12 21:55:59 +00:00
L:
2017-03-31 22:53:01 +00:00
for {
meta, err := reader.ReadMetadata()
if err != nil {
2017-04-08 23:43:25 +00:00
log.Trace(newError("failed to read metadata").Base(err))
2017-03-31 22:53:01 +00:00
break
}
2017-04-12 21:55:59 +00:00
var drainData bool
switch meta.SessionStatus {
case SessionStatusKeepAlive:
drainData = true
case SessionStatusEnd:
if s, found := m.sessionManager.Get(meta.SessionID); found {
s.CloseDownlink()
s.output.Close()
}
drainData = true
case SessionStatusNew:
drainData = true
case SessionStatusKeep:
if !meta.Option.Has(OptionData) {
break
}
if s, found := m.sessionManager.Get(meta.SessionID); found {
if err := pipe(reader, s.output); err != nil {
log.Trace(newError("failed to pipe data").Base(err))
break L
2017-04-12 09:52:10 +00:00
}
}
2017-04-03 21:43:33 +00:00
}
2017-04-12 21:55:59 +00:00
if drainData && meta.Option.Has(OptionData) {
if err := drain(reader); err != nil {
log.Trace(newError("failed to drain data").Base(err))
break
}
2017-03-31 22:53:01 +00:00
}
}
2017-02-07 20:11:47 +00:00
}
2017-04-02 07:48:30 +00:00
type Server struct {
dispatcher dispatcher.Interface
}
2017-04-02 12:06:20 +00:00
func NewServer(ctx context.Context) *Server {
s := &Server{}
space := app.SpaceFromContext(ctx)
space.OnInitialize(func() error {
d := dispatcher.FromSpace(space)
if d == nil {
2017-04-08 23:43:25 +00:00
return newError("no dispatcher in space")
2017-04-02 12:06:20 +00:00
}
s.dispatcher = d
return nil
})
return s
}
2017-04-02 07:48:30 +00:00
func (s *Server) Dispatch(ctx context.Context, dest net.Destination) (ray.InboundRay, error) {
if dest != muxCoolDestination {
return s.dispatcher.Dispatch(ctx, dest)
}
ray := ray.NewRay(ctx)
2017-04-02 12:06:20 +00:00
worker := &ServerWorker{
dispatcher: s.dispatcher,
outboundRay: ray,
sessionManager: NewSessionManager(),
2017-04-02 12:06:20 +00:00
}
go worker.run(ctx)
2017-04-02 07:48:30 +00:00
return ray, nil
}
type ServerWorker struct {
dispatcher dispatcher.Interface
outboundRay ray.OutboundRay
sessionManager *SessionManager
2017-04-02 07:48:30 +00:00
}
func handle(ctx context.Context, s *Session, output buf.Writer) {
writer := NewResponseWriter(s.ID, output)
2017-04-04 08:24:38 +00:00
if err := buf.PipeUntilEOF(signal.BackgroundTimer(), s.input, writer); err != nil {
log.Trace(newError("session ", s.ID, " ends: ").Base(err))
2017-04-02 07:48:30 +00:00
}
2017-04-04 09:20:07 +00:00
writer.Close()
s.CloseDownlink()
2017-04-02 07:48:30 +00:00
}
func (w *ServerWorker) run(ctx context.Context) {
input := w.outboundRay.OutboundInput()
reader := NewReader(input)
2017-04-12 21:55:59 +00:00
L:
2017-04-02 07:48:30 +00:00
for {
select {
case <-ctx.Done():
return
default:
}
meta, err := reader.ReadMetadata()
if err != nil {
2017-04-08 23:43:25 +00:00
log.Trace(newError("failed to read metadata").Base(err))
2017-04-02 07:48:30 +00:00
return
}
2017-04-12 21:55:59 +00:00
var drainData bool
switch meta.SessionStatus {
case SessionStatusKeepAlive:
drainData = true
case SessionStatusEnd:
if s, found := w.sessionManager.Get(meta.SessionID); found {
s.CloseUplink()
s.output.Close()
2017-04-12 09:52:10 +00:00
}
2017-04-12 21:55:59 +00:00
drainData = true
case SessionStatusNew:
2017-04-08 23:43:25 +00:00
log.Trace(newError("received request for ", meta.Target))
2017-04-02 07:48:30 +00:00
inboundRay, err := w.dispatcher.Dispatch(ctx, meta.Target)
if err != nil {
2017-04-08 23:43:25 +00:00
log.Trace(newError("failed to dispatch request.").Base(err))
2017-04-12 21:55:59 +00:00
drainData = true
break
2017-04-02 07:48:30 +00:00
}
2017-04-12 21:55:59 +00:00
s := &Session{
2017-04-02 07:48:30 +00:00
input: inboundRay.InboundOutput(),
output: inboundRay.InboundInput(),
parent: w.sessionManager,
ID: meta.SessionID,
2017-04-02 07:48:30 +00:00
}
w.sessionManager.Add(s)
2017-04-03 15:28:15 +00:00
go handle(ctx, s, w.outboundRay.OutboundOutput())
2017-04-12 21:55:59 +00:00
if !meta.Option.Has(OptionData) {
break
}
if err := pipe(reader, s.output); err != nil {
log.Trace(newError("failed to read data").Base(err))
break L
}
case SessionStatusKeep:
if !meta.Option.Has(OptionData) {
break
}
if s, found := w.sessionManager.Get(meta.SessionID); found {
if err := pipe(reader, s.output); err != nil {
log.Trace(newError("failed to read data").Base(err))
break L
}
}
2017-04-02 07:48:30 +00:00
}
2017-04-12 21:55:59 +00:00
if meta.Option.Has(OptionData) && drainData {
if err := drain(reader); err != nil {
log.Trace(newError("failed to drain data").Base(err))
break
}
2017-04-02 07:48:30 +00:00
}
}
}