1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-08 11:17:44 -05:00
v2fly/app/proxyman/mux/mux.go

490 lines
12 KiB
Go
Raw Normal View History

2017-02-07 15:11:47 -05:00
package mux
2017-12-02 19:04:57 -05:00
//go:generate go run $GOPATH/src/v2ray.com/core/common/errors/errorgen/main.go -pkg mux -path App,Proxyman,Mux
2017-04-08 19:43:25 -04:00
2017-03-31 18:53:01 -04:00
import (
"context"
2017-04-16 07:24:02 -04:00
"io"
2017-03-31 18:53:01 -04:00
"sync"
"time"
"v2ray.com/core"
2017-04-12 04:40:21 -04:00
"v2ray.com/core/app/proxyman"
2018-04-04 15:33:33 -04:00
"v2ray.com/core/common"
2017-03-31 18:53:01 -04:00
"v2ray.com/core/common/buf"
2017-04-16 07:24:02 -04:00
"v2ray.com/core/common/errors"
2018-04-04 15:33:33 -04:00
"v2ray.com/core/common/log"
2017-04-02 03:48:30 -04:00
"v2ray.com/core/common/net"
2017-05-02 16:23:07 -04:00
"v2ray.com/core/common/protocol"
"v2ray.com/core/common/session"
2018-05-27 08:42:53 -04:00
"v2ray.com/core/common/signal/done"
2017-03-31 18:53:01 -04:00
"v2ray.com/core/proxy"
2018-04-16 18:31:10 -04:00
"v2ray.com/core/transport/pipe"
2017-03-31 18:53:01 -04:00
)
2017-02-07 15:11:47 -05:00
2017-03-26 19:47:01 -04:00
const (
2017-04-12 04:40:21 -04:00
maxTotal = 128
2017-03-26 19:47:01 -04:00
)
2017-04-02 15:30:21 -04:00
type ClientManager struct {
access sync.Mutex
clients []*Client
proxy proxy.Outbound
dialer proxy.Dialer
2017-04-12 04:40:21 -04:00
config *proxyman.MultiplexingConfig
2017-04-02 15:30:21 -04:00
}
2017-04-12 04:40:21 -04:00
func NewClientManager(p proxy.Outbound, d proxy.Dialer, c *proxyman.MultiplexingConfig) *ClientManager {
2017-04-02 15:30:21 -04:00
return &ClientManager{
proxy: p,
dialer: d,
2017-04-12 04:40:21 -04:00
config: c,
2017-04-02 15:30:21 -04:00
}
}
2018-04-16 18:31:10 -04:00
func (m *ClientManager) Dispatch(ctx context.Context, link *core.Link) error {
2017-04-02 15:30:21 -04:00
m.access.Lock()
defer m.access.Unlock()
for _, client := range m.clients {
2018-04-16 18:31:10 -04:00
if client.Dispatch(ctx, link) {
2017-04-02 15:30:21 -04:00
return nil
}
}
2018-05-25 06:08:28 -04:00
client, err := NewClient(ctx, m.proxy, m.dialer, m)
2017-04-02 15:30:21 -04:00
if err != nil {
2017-04-08 19:43:25 -04:00
return newError("failed to create client").Base(err)
2017-04-02 15:30:21 -04:00
}
m.clients = append(m.clients, client)
2018-04-16 18:31:10 -04:00
client.Dispatch(ctx, link)
2017-04-02 15:30:21 -04:00
return nil
}
func (m *ClientManager) onClientFinish() {
m.access.Lock()
defer m.access.Unlock()
2017-04-03 17:43:33 -04:00
activeClients := make([]*Client, 0, len(m.clients))
for _, client := range m.clients {
if !client.Closed() {
activeClients = append(activeClients, client)
2017-04-02 15:30:21 -04:00
}
}
2017-04-03 17:43:33 -04:00
m.clients = activeClients
2017-04-02 15:30:21 -04:00
}
2017-03-31 18:53:01 -04:00
type Client struct {
sessionManager *SessionManager
2018-04-16 18:31:10 -04:00
link core.Link
2018-05-27 08:42:53 -04:00
done *done.Instance
2017-04-05 08:13:26 -04:00
manager *ClientManager
2017-04-12 04:40:21 -04:00
concurrency uint32
2017-03-31 18:53:01 -04:00
}
2017-05-17 15:13:01 -04:00
var muxCoolAddress = net.DomainAddress("v1.mux.cool")
var muxCoolPort = net.Port(9527)
2017-03-31 18:53:01 -04:00
2017-04-26 15:43:53 -04:00
// NewClient creates a new mux.Client.
2018-05-25 06:08:28 -04:00
func NewClient(pctx context.Context, p proxy.Outbound, dialer proxy.Dialer, m *ClientManager) (*Client, error) {
ctx := session.ContextWithOutbound(context.Background(), &session.Outbound{
Target: net.TCPDestination(muxCoolAddress, muxCoolPort),
})
2018-02-08 11:46:50 -05:00
ctx, cancel := context.WithCancel(ctx)
2018-05-25 06:08:28 -04:00
opts := pipe.OptionsFromContext(pctx)
uplinkReader, upLinkWriter := pipe.New(opts...)
downlinkReader, downlinkWriter := pipe.New(opts...)
2017-10-20 15:11:13 -04:00
2017-04-03 06:55:46 -04:00
c := &Client{
sessionManager: NewSessionManager(),
2018-04-16 18:31:10 -04:00
link: core.Link{
Reader: downlinkReader,
Writer: upLinkWriter,
},
2018-05-27 08:42:53 -04:00
done: done.New(),
2018-04-16 18:31:10 -04:00
manager: m,
concurrency: m.config.Concurrency,
2017-04-03 06:55:46 -04:00
}
2018-02-08 11:46:50 -05:00
go func() {
2018-04-16 18:31:10 -04:00
if err := p.Process(ctx, &core.Link{Reader: uplinkReader, Writer: downlinkWriter}, dialer); err != nil {
2018-02-08 11:46:50 -05:00
errors.New("failed to handler mux client connection").Base(err).WriteToLog()
}
2018-04-18 16:35:44 -04:00
common.Must(c.done.Close())
2018-02-08 11:46:50 -05:00
cancel()
}()
2017-04-03 06:55:46 -04:00
go c.fetchOutput()
2017-04-05 08:13:26 -04:00
go c.monitor()
2017-04-03 06:55:46 -04:00
return c, nil
2017-02-07 15:11:47 -05:00
}
2017-10-24 11:33:46 -04:00
// Closed returns true if this Client is closed.
2017-04-02 03:48:30 -04:00
func (m *Client) Closed() bool {
2018-02-08 11:46:50 -05:00
return m.done.Done()
2017-03-26 19:47:01 -04:00
}
2017-04-05 08:13:26 -04:00
func (m *Client) monitor() {
2017-04-05 08:26:20 -04:00
defer m.manager.onClientFinish()
2017-05-08 18:01:15 -04:00
timer := time.NewTicker(time.Second * 16)
defer timer.Stop()
2017-04-05 08:13:26 -04:00
for {
select {
2018-04-15 14:40:47 -04:00
case <-m.done.Wait():
m.sessionManager.Close()
2018-05-26 10:32:55 -04:00
common.Close(m.link.Writer) // nolint: errcheck
pipe.CloseError(m.link.Reader) // nolint: errcheck
2017-04-05 08:13:26 -04:00
return
2017-05-08 18:01:15 -04:00
case <-timer.C:
size := m.sessionManager.Size()
2017-04-13 14:14:07 -04:00
if size == 0 && m.sessionManager.CloseIfNoSession() {
2018-04-04 15:33:33 -04:00
common.Must(m.done.Close())
2017-04-05 09:22:21 -04:00
}
2017-04-05 08:13:26 -04:00
}
}
}
func writeFirstPayload(reader buf.Reader, writer *Writer) error {
2018-08-21 17:09:45 -04:00
err := buf.CopyOnceTimeout(reader, writer, time.Millisecond*100)
if err == buf.ErrNotTimeoutReader || err == buf.ErrReadTimeout {
return writer.WriteMultiBuffer(buf.MultiBuffer{})
}
if err != nil {
return err
}
return nil
}
func fetchInput(ctx context.Context, s *Session, output buf.Writer) {
dest := session.OutboundFromContext(ctx).Target
2017-05-02 17:36:37 -04:00
transferType := protocol.TransferTypeStream
if dest.Network == net.Network_UDP {
transferType = protocol.TransferTypePacket
2017-04-03 06:55:46 -04:00
}
2017-05-02 17:36:37 -04:00
s.transferType = transferType
writer := NewWriter(s.ID, dest, output, transferType)
2018-05-26 10:32:55 -04:00
defer s.Close() // nolint: errcheck
defer writer.Close() // nolint: errcheck
2017-04-03 06:55:46 -04:00
newError("dispatching request to ", dest).WriteToLog(session.ExportIDToError(ctx))
if err := writeFirstPayload(s.input, writer); err != nil {
newError("failed to write first payload").Base(err).WriteToLog(session.ExportIDToError(ctx))
writer.hasError = true
pipe.CloseError(s.input)
return
}
2017-04-27 16:30:48 -04:00
if err := buf.Copy(s.input, writer); err != nil {
newError("failed to fetch all input").Base(err).WriteToLog(session.ExportIDToError(ctx))
2018-04-04 15:33:33 -04:00
writer.hasError = true
2018-05-26 10:32:55 -04:00
pipe.CloseError(s.input)
return
2017-04-02 15:30:21 -04:00
}
2017-03-31 18:53:01 -04:00
}
2018-04-16 18:31:10 -04:00
func (m *Client) Dispatch(ctx context.Context, link *core.Link) bool {
2017-04-19 15:27:21 -04:00
sm := m.sessionManager
if sm.Size() >= int(m.concurrency) || sm.Count() >= maxTotal {
2017-04-02 03:48:30 -04:00
return false
}
2018-02-08 11:46:50 -05:00
if m.done.Done() {
2017-04-02 03:48:30 -04:00
return false
}
2017-04-19 15:27:21 -04:00
s := sm.Allocate()
2017-04-13 14:14:07 -04:00
if s == nil {
return false
2017-03-31 18:53:01 -04:00
}
2018-04-16 18:31:10 -04:00
s.input = link.Reader
s.output = link.Writer
go fetchInput(ctx, s, m.link.Writer)
2017-04-02 03:48:30 -04:00
return true
2017-03-31 18:53:01 -04:00
}
2018-04-18 17:01:57 -04:00
func drain(reader buf.Reader) error {
return buf.Copy(reader, buf.Discard)
2017-04-03 17:43:33 -04:00
}
func (m *Client) handleStatueKeepAlive(meta *FrameMetadata, reader *buf.BufferedReader) error {
2017-04-14 04:03:10 -04:00
if meta.Option.Has(OptionData) {
2018-04-18 17:01:57 -04:00
return drain(NewStreamReader(reader))
2017-04-14 04:03:10 -04:00
}
return nil
}
func (m *Client) handleStatusNew(meta *FrameMetadata, reader *buf.BufferedReader) error {
2017-04-14 04:03:10 -04:00
if meta.Option.Has(OptionData) {
2018-04-18 17:01:57 -04:00
return drain(NewStreamReader(reader))
2017-04-14 04:03:10 -04:00
}
return nil
}
func (m *Client) handleStatusKeep(meta *FrameMetadata, reader *buf.BufferedReader) error {
2017-04-14 04:03:10 -04:00
if !meta.Option.Has(OptionData) {
return nil
}
if s, found := m.sessionManager.Get(meta.SessionID); found {
2018-04-18 17:01:57 -04:00
rr := s.NewReader(reader)
if err := buf.Copy(rr, s.output); err != nil {
drain(rr)
2018-04-16 18:31:10 -04:00
pipe.CloseError(s.input)
2018-04-05 06:19:57 -04:00
return s.Close()
}
2018-04-05 14:16:31 -04:00
return nil
2017-04-14 04:03:10 -04:00
}
2018-04-18 17:01:57 -04:00
return drain(NewStreamReader(reader))
2017-04-14 04:03:10 -04:00
}
func (m *Client) handleStatusEnd(meta *FrameMetadata, reader *buf.BufferedReader) error {
2017-04-14 04:03:10 -04:00
if s, found := m.sessionManager.Get(meta.SessionID); found {
2018-04-04 15:33:33 -04:00
if meta.Option.Has(OptionError) {
2018-04-16 18:31:10 -04:00
pipe.CloseError(s.input)
pipe.CloseError(s.output)
2018-04-04 15:33:33 -04:00
}
2018-04-04 11:20:45 -04:00
s.Close()
}
if meta.Option.Has(OptionData) {
2018-04-18 17:01:57 -04:00
return drain(NewStreamReader(reader))
2018-04-04 11:20:45 -04:00
}
return nil
}
2017-03-31 18:53:01 -04:00
func (m *Client) fetchOutput() {
2018-04-18 17:15:57 -04:00
defer func() {
common.Must(m.done.Close())
}()
2017-04-05 08:13:26 -04:00
2018-04-20 18:54:53 -04:00
reader := &buf.BufferedReader{Reader: m.link.Reader}
2017-05-02 16:23:07 -04:00
2018-09-26 07:01:12 -04:00
var meta FrameMetadata
2017-03-31 18:53:01 -04:00
for {
2018-09-26 07:01:12 -04:00
err := meta.ReadFrom(reader)
2017-03-31 18:53:01 -04:00
if err != nil {
2017-04-16 07:24:02 -04:00
if errors.Cause(err) != io.EOF {
2017-12-19 15:28:12 -05:00
newError("failed to read metadata").Base(err).WriteToLog()
2017-04-16 07:24:02 -04:00
}
2017-03-31 18:53:01 -04:00
break
}
2017-04-12 17:55:59 -04:00
switch meta.SessionStatus {
case SessionStatusKeepAlive:
2018-09-26 07:01:12 -04:00
err = m.handleStatueKeepAlive(&meta, reader)
2017-04-12 17:55:59 -04:00
case SessionStatusEnd:
2018-09-26 07:01:12 -04:00
err = m.handleStatusEnd(&meta, reader)
2017-04-12 17:55:59 -04:00
case SessionStatusNew:
2018-09-26 07:01:12 -04:00
err = m.handleStatusNew(&meta, reader)
2017-04-12 17:55:59 -04:00
case SessionStatusKeep:
2018-09-26 07:01:12 -04:00
err = m.handleStatusKeep(&meta, reader)
2017-04-14 04:03:10 -04:00
default:
2018-09-26 07:01:12 -04:00
status := meta.SessionStatus
newError("unknown status: ", status).AtError().WriteToLog()
2017-04-14 04:03:10 -04:00
return
2017-04-03 17:43:33 -04:00
}
2017-04-14 04:03:10 -04:00
if err != nil {
2017-12-19 15:28:12 -05:00
newError("failed to process data").Base(err).WriteToLog()
2017-04-14 04:03:10 -04:00
return
2017-03-31 18:53:01 -04:00
}
}
2017-02-07 15:11:47 -05:00
}
2017-04-02 03:48:30 -04:00
type Server struct {
dispatcher core.Dispatcher
2017-04-02 03:48:30 -04:00
}
2017-04-26 15:43:53 -04:00
// NewServer creates a new mux.Server.
2017-04-02 08:06:20 -04:00
func NewServer(ctx context.Context) *Server {
s := &Server{
2018-02-21 11:05:29 -05:00
dispatcher: core.MustFromContext(ctx).Dispatcher(),
}
2017-04-02 08:06:20 -04:00
return s
}
2018-04-16 18:31:10 -04:00
func (s *Server) Dispatch(ctx context.Context, dest net.Destination) (*core.Link, error) {
2017-05-17 15:13:01 -04:00
if dest.Address != muxCoolAddress {
2017-04-02 03:48:30 -04:00
return s.dispatcher.Dispatch(ctx, dest)
}
2018-05-25 06:08:28 -04:00
opts := pipe.OptionsFromContext(ctx)
uplinkReader, uplinkWriter := pipe.New(opts...)
downlinkReader, downlinkWriter := pipe.New(opts...)
2018-04-16 18:31:10 -04:00
2017-04-02 08:06:20 -04:00
worker := &ServerWorker{
2018-04-16 18:31:10 -04:00
dispatcher: s.dispatcher,
link: &core.Link{
Reader: uplinkReader,
Writer: downlinkWriter,
},
sessionManager: NewSessionManager(),
2017-04-02 08:06:20 -04:00
}
go worker.run(ctx)
2018-04-16 18:31:10 -04:00
return &core.Link{Reader: downlinkReader, Writer: uplinkWriter}, nil
2017-04-02 03:48:30 -04:00
}
2018-05-31 05:55:11 -04:00
// Start implements common.Runnable.
func (s *Server) Start() error {
return nil
}
2018-05-31 05:55:11 -04:00
// Close implements common.Closable.
2018-02-08 09:39:46 -05:00
func (s *Server) Close() error {
return nil
}
2017-04-02 03:48:30 -04:00
type ServerWorker struct {
dispatcher core.Dispatcher
2018-04-16 18:31:10 -04:00
link *core.Link
sessionManager *SessionManager
2017-04-02 03:48:30 -04:00
}
func handle(ctx context.Context, s *Session, output buf.Writer) {
2017-05-02 16:23:07 -04:00
writer := NewResponseWriter(s.ID, output, s.transferType)
2017-04-27 16:30:48 -04:00
if err := buf.Copy(s.input, writer); err != nil {
newError("session ", s.ID, " ends.").Base(err).WriteToLog(session.ExportIDToError(ctx))
2018-04-04 15:33:33 -04:00
writer.hasError = true
2017-04-02 03:48:30 -04:00
}
2018-04-04 15:33:33 -04:00
writer.Close()
2017-05-02 17:53:39 -04:00
s.Close()
2017-04-02 03:48:30 -04:00
}
func (w *ServerWorker) handleStatusKeepAlive(meta *FrameMetadata, reader *buf.BufferedReader) error {
2017-04-14 04:03:10 -04:00
if meta.Option.Has(OptionData) {
2018-04-18 17:01:57 -04:00
return drain(NewStreamReader(reader))
2017-04-14 04:03:10 -04:00
}
return nil
}
func (w *ServerWorker) handleStatusNew(ctx context.Context, meta *FrameMetadata, reader *buf.BufferedReader) error {
newError("received request for ", meta.Target).WriteToLog(session.ExportIDToError(ctx))
2018-04-04 15:33:33 -04:00
{
msg := &log.AccessMessage{
To: meta.Target,
Status: log.AccessAccepted,
Reason: "",
}
if inbound := session.InboundFromContext(ctx); inbound != nil && inbound.Source.IsValid() {
msg.From = inbound.Source
2018-04-04 15:33:33 -04:00
}
log.Record(msg)
}
2018-04-16 18:31:10 -04:00
link, err := w.dispatcher.Dispatch(ctx, meta.Target)
2017-04-14 04:03:10 -04:00
if err != nil {
if meta.Option.Has(OptionData) {
2018-04-18 17:01:57 -04:00
drain(NewStreamReader(reader))
2017-04-14 04:03:10 -04:00
}
return newError("failed to dispatch request.").Base(err)
}
s := &Session{
2018-04-16 18:31:10 -04:00
input: link.Reader,
output: link.Writer,
2017-05-02 16:23:07 -04:00
parent: w.sessionManager,
ID: meta.SessionID,
transferType: protocol.TransferTypeStream,
}
if meta.Target.Network == net.Network_UDP {
s.transferType = protocol.TransferTypePacket
2017-04-14 04:03:10 -04:00
}
w.sessionManager.Add(s)
2018-04-16 18:31:10 -04:00
go handle(ctx, s, w.link.Writer)
2018-04-18 17:01:57 -04:00
if !meta.Option.Has(OptionData) {
return nil
}
rr := s.NewReader(reader)
if err := buf.Copy(rr, s.output); err != nil {
drain(rr)
pipe.CloseError(s.input)
return s.Close()
2017-04-14 04:03:10 -04:00
}
return nil
}
func (w *ServerWorker) handleStatusKeep(meta *FrameMetadata, reader *buf.BufferedReader) error {
2017-04-14 04:03:10 -04:00
if !meta.Option.Has(OptionData) {
return nil
}
if s, found := w.sessionManager.Get(meta.SessionID); found {
2018-04-18 17:01:57 -04:00
rr := s.NewReader(reader)
if err := buf.Copy(rr, s.output); err != nil {
drain(rr)
2018-04-16 18:31:10 -04:00
pipe.CloseError(s.input)
2018-04-05 06:19:57 -04:00
return s.Close()
}
2018-04-05 14:16:31 -04:00
return nil
2017-04-14 04:03:10 -04:00
}
2018-04-18 17:01:57 -04:00
return drain(NewStreamReader(reader))
2017-04-14 04:03:10 -04:00
}
func (w *ServerWorker) handleStatusEnd(meta *FrameMetadata, reader *buf.BufferedReader) error {
2017-04-14 04:03:10 -04:00
if s, found := w.sessionManager.Get(meta.SessionID); found {
2018-04-04 15:33:33 -04:00
if meta.Option.Has(OptionError) {
2018-04-16 18:31:10 -04:00
pipe.CloseError(s.input)
pipe.CloseError(s.output)
2018-04-04 15:33:33 -04:00
}
2018-04-04 11:20:45 -04:00
s.Close()
}
if meta.Option.Has(OptionData) {
2018-04-18 17:01:57 -04:00
return drain(NewStreamReader(reader))
2018-04-04 11:20:45 -04:00
}
return nil
}
func (w *ServerWorker) handleFrame(ctx context.Context, reader *buf.BufferedReader) error {
2018-09-26 07:01:12 -04:00
var meta FrameMetadata
err := meta.ReadFrom(reader)
2017-04-26 15:43:53 -04:00
if err != nil {
return newError("failed to read metadata").Base(err)
}
switch meta.SessionStatus {
case SessionStatusKeepAlive:
2018-09-26 07:01:12 -04:00
err = w.handleStatusKeepAlive(&meta, reader)
2017-04-26 15:43:53 -04:00
case SessionStatusEnd:
2018-09-26 07:01:12 -04:00
err = w.handleStatusEnd(&meta, reader)
2017-04-26 15:43:53 -04:00
case SessionStatusNew:
2018-09-26 07:01:12 -04:00
err = w.handleStatusNew(ctx, &meta, reader)
2017-04-26 15:43:53 -04:00
case SessionStatusKeep:
2018-09-26 07:01:12 -04:00
err = w.handleStatusKeep(&meta, reader)
2017-04-26 15:43:53 -04:00
default:
2018-09-26 07:01:12 -04:00
status := meta.SessionStatus
return newError("unknown status: ", status).AtError()
2017-04-26 15:43:53 -04:00
}
if err != nil {
return newError("failed to process data").Base(err)
}
return nil
}
2017-04-02 03:48:30 -04:00
func (w *ServerWorker) run(ctx context.Context) {
2018-04-16 18:31:10 -04:00
input := w.link.Reader
2018-04-20 18:54:53 -04:00
reader := &buf.BufferedReader{Reader: input}
2018-05-31 05:55:11 -04:00
defer w.sessionManager.Close() // nolint: errcheck
2017-04-14 04:03:10 -04:00
2017-04-02 03:48:30 -04:00
for {
select {
case <-ctx.Done():
return
default:
2017-10-27 10:32:00 -04:00
err := w.handleFrame(ctx, reader)
2017-04-26 15:43:53 -04:00
if err != nil {
if errors.Cause(err) != io.EOF {
newError("unexpected EOF").Base(err).WriteToLog(session.ExportIDToError(ctx))
2018-04-16 18:31:10 -04:00
pipe.CloseError(input)
2017-04-26 15:43:53 -04:00
}
return
}
2017-04-02 03:48:30 -04:00
}
}
}