mirror of
https://github.com/XTLS/Xray-core.git
synced 2026-11-27 03:50:08 +00:00
VLESS Multiplex, Reverse Proxy: Refactor to move code into VLESS; Mux only uses settings.multiplex in VLESS/VMess outbound (#7364)
https://github.com/XTLS/Xray-core/pull/6748#issuecomment-5752780799 https://github.com/XTLS/Xray-core/issues/7240#issuecomment-6439951754 https://github.com/XTLS/Xray-core/pull/4231#issuecomment-6679992732 https://github.com/XTLS/Xray-core/pull/7355#issuecomment-6739539943 https://github.com/XTLS/Xray-core/pull/7359#issuecomment-6742147165 https://github.com/XTLS/Xray-core/pull/7364#issuecomment-6784892866 https://github.com/XTLS/Xray-core/pull/7364#issuecomment-6812285253 https://github.com/XTLS/Xray-core/pull/7364#issuecomment-6842747639 https://github.com/XTLS/Xray-core/pull/4231#issuecomment-7012427059 https://github.com/XTLS/Xray-core/pull/7364#issuecomment-7108550396 https://github.com/XTLS/Xray-core/pull/7364#issuecomment-7129493942 https://github.com/XTLS/Xray-core/pull/7364#issuecomment-7130454962 --------- Co-authored-by: Codex <codex@users.noreply.github.com> Co-authored-by: RPRX <63339210+RPRX@users.noreply.github.com>
This commit is contained in:
committed by
RPRXX
co-authored by
Codex
RPRX
parent
15b2499d34
commit
e17392a96e
@@ -0,0 +1,256 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
)
|
||||
|
||||
// Control intents carry no encoded DATA or caller payload.
|
||||
type carrier struct {
|
||||
sync.RWMutex
|
||||
sessions map[uint16]*Session
|
||||
|
||||
ready map[uint16]*Session // nil is a bounded END for an unknown wire ID
|
||||
unknown int
|
||||
count uint16
|
||||
active int
|
||||
client bool
|
||||
link transport.Link
|
||||
writeMutex sync.Mutex
|
||||
control *sync.Cond
|
||||
ctx context.Context
|
||||
cancel context.CancelCauseFunc
|
||||
timer *time.Timer
|
||||
}
|
||||
|
||||
func newCarrier(parent context.Context, link transport.Link, idle time.Duration, client bool) *carrier {
|
||||
ctx, cancel := context.WithCancelCause(parent)
|
||||
c := &carrier{
|
||||
sessions: make(map[uint16]*Session, 16), link: link, ctx: ctx, cancel: cancel,
|
||||
client: client,
|
||||
}
|
||||
c.control = sync.NewCond(&c.RWMutex)
|
||||
c.ready = make(map[uint16]*Session)
|
||||
context.AfterFunc(c.ctx, func() { common.Interrupt(c.link.Reader) })
|
||||
c.Lock()
|
||||
checkSize, checkCount := c.active, c.count
|
||||
c.timer = time.AfterFunc(idle, func() {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
if c.Closed() {
|
||||
return
|
||||
}
|
||||
if c.active == 0 && checkSize == 0 && c.count == checkCount {
|
||||
c.cancel(nil)
|
||||
return
|
||||
}
|
||||
checkSize, checkCount = c.active, c.count
|
||||
c.timer.Reset(idle)
|
||||
})
|
||||
c.Unlock()
|
||||
context.AfterFunc(c.ctx, c.shutdown)
|
||||
go c.controlLoop()
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *carrier) admitLocked(s *Session) bool {
|
||||
if c.Closed() || s.phase != outputOpen || c.sessions[s.ID] != nil {
|
||||
return false
|
||||
}
|
||||
c.count++
|
||||
c.active++
|
||||
c.invalidateUnknownLocked(s.ID)
|
||||
c.sessions[s.ID] = s
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *carrier) queueReadyLocked(s *Session) {
|
||||
if c.ready[s.ID] != s {
|
||||
c.ready[s.ID] = s
|
||||
c.control.Broadcast()
|
||||
}
|
||||
}
|
||||
|
||||
func (c *carrier) scheduleLocked(s *Session) {
|
||||
if !c.Closed() && c.sessions[s.ID] == s && (s.phase == outputDone || s.packetReady()) {
|
||||
c.queueReadyLocked(s)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *carrier) invalidateUnknownLocked(id uint16) bool {
|
||||
if s, ok := c.ready[id]; ok && s == nil {
|
||||
delete(c.ready, id)
|
||||
c.unknown--
|
||||
c.control.Broadcast()
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *carrier) unknownEnd(id uint16) {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
for !c.Closed() {
|
||||
if _, queued := c.ready[id]; queued || c.sessions[id] != nil {
|
||||
return
|
||||
}
|
||||
if c.unknown < 16 {
|
||||
c.ready[id] = nil
|
||||
c.unknown++
|
||||
c.control.Broadcast()
|
||||
return
|
||||
}
|
||||
c.control.Wait()
|
||||
}
|
||||
}
|
||||
|
||||
func (c *carrier) controlLoop() {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
for !c.Closed() {
|
||||
if len(c.ready) == 0 {
|
||||
c.control.Wait()
|
||||
continue
|
||||
}
|
||||
// Advance the iterator under the lock. Physical sends never hold it.
|
||||
for id, selected := range c.ready {
|
||||
c.Unlock()
|
||||
c.writeMutex.Lock()
|
||||
var frames buf.MultiBuffer
|
||||
var err error
|
||||
raw, terminal := c.responseTurn(id, selected)
|
||||
if terminal {
|
||||
frames = endFrame(id, selected != nil && selected.endFailed)
|
||||
} else if len(raw) != 0 {
|
||||
frames, err = selected.encodeBatch(&raw)
|
||||
buf.ReleaseMulti(raw)
|
||||
}
|
||||
err = c.writeAndUnlock(frames, err)
|
||||
c.Lock()
|
||||
if err != nil || c.Closed() {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// No logical lock spans physical I/O or a codec/address callback.
|
||||
func (c *carrier) writeAndUnlock(frames buf.MultiBuffer, err error) error {
|
||||
if err != nil || c.Closed() {
|
||||
buf.ReleaseMulti(frames)
|
||||
} else if len(frames) != 0 {
|
||||
if r, ok := c.link.Reader.(*responseReader); ok {
|
||||
r.activity.Update()
|
||||
}
|
||||
err = c.link.Writer.WriteMultiBuffer(frames)
|
||||
}
|
||||
if err != nil {
|
||||
c.cancel(err)
|
||||
}
|
||||
c.writeMutex.Unlock()
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *carrier) ActiveConnections() uint32 {
|
||||
c.RLock()
|
||||
defer c.RUnlock()
|
||||
return uint32(c.active)
|
||||
}
|
||||
func (c *carrier) Closed() bool { return c.ctx.Err() != nil }
|
||||
func (c *carrier) WaitClosed() <-chan struct{} { return c.ctx.Done() }
|
||||
|
||||
// Err reports the first close cause, excluding normal cancellation.
|
||||
func (c *carrier) Err() error {
|
||||
err := context.Cause(c.ctx)
|
||||
if err == context.Canceled {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *carrier) Close() error {
|
||||
c.cancel(nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *carrier) shutdown() {
|
||||
c.Lock()
|
||||
c.timer.Stop()
|
||||
c.ready = nil
|
||||
c.control.Broadcast()
|
||||
sessions := c.sessions
|
||||
c.sessions, c.active = nil, 0
|
||||
c.Unlock()
|
||||
for _, s := range sessions {
|
||||
s.abort()
|
||||
}
|
||||
common.Interrupt(c.link.Writer)
|
||||
}
|
||||
|
||||
func (c *carrier) readFrame(ctx context.Context, meta *FrameMetadata, reader *buf.BufferedReader, accept func(context.Context, *FrameMetadata, *buf.BufferedReader) error) error {
|
||||
var target *Session
|
||||
data := meta.Option.Has(OptionData)
|
||||
switch meta.SessionStatus {
|
||||
case SessionStatusNew:
|
||||
if accept != nil {
|
||||
return accept(session.ContextWithIsReverseMux(ctx, false), meta, reader)
|
||||
}
|
||||
case SessionStatusKeep:
|
||||
if !data {
|
||||
return nil
|
||||
}
|
||||
c.RLock()
|
||||
s, found := c.sessions[meta.SessionID]
|
||||
if found && s.phase == outputOpen {
|
||||
target = s
|
||||
}
|
||||
c.RUnlock()
|
||||
if !found && !c.client {
|
||||
c.unknownEnd(meta.SessionID)
|
||||
}
|
||||
case SessionStatusEnd:
|
||||
c.RLock()
|
||||
s := c.sessions[meta.SessionID]
|
||||
c.RUnlock()
|
||||
if s != nil {
|
||||
s.abort()
|
||||
}
|
||||
case SessionStatusKeepAlive:
|
||||
default:
|
||||
return errors.New("unknown status: ", meta.SessionStatus)
|
||||
}
|
||||
if data {
|
||||
return copyFramePayload(reader, target, meta.Target)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *carrier) run(ctx context.Context, accept func(context.Context, *FrameMetadata, *buf.BufferedReader) error) {
|
||||
var err error
|
||||
defer func() { c.cancel(err) }()
|
||||
reader := &buf.BufferedReader{Reader: c.link.Reader}
|
||||
defer func() { buf.ReleaseMulti(reader.Buffer) }()
|
||||
for !c.Closed() {
|
||||
var meta FrameMetadata
|
||||
err = meta.Unmarshal(reader, session.IsReverseMuxFromContext(ctx))
|
||||
if errors.Cause(err) == io.EOF {
|
||||
err = nil // clean EOF before the next metadata prefix
|
||||
return
|
||||
}
|
||||
if err == nil {
|
||||
err = frameReadError(c.readFrame(ctx, &meta, reader, accept))
|
||||
}
|
||||
if err != nil {
|
||||
errors.LogInfoInner(ctx, err, "failed to process multiplex frame")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"slices"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/proxy/vless"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
)
|
||||
|
||||
// NormalizeConfig validates the pool settings and returns nil when both pools are off.
|
||||
func NormalizeConfig(config *vless.Multiplex) (*vless.Multiplex, error) {
|
||||
if config.GetConcurrency() < 0 || config.GetXudpConcurrency() < 0 {
|
||||
return nil, errors.New(`multiplex "concurrency" and "xudpConcurrency" must be non-negative`)
|
||||
}
|
||||
switch config.GetXudpProxyUDP443() {
|
||||
case "", "reject", "allow", "skip":
|
||||
default:
|
||||
return nil, errors.New(`unknown "xudpProxyUDP443": `, config.GetXudpProxyUDP443())
|
||||
}
|
||||
if config.GetConcurrency() == 0 && config.GetXudpConcurrency() == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return config, nil
|
||||
}
|
||||
|
||||
// Client owns the logical stream pools.
|
||||
type Client struct {
|
||||
config *vless.Multiplex
|
||||
tcp *Pool
|
||||
udp *Pool
|
||||
}
|
||||
|
||||
func NewClient(ctx context.Context, config *vless.Multiplex, network string, open func(context.Context) (context.Context, *transport.Link, error)) *Client {
|
||||
c := &Client{config: config}
|
||||
pool := func(concurrency int32) *Pool {
|
||||
return NewPool(ctx, ClientStrategy{MaxConcurrency: uint32(concurrency), MaxConnection: 1024}, open)
|
||||
}
|
||||
if concurrency := config.GetConcurrency(); concurrency > 0 {
|
||||
if network == "xdrive" {
|
||||
concurrency = max(concurrency, 128)
|
||||
}
|
||||
c.tcp = pool(concurrency)
|
||||
}
|
||||
if concurrency := config.GetXudpConcurrency(); concurrency > 0 {
|
||||
c.udp = pool(concurrency)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *Client) Dispatch(ctx context.Context, link *transport.Link) (bool, error) {
|
||||
if c == nil {
|
||||
return false, nil
|
||||
}
|
||||
pool := c.tcp
|
||||
outbounds := session.OutboundsFromContext(ctx)
|
||||
target := outbounds[len(outbounds)-1].Target
|
||||
if target.Network == net.Network_UDP && c.udp != nil {
|
||||
pool = c.udp
|
||||
}
|
||||
if pool == nil {
|
||||
return false, nil
|
||||
}
|
||||
if target.Network == net.Network_UDP && target.Port == 443 {
|
||||
switch c.config.GetXudpProxyUDP443() {
|
||||
case "reject", "":
|
||||
return true, errors.New("XUDP rejected UDP/443 traffic")
|
||||
case "skip":
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
return true, Dispatch(ctx, link, pool.Admit)
|
||||
}
|
||||
|
||||
type deferredWriterClose struct{}
|
||||
|
||||
func (deferredWriterClose) Error() string { return "defer link writer close" }
|
||||
func (deferredWriterClose) DeferWriterClose() bool { return true }
|
||||
|
||||
// Dispatch runs a logical child. The caller owns the application endpoints.
|
||||
func Dispatch(ctx context.Context, link *transport.Link, admit func(context.Context, *Session) error, finish ...func(context.Context)) error {
|
||||
s := NewSession(ctx, link)
|
||||
if err := admit(ctx, s); err != nil {
|
||||
return err
|
||||
}
|
||||
go fetchInput(ctx, s)
|
||||
callerDone := ctx.Done()
|
||||
if session.TimeoutOnlyFromContext(ctx) {
|
||||
callerDone = nil
|
||||
}
|
||||
select {
|
||||
case <-callerDone:
|
||||
s.Close()
|
||||
case <-s.WaitClosed():
|
||||
}
|
||||
// The session is sealed. Only a response write already in progress can
|
||||
// still hold the application writer.
|
||||
writingResponse := s.writingResponse.Load()
|
||||
if len(finish) != 0 {
|
||||
if writingResponse {
|
||||
go finish[0](s.parent.ctx)
|
||||
} else {
|
||||
finish[0](s.parent.ctx)
|
||||
}
|
||||
} else if writingResponse {
|
||||
return deferredWriterClose{}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Pool serializes unpublished opening with cancelable admission.
|
||||
type Pool struct {
|
||||
ctx context.Context
|
||||
access sync.Mutex
|
||||
opening chan struct{}
|
||||
workers []*ClientWorker
|
||||
strategy ClientStrategy
|
||||
open func(context.Context) (context.Context, *transport.Link, error)
|
||||
}
|
||||
|
||||
// NewPool borrows ctx; open must return a context derived from its input context.
|
||||
func NewPool(ctx context.Context, strategy ClientStrategy, open func(context.Context) (context.Context, *transport.Link, error)) *Pool {
|
||||
return &Pool{ctx: ctx, strategy: strategy, open: open}
|
||||
}
|
||||
|
||||
func (p *Pool) Admit(ctx context.Context, s *Session) error {
|
||||
p.access.Lock()
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
p.access.Unlock()
|
||||
return err
|
||||
}
|
||||
if p.ctx.Err() != nil {
|
||||
p.access.Unlock()
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
for _, worker := range p.workers {
|
||||
if worker.TryAdmit(ctx, s) {
|
||||
p.access.Unlock()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if p.opening == nil {
|
||||
p.opening = make(chan struct{})
|
||||
break
|
||||
}
|
||||
wait := p.opening
|
||||
p.access.Unlock()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-p.ctx.Done():
|
||||
return io.ErrClosedPipe
|
||||
case <-wait:
|
||||
}
|
||||
p.access.Lock()
|
||||
}
|
||||
p.access.Unlock()
|
||||
opening, cancel := context.WithCancel(p.ctx)
|
||||
stopCaller := context.AfterFunc(ctx, cancel)
|
||||
physicalCtx, physicalLink, err := p.open(opening)
|
||||
if !stopCaller() && err == nil {
|
||||
err = context.Canceled
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
err = ctx.Err()
|
||||
}
|
||||
if p.ctx.Err() != nil {
|
||||
err = io.ErrClosedPipe
|
||||
}
|
||||
p.access.Lock()
|
||||
close(p.opening)
|
||||
p.opening = nil
|
||||
var worker *ClientWorker
|
||||
if err == nil {
|
||||
worker = NewClientWorker(physicalCtx, *physicalLink, p.strategy)
|
||||
if !worker.TryAdmit(ctx, s) {
|
||||
err = ctx.Err()
|
||||
if err == nil {
|
||||
err = errors.New("unable to admit multiplex child")
|
||||
}
|
||||
} else {
|
||||
p.workers = append(p.workers, worker)
|
||||
}
|
||||
}
|
||||
p.access.Unlock()
|
||||
if err != nil {
|
||||
cancel()
|
||||
if physicalLink != nil {
|
||||
common.Interrupt(physicalLink.Reader)
|
||||
common.Interrupt(physicalLink.Writer)
|
||||
}
|
||||
return err
|
||||
}
|
||||
context.AfterFunc(worker.ctx, func() {
|
||||
cancel()
|
||||
p.access.Lock()
|
||||
p.workers = slices.DeleteFunc(p.workers, func(current *ClientWorker) bool { return current == worker })
|
||||
p.access.Unlock()
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
type ClientStrategy struct {
|
||||
MaxConcurrency uint32
|
||||
MaxConnection uint32
|
||||
}
|
||||
|
||||
type ClientWorker struct {
|
||||
*carrier
|
||||
strategy ClientStrategy
|
||||
}
|
||||
|
||||
func NewClientWorker(ctx context.Context, stream transport.Link, strategy ClientStrategy) *ClientWorker {
|
||||
c := &ClientWorker{carrier: newCarrier(ctx, stream, 16*time.Second, true), strategy: strategy}
|
||||
go c.run(context.Background(), nil)
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *ClientWorker) TotalConnections() uint32 {
|
||||
c.RLock()
|
||||
defer c.RUnlock()
|
||||
return uint32(c.count)
|
||||
}
|
||||
|
||||
func writeFirstPayload(s *Session) error {
|
||||
err := buf.CopyOnceTimeout(s.input, s, time.Millisecond*100)
|
||||
if err == buf.ErrNotTimeoutReader || err == buf.ErrReadTimeout {
|
||||
return s.WriteMultiBuffer(nil)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func fetchInput(ctx context.Context, s *Session) {
|
||||
var err error
|
||||
defer func() { s.CloseWithError(err) }()
|
||||
errors.LogInfo(ctx, "dispatching request to ", s.target)
|
||||
if err = writeFirstPayload(s); err != nil {
|
||||
errors.LogInfoInner(ctx, err, "failed to write first payload")
|
||||
return
|
||||
}
|
||||
if err = buf.Copy(s.input, s); err != nil {
|
||||
errors.LogInfoInner(ctx, err, "failed to fetch all input")
|
||||
}
|
||||
}
|
||||
|
||||
// TryAdmit publishes this prepared child without input or foreign cleanup.
|
||||
func (m *ClientWorker) TryAdmit(ctx context.Context, s *Session) bool {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
if ctx.Err() != nil || m.Closed() || m.count == 65535 ||
|
||||
(m.strategy.MaxConcurrency > 0 && m.active >= int(m.strategy.MaxConcurrency)) ||
|
||||
(m.strategy.MaxConnection > 0 && uint32(m.count) >= m.strategy.MaxConnection) {
|
||||
return false
|
||||
}
|
||||
s.parent, s.ID, s.phase, s.done = m.carrier, m.count+1, outputOpen, make(chan struct{})
|
||||
return m.admitLocked(s)
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/proxy/vless"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
)
|
||||
|
||||
func TestClientUDP443Policy(t *testing.T) {
|
||||
ctx := session.ContextWithOutbounds(t.Context(), []*session.Outbound{{
|
||||
Target: net.UDPDestination(net.LocalHostIP, 443),
|
||||
}})
|
||||
for _, policy := range []string{"reject", "skip"} {
|
||||
t.Run(policy, func(t *testing.T) {
|
||||
opened := false
|
||||
client := NewClient(ctx, &vless.Multiplex{Concurrency: 1, XudpProxyUDP443: policy}, "", func(context.Context) (context.Context, *transport.Link, error) {
|
||||
opened = true
|
||||
return nil, nil, context.Canceled
|
||||
})
|
||||
handled, err := client.Dispatch(ctx, &transport.Link{})
|
||||
wantRejected := policy == "reject"
|
||||
if opened || handled != wantRejected || (err != nil) != wantRejected {
|
||||
t.Fatalf("Dispatch() = (%t, %v), opened carrier = %t, want rejected = %t without opening a carrier", handled, err, opened, wantRejected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientWithoutPoolLeavesUDP443ToOutbound(t *testing.T) {
|
||||
ctx := session.ContextWithOutbounds(t.Context(), []*session.Outbound{{
|
||||
Target: net.UDPDestination(net.LocalHostIP, 443),
|
||||
}})
|
||||
client := NewClient(ctx, &vless.Multiplex{XudpProxyUDP443: "reject"}, "", nil)
|
||||
if handled, err := client.Dispatch(ctx, &transport.Link{}); handled || err != nil {
|
||||
t.Fatalf("Dispatch without a pool = (%t, %v), want fallback", handled, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolFailure(t *testing.T) {
|
||||
calls := 0
|
||||
owner, stop := context.WithCancel(context.Background())
|
||||
defer stop()
|
||||
pool := NewPool(owner, ClientStrategy{}, func(context.Context) (context.Context, *transport.Link, error) {
|
||||
calls++
|
||||
return nil, nil, errors.New("test")
|
||||
})
|
||||
ctx := testOutboundContext()
|
||||
s := NewSession(ctx, &transport.Link{Writer: buf.Discard})
|
||||
if err := pool.Admit(ctx, s); err == nil || calls != 1 {
|
||||
t.Fatalf("expected one failed opening, got %d calls and %v", calls, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientWorkerEOF(t *testing.T) {
|
||||
reader, writer := pipe.New(pipe.WithoutSizeLimit())
|
||||
common.Must(writer.Close())
|
||||
|
||||
worker := NewClientWorker(context.Background(), transport.Link{Reader: reader, Writer: writer}, ClientStrategy{})
|
||||
|
||||
select {
|
||||
case <-worker.WaitClosed():
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("worker did not close after EOF")
|
||||
}
|
||||
|
||||
ctx := testOutboundContext()
|
||||
f := worker.TryAdmit(ctx, NewSession(ctx, &transport.Link{Writer: buf.Discard}))
|
||||
if f {
|
||||
t.Error("expected failed dispatching, but actually not")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientWorkerClose(t *testing.T) {
|
||||
r1, w1 := pipe.New(pipe.WithoutSizeLimit())
|
||||
r2, w2 := pipe.New(pipe.WithoutSizeLimit())
|
||||
links := []*transport.Link{{Reader: r1, Writer: w1}, {Reader: r2, Writer: w2}}
|
||||
owner, stop := context.WithCancel(context.Background())
|
||||
defer stop()
|
||||
pool := NewPool(owner, ClientStrategy{MaxConcurrency: 4, MaxConnection: 4}, func(ctx context.Context) (context.Context, *transport.Link, error) {
|
||||
if len(links) == 0 {
|
||||
return nil, nil, errors.New("unexpected opening")
|
||||
}
|
||||
link := links[0]
|
||||
links = links[1:]
|
||||
return ctx, link, nil
|
||||
})
|
||||
ctx := testOutboundContext()
|
||||
worker1 := NewSession(ctx, &transport.Link{Writer: buf.Discard})
|
||||
common.Must(pool.Admit(ctx, worker1))
|
||||
tr1, tw1 := pipe.New(pipe.WithoutSizeLimit())
|
||||
ctx1 := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{Target: net.TCPDestination(net.DomainAddress("www.example.com"), 80)}})
|
||||
child1 := NewSession(ctx1, &transport.Link{Reader: tr1, Writer: tw1})
|
||||
common.Must(pool.Admit(ctx1, child1))
|
||||
go fetchInput(ctx1, child1)
|
||||
defer tw1.Close()
|
||||
common.Must(w1.Close())
|
||||
select {
|
||||
case <-worker1.parent.WaitClosed():
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("first worker did not close")
|
||||
}
|
||||
tr2, tw2 := pipe.New(pipe.WithoutSizeLimit())
|
||||
ctx2 := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{Target: net.TCPDestination(net.DomainAddress("www.example.com"), 80)}})
|
||||
child2 := NewSession(ctx2, &transport.Link{Reader: tr2, Writer: tw2})
|
||||
common.Must(pool.Admit(ctx2, child2))
|
||||
go fetchInput(ctx2, child2)
|
||||
defer tw2.Close()
|
||||
common.Must(w2.Close())
|
||||
}
|
||||
|
||||
func TestClientWorkerUDPSource(t *testing.T) {
|
||||
downR, downW := pipe.New(pipe.WithoutSizeLimit())
|
||||
upR, upW := pipe.New(pipe.WithoutSizeLimit())
|
||||
worker := NewClientWorker(context.Background(), transport.Link{Reader: downR, Writer: upW}, ClientStrategy{})
|
||||
t.Cleanup(func() {
|
||||
worker.Close()
|
||||
downW.Close()
|
||||
upR.Interrupt()
|
||||
})
|
||||
|
||||
inR, inW := pipe.New(pipe.WithoutSizeLimit())
|
||||
outR, outW := pipe.New(pipe.WithoutSizeLimit())
|
||||
t.Cleanup(func() {
|
||||
inW.Close()
|
||||
outR.Interrupt()
|
||||
})
|
||||
ctx := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{
|
||||
Target: net.UDPDestination(net.ParseAddress("8.8.8.8"), 53),
|
||||
}})
|
||||
child := NewSession(ctx, &transport.Link{Reader: inR, Writer: outW})
|
||||
if !worker.TryAdmit(ctx, child) {
|
||||
t.Fatal("failed to dispatch")
|
||||
}
|
||||
go fetchInput(ctx, child)
|
||||
b := buf.New()
|
||||
b.WriteString("query")
|
||||
common.Must(inW.WriteMultiBuffer(buf.MultiBuffer{b}))
|
||||
mb, err := upR.ReadMultiBuffer() // New frame, the session is UDP from now on
|
||||
common.Must(err)
|
||||
buf.ReleaseMulti(mb)
|
||||
|
||||
srcs := []net.Destination{
|
||||
net.UDPDestination(net.ParseAddress("1.1.1.1"), 1111),
|
||||
net.UDPDestination(net.DomainAddress("example.com"), 2222),
|
||||
net.UDPDestination(net.ParseAddress("3.3.3.3"), 3333),
|
||||
}
|
||||
response := &Session{ID: 1, target: net.Destination{Network: net.Network_UDP}}
|
||||
var got buf.MultiBuffer
|
||||
defer func() { buf.ReleaseMulti(got) }()
|
||||
for i := range srcs {
|
||||
b := buf.New()
|
||||
b.WriteString("reply")
|
||||
b.UDP = &srcs[i]
|
||||
data := buf.MultiBuffer{b}
|
||||
frames, err := response.encodeBatch(&data)
|
||||
buf.ReleaseMulti(data)
|
||||
if err != nil {
|
||||
buf.ReleaseMulti(frames)
|
||||
t.Fatal(err)
|
||||
}
|
||||
common.Must(downW.WriteMultiBuffer(frames))
|
||||
// keep earlier replies around while the next frame is parsed
|
||||
mb, err := outR.ReadMultiBuffer()
|
||||
common.Must(err)
|
||||
got = append(got, mb...)
|
||||
}
|
||||
if len(got) != len(srcs) {
|
||||
t.Fatalf("received %d replies, want %d", len(got), len(srcs))
|
||||
}
|
||||
for i, b := range got {
|
||||
if string(b.Bytes()) != "reply" {
|
||||
t.Errorf("reply %d: payload = %q", i, b.Bytes())
|
||||
}
|
||||
if b.UDP == nil || *b.UDP != srcs[i] {
|
||||
t.Errorf("reply %d: source = %v, want %v", i, b.UDP, srcs[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testOutboundContext() context.Context {
|
||||
return session.ContextWithOutbounds(context.Background(), []*session.Outbound{{Target: net.TCPDestination(net.DomainAddress("www.example.com"), 80)}})
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/signal"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
)
|
||||
|
||||
type responseReader struct {
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
activity *signal.ActivityTimer
|
||||
open func() (buf.Reader, error)
|
||||
body buf.Reader
|
||||
terminal error
|
||||
}
|
||||
|
||||
func (r *responseReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
|
||||
if err := r.ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if r.open != nil {
|
||||
r.body, r.terminal = r.open()
|
||||
r.open = nil
|
||||
}
|
||||
for r.terminal == nil {
|
||||
data, err := r.body.ReadMultiBuffer()
|
||||
r.terminal = err
|
||||
if err := r.ctx.Err(); err != nil {
|
||||
buf.ReleaseMulti(data)
|
||||
return nil, err
|
||||
}
|
||||
if !data.IsEmpty() {
|
||||
r.activity.Update()
|
||||
return data, nil
|
||||
}
|
||||
buf.ReleaseMulti(data)
|
||||
}
|
||||
return nil, r.terminal
|
||||
}
|
||||
|
||||
func (r *responseReader) Interrupt() {
|
||||
r.cancel()
|
||||
r.activity.SetTimeout(0)
|
||||
}
|
||||
|
||||
func OpenLink(ctx context.Context, cancel context.CancelFunc, writer buf.Writer, activity *signal.ActivityTimer, openResponse func() (buf.Reader, error)) (*transport.Link, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
cancel()
|
||||
activity.SetTimeout(0)
|
||||
return nil, err
|
||||
}
|
||||
return &transport.Link{Reader: &responseReader{ctx: ctx, cancel: cancel, activity: activity, open: openResponse}, Writer: writer}, nil
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"io"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/bitmask"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/common/xudp"
|
||||
)
|
||||
|
||||
type SessionStatus byte
|
||||
|
||||
const (
|
||||
SessionStatusNew SessionStatus = 0x01
|
||||
SessionStatusKeep SessionStatus = 0x02
|
||||
SessionStatusEnd SessionStatus = 0x03
|
||||
SessionStatusKeepAlive SessionStatus = 0x04
|
||||
)
|
||||
|
||||
const (
|
||||
OptionData bitmask.Byte = 0x01
|
||||
OptionError bitmask.Byte = 0x02
|
||||
)
|
||||
|
||||
type TargetNetwork byte
|
||||
|
||||
const (
|
||||
TargetNetworkTCP TargetNetwork = 0x01
|
||||
TargetNetworkUDP TargetNetwork = 0x02
|
||||
)
|
||||
|
||||
var addrParser = xudp.AddrParser
|
||||
|
||||
/*
|
||||
Frame format
|
||||
2 bytes - length
|
||||
2 bytes - session id
|
||||
1 bytes - status
|
||||
1 bytes - option
|
||||
|
||||
1 byte - network
|
||||
2 bytes - port
|
||||
n bytes - address
|
||||
|
||||
*/
|
||||
|
||||
type FrameMetadata struct {
|
||||
Target net.Destination
|
||||
SessionID uint16
|
||||
Option bitmask.Byte
|
||||
SessionStatus SessionStatus
|
||||
GlobalID [8]byte
|
||||
Inbound *session.Inbound
|
||||
}
|
||||
|
||||
func (f FrameMetadata) WriteTo(b *buf.Buffer) error {
|
||||
lenBytes := b.Extend(2)
|
||||
|
||||
len0 := b.Len()
|
||||
sessionBytes := b.Extend(2)
|
||||
binary.BigEndian.PutUint16(sessionBytes, f.SessionID)
|
||||
|
||||
common.Must(b.WriteByte(byte(f.SessionStatus)))
|
||||
common.Must(b.WriteByte(byte(f.Option)))
|
||||
|
||||
if f.SessionStatus == SessionStatusNew {
|
||||
switch f.Target.Network {
|
||||
case net.Network_TCP:
|
||||
common.Must(b.WriteByte(byte(TargetNetworkTCP)))
|
||||
case net.Network_UDP:
|
||||
common.Must(b.WriteByte(byte(TargetNetworkUDP)))
|
||||
}
|
||||
if err := addrParser.WriteAddressPort(b, f.Target.Address, f.Target.Port); err != nil {
|
||||
return err
|
||||
}
|
||||
if f.Inbound != nil {
|
||||
for _, dst := range [...]net.Destination{f.Inbound.Source, f.Inbound.Local} {
|
||||
if dst.Network != net.Network_TCP && dst.Network != net.Network_UDP {
|
||||
break
|
||||
}
|
||||
common.Must(b.WriteByte(byte(dst.Network - 1)))
|
||||
if err := addrParser.WriteAddressPort(b, dst.Address, dst.Port); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else if b.UDP != nil { // make sure it's user's proxy request
|
||||
b.Write(f.GlobalID[:]) // no need to check whether it's empty
|
||||
}
|
||||
} else if b.UDP != nil {
|
||||
b.WriteByte(byte(TargetNetworkUDP))
|
||||
addrParser.WriteAddressPort(b, b.UDP.Address, b.UDP.Port)
|
||||
}
|
||||
|
||||
len1 := b.Len()
|
||||
binary.BigEndian.PutUint16(lenBytes, uint16(len1-len0))
|
||||
return nil
|
||||
}
|
||||
|
||||
// Unmarshal reads FrameMetadata from the given reader.
|
||||
func (f *FrameMetadata) Unmarshal(reader io.Reader, readSourceAndLocal bool) error {
|
||||
b, err := readBlock(reader, 512, "invalid metalen ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer b.Release()
|
||||
return frameReadError(f.UnmarshalFromBuffer(b, readSourceAndLocal))
|
||||
}
|
||||
|
||||
// UnmarshalFromBuffer reads a FrameMetadata from the given buffer.
|
||||
// Visible for testing only.
|
||||
func (f *FrameMetadata) UnmarshalFromBuffer(b *buf.Buffer, readSourceAndLocal bool) error {
|
||||
if b.Len() < 4 {
|
||||
return errors.New("insufficient buffer: ", b.Len())
|
||||
}
|
||||
|
||||
f.SessionID = binary.BigEndian.Uint16(b.BytesTo(2))
|
||||
f.SessionStatus = SessionStatus(b.Byte(2))
|
||||
f.Option = bitmask.Byte(b.Byte(3))
|
||||
f.Target.Network = net.Network_Unknown
|
||||
|
||||
if f.SessionStatus == SessionStatusNew || (f.SessionStatus == SessionStatusKeep && b.Len() > 4 &&
|
||||
TargetNetwork(b.Byte(4)) == TargetNetworkUDP) { // MUST check the flag first
|
||||
if b.Len() < 8 {
|
||||
return errors.New("insufficient buffer: ", b.Len())
|
||||
}
|
||||
b.Advance(4)
|
||||
target, err := readDestination(b, "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
f.Target = target
|
||||
}
|
||||
|
||||
if f.SessionStatus == SessionStatusNew && readSourceAndLocal {
|
||||
f.Inbound = &session.Inbound{}
|
||||
for i, dst := range [...]*net.Destination{&f.Inbound.Source, &f.Inbound.Local} {
|
||||
if b.Len() == 0 || b.Byte(0) == 0 { // heartbeat, absent endpoint, or padding
|
||||
break
|
||||
}
|
||||
parsed, err := readDestination(b, [...]string{"reading source: ", "reading local: "}[i])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*dst = parsed
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if f.SessionStatus == SessionStatusNew && f.Option.Has(OptionData) &&
|
||||
f.Target.Network == net.Network_UDP && b.Len() >= 8 {
|
||||
copy(f.GlobalID[:], b.Bytes())
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func readDestination(b *buf.Buffer, prefix string) (net.Destination, error) {
|
||||
network := TargetNetwork(b.Byte(0))
|
||||
b.Advance(1)
|
||||
addr, port, err := addrParser.ReadAddressPort(nil, b)
|
||||
if err != nil {
|
||||
return net.Destination{}, errors.New(prefix, "failed to parse address and port").Base(err)
|
||||
}
|
||||
switch network {
|
||||
case TargetNetworkTCP:
|
||||
return net.TCPDestination(addr, port), nil
|
||||
case TargetNetworkUDP:
|
||||
return net.UDPDestination(addr, port), nil
|
||||
default:
|
||||
return net.Destination{}, errors.New(prefix, "unknown network type: ", network)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package multiplex_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/proxy/vless/multiplex"
|
||||
)
|
||||
|
||||
func TestFrameEndpoints(t *testing.T) {
|
||||
target := net.TCPDestination(net.DomainAddress("example.test"), 443)
|
||||
src := net.TCPDestination(net.LocalHostIP, 2053)
|
||||
local := net.UDPDestination(net.ParseAddress("::1"), 5060)
|
||||
// Wire bytes from the codec before consolidating its endpoint decoder.
|
||||
const targetBytes = "000701000101bb020c6578616d706c652e74657374"
|
||||
const sourceBytes = "010805017f000001"
|
||||
const localBytes = "0213c40300000000000000000000000000000001"
|
||||
for _, tc := range []struct {
|
||||
name, wire string
|
||||
input session.Inbound
|
||||
}{
|
||||
{"heartbeat", "0015" + targetBytes, session.Inbound{}},
|
||||
{"source-only", "001d" + targetBytes + sourceBytes, session.Inbound{Source: src}},
|
||||
{"both", "0031" + targetBytes + sourceBytes + localBytes, session.Inbound{Source: src, Local: local}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
frame := multiplex.FrameMetadata{
|
||||
Target: target, SessionID: 7, SessionStatus: multiplex.SessionStatusNew, Inbound: &tc.input,
|
||||
}
|
||||
wire := buf.New()
|
||||
defer wire.Release()
|
||||
if err := frame.WriteTo(wire); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := hex.EncodeToString(wire.Bytes()); got != tc.wire {
|
||||
t.Fatalf("metadata = %s, want %s", got, tc.wire)
|
||||
}
|
||||
reader := io.MultiReader(bytes.NewReader(wire.Bytes()), bytes.NewReader([]byte("payload")))
|
||||
var decoded multiplex.FrameMetadata
|
||||
if err := decoded.Unmarshal(reader, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if decoded.Inbound == nil || decoded.Target != target ||
|
||||
decoded.Inbound.Source != tc.input.Source || decoded.Inbound.Local != tc.input.Local {
|
||||
t.Fatalf("unexpected endpoint metadata: %+v", decoded)
|
||||
}
|
||||
if rest, err := io.ReadAll(reader); err != nil || string(rest) != "payload" {
|
||||
t.Fatalf("payload was consumed with metadata: %q, err = %v", rest, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkFrameWrite(b *testing.B) {
|
||||
frame := multiplex.FrameMetadata{
|
||||
Target: net.TCPDestination(net.DomainAddress("www.example.com"), net.Port(80)),
|
||||
SessionID: 1,
|
||||
SessionStatus: multiplex.SessionStatusNew,
|
||||
}
|
||||
writer := buf.New()
|
||||
defer writer.Release()
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
common.Must(frame.WriteTo(writer))
|
||||
writer.Clear()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/crypto"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
)
|
||||
|
||||
func readAll(reader buf.Reader) (buf.MultiBuffer, error) {
|
||||
var mb buf.MultiBuffer
|
||||
for {
|
||||
b, err := reader.ReadMultiBuffer()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mb = append(mb, b...)
|
||||
}
|
||||
return mb, nil
|
||||
}
|
||||
|
||||
func TestReaderWriter(t *testing.T) {
|
||||
pReader, pWriter := pipe.New(pipe.WithSizeLimit(1024))
|
||||
|
||||
dest := net.TCPDestination(net.DomainAddress("example.com"), 80)
|
||||
s1 := &Session{ID: 1, target: dest, inbound: &session.Inbound{}, first: true}
|
||||
|
||||
dest2 := net.TCPDestination(net.LocalHostIP, 443)
|
||||
s2 := &Session{ID: 2, target: dest2, inbound: &session.Inbound{}, first: true}
|
||||
|
||||
dest3 := net.TCPDestination(net.LocalHostIPv6, 18374)
|
||||
s3 := &Session{ID: 3, target: dest3, inbound: &session.Inbound{}, first: true}
|
||||
|
||||
writePayload := func(s *Session, payload ...byte) error {
|
||||
b := buf.New()
|
||||
b.Write(payload)
|
||||
data := buf.MultiBuffer{b}
|
||||
defer func() { buf.ReleaseMulti(data) }()
|
||||
frames, err := s.encodeBatch(&data)
|
||||
if err != nil {
|
||||
buf.ReleaseMulti(frames)
|
||||
return err
|
||||
}
|
||||
return pWriter.WriteMultiBuffer(frames)
|
||||
}
|
||||
|
||||
common.Must(writePayload(s1, 'a', 'b', 'c', 'd'))
|
||||
common.Must(writePayload(s2))
|
||||
|
||||
common.Must(writePayload(s1, 'e', 'f', 'g', 'h'))
|
||||
common.Must(writePayload(s3, 'x'))
|
||||
|
||||
common.Must(pWriter.WriteMultiBuffer(endFrame(s1.ID, false)))
|
||||
common.Must(pWriter.WriteMultiBuffer(endFrame(s3.ID, false)))
|
||||
|
||||
common.Must(writePayload(s2, 'y'))
|
||||
common.Must(pWriter.WriteMultiBuffer(endFrame(s2.ID, false)))
|
||||
|
||||
bytesReader := &buf.BufferedReader{Reader: pReader}
|
||||
|
||||
{
|
||||
var meta FrameMetadata
|
||||
common.Must(meta.Unmarshal(bytesReader, false))
|
||||
if r := cmp.Diff(meta, FrameMetadata{
|
||||
SessionID: 1,
|
||||
SessionStatus: SessionStatusNew,
|
||||
Target: dest,
|
||||
Option: OptionData,
|
||||
}); r != "" {
|
||||
t.Error("metadata: ", r)
|
||||
}
|
||||
|
||||
data, err := readAll(crypto.NewChunkStreamReaderWithChunkCount(crypto.PlainChunkSizeParser{}, bytesReader, 1))
|
||||
common.Must(err)
|
||||
if s := data.String(); s != "abcd" {
|
||||
t.Error("data: ", s)
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
var meta FrameMetadata
|
||||
common.Must(meta.Unmarshal(bytesReader, false))
|
||||
if r := cmp.Diff(meta, FrameMetadata{
|
||||
SessionStatus: SessionStatusNew,
|
||||
SessionID: 2,
|
||||
Option: 0,
|
||||
Target: dest2,
|
||||
}); r != "" {
|
||||
t.Error("meta: ", r)
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
var meta FrameMetadata
|
||||
common.Must(meta.Unmarshal(bytesReader, false))
|
||||
if r := cmp.Diff(meta, FrameMetadata{
|
||||
SessionID: 1,
|
||||
SessionStatus: SessionStatusKeep,
|
||||
Option: 1,
|
||||
}); r != "" {
|
||||
t.Error("meta: ", r)
|
||||
}
|
||||
|
||||
data, err := readAll(crypto.NewChunkStreamReaderWithChunkCount(crypto.PlainChunkSizeParser{}, bytesReader, 1))
|
||||
common.Must(err)
|
||||
if s := data.String(); s != "efgh" {
|
||||
t.Error("data: ", s)
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
var meta FrameMetadata
|
||||
common.Must(meta.Unmarshal(bytesReader, false))
|
||||
if r := cmp.Diff(meta, FrameMetadata{
|
||||
SessionID: 3,
|
||||
SessionStatus: SessionStatusNew,
|
||||
Option: 1,
|
||||
Target: dest3,
|
||||
}); r != "" {
|
||||
t.Error("meta: ", r)
|
||||
}
|
||||
|
||||
data, err := readAll(crypto.NewChunkStreamReaderWithChunkCount(crypto.PlainChunkSizeParser{}, bytesReader, 1))
|
||||
common.Must(err)
|
||||
if s := data.String(); s != "x" {
|
||||
t.Error("data: ", s)
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
var meta FrameMetadata
|
||||
common.Must(meta.Unmarshal(bytesReader, false))
|
||||
if r := cmp.Diff(meta, FrameMetadata{
|
||||
SessionID: 1,
|
||||
SessionStatus: SessionStatusEnd,
|
||||
Option: 0,
|
||||
}); r != "" {
|
||||
t.Error("meta: ", r)
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
var meta FrameMetadata
|
||||
common.Must(meta.Unmarshal(bytesReader, false))
|
||||
if r := cmp.Diff(meta, FrameMetadata{
|
||||
SessionID: 3,
|
||||
SessionStatus: SessionStatusEnd,
|
||||
Option: 0,
|
||||
}); r != "" {
|
||||
t.Error("meta: ", r)
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
var meta FrameMetadata
|
||||
common.Must(meta.Unmarshal(bytesReader, false))
|
||||
if r := cmp.Diff(meta, FrameMetadata{
|
||||
SessionID: 2,
|
||||
SessionStatus: SessionStatusKeep,
|
||||
Option: 1,
|
||||
}); r != "" {
|
||||
t.Error("meta: ", r)
|
||||
}
|
||||
|
||||
data, err := readAll(crypto.NewChunkStreamReaderWithChunkCount(crypto.PlainChunkSizeParser{}, bytesReader, 1))
|
||||
common.Must(err)
|
||||
if s := data.String(); s != "y" {
|
||||
t.Error("data: ", s)
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
var meta FrameMetadata
|
||||
common.Must(meta.Unmarshal(bytesReader, false))
|
||||
if r := cmp.Diff(meta, FrameMetadata{
|
||||
SessionID: 2,
|
||||
SessionStatus: SessionStatusEnd,
|
||||
Option: 0,
|
||||
}); r != "" {
|
||||
t.Error("meta: ", r)
|
||||
}
|
||||
}
|
||||
|
||||
pWriter.Close()
|
||||
|
||||
{
|
||||
var meta FrameMetadata
|
||||
err := meta.Unmarshal(bytesReader, false)
|
||||
if err == nil {
|
||||
t.Error("nil error")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"io"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
)
|
||||
|
||||
// frameReadError distinguishes truncation inside a frame from EOF between frames.
|
||||
func frameReadError(err error) error {
|
||||
if errors.Cause(err) == io.EOF {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// readBlock reads one length-prefixed frame component without retaining a partial buffer.
|
||||
func readBlock(reader io.Reader, limit uint16, oversized string) (*buf.Buffer, error) {
|
||||
size, err := serial.ReadUint16(reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if size > limit {
|
||||
return nil, errors.New(oversized, size)
|
||||
}
|
||||
b := buf.New()
|
||||
if _, err := b.ReadFullFrom(reader, int32(size)); err != nil {
|
||||
b.Release()
|
||||
return nil, frameReadError(err)
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// readPacket reads one complete packet; its destination belongs to the buffer.
|
||||
func readPacket(reader io.Reader, dest net.Destination) (buf.MultiBuffer, error) {
|
||||
b, err := readBlock(reader, buf.Size, "packet size too large: ")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if dest.Network == net.Network_UDP {
|
||||
b.UDP = &dest
|
||||
}
|
||||
return buf.MultiBuffer{b}, nil
|
||||
}
|
||||
|
||||
// copyFramePayload publishes stream data as it arrives and keeps packets whole.
|
||||
// A closed child discards the remainder without crossing the frame boundary.
|
||||
func copyFramePayload(reader *buf.BufferedReader, s *Session, dest net.Destination) (err error) {
|
||||
packet := s != nil && s.target.Network == net.Network_UDP
|
||||
var left int32
|
||||
if !packet {
|
||||
size, sizeErr := serial.ReadUint16(reader)
|
||||
if sizeErr != nil {
|
||||
return sizeErr
|
||||
}
|
||||
left = int32(size)
|
||||
}
|
||||
for packet || left > 0 {
|
||||
var mb buf.MultiBuffer
|
||||
if packet {
|
||||
mb, err = readPacket(reader, dest)
|
||||
} else {
|
||||
mb, err = reader.ReadAtMost(left)
|
||||
left -= mb.Len()
|
||||
// Coalesce cached pieces without reading more from the transport.
|
||||
for s != nil && left > 0 && reader.BufferedBytes() > 0 {
|
||||
var part buf.MultiBuffer
|
||||
part, err = reader.ReadAtMost(left)
|
||||
left -= part.Len()
|
||||
mb = append(mb, part...)
|
||||
}
|
||||
}
|
||||
if s == nil || mb.IsEmpty() {
|
||||
buf.ReleaseMulti(mb)
|
||||
} else if werr := s.writePayload(mb); werr != nil {
|
||||
s.Interrupt()
|
||||
s = nil
|
||||
}
|
||||
if packet || err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/log"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
)
|
||||
|
||||
type ServerWorker struct {
|
||||
*carrier
|
||||
dispatch func(context.Context, net.Destination, *transport.Link) error
|
||||
}
|
||||
|
||||
func NewServerWorker(ctx context.Context, dispatch func(context.Context, net.Destination, *transport.Link) error, link *transport.Link) *ServerWorker {
|
||||
w := &ServerWorker{carrier: newCarrier(ctx, *link, 60*time.Second, false), dispatch: dispatch}
|
||||
go w.run(ctx, w.handleStatusNew)
|
||||
return w
|
||||
}
|
||||
|
||||
// A non-nil dispatch return rejects admission; accepted backend failures use the link.
|
||||
func (w *ServerWorker) dispatchFlow(ctx context.Context, dest net.Destination, flow *inboundFlow, output buf.Writer) {
|
||||
if err := w.dispatch(ctx, dest, &transport.Link{Reader: flow, Writer: output}); err != nil {
|
||||
if flow.GlobalID != [8]byte{} {
|
||||
XUDPManager.Lock()
|
||||
if XUDPManager.Map[flow.GlobalID] == flow {
|
||||
delete(XUDPManager.Map, flow.GlobalID)
|
||||
}
|
||||
XUDPManager.Unlock()
|
||||
}
|
||||
w.cancel(err)
|
||||
flow.Interrupt()
|
||||
flow.finish(true)
|
||||
errors.LogInfoInner(ctx, err, "failed to dispatch request to ", dest)
|
||||
}
|
||||
}
|
||||
|
||||
func (w *ServerWorker) handleStatusNew(ctx context.Context, meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
w.RLock()
|
||||
previous := w.sessions[meta.SessionID]
|
||||
w.RUnlock()
|
||||
if previous != nil {
|
||||
previous.abort()
|
||||
}
|
||||
ctx = session.SubContextFromMuxInbound(ctx)
|
||||
if meta.Inbound != nil && meta.Inbound.Source.IsValid() && meta.Inbound.Local.IsValid() {
|
||||
if inbound := session.InboundFromContext(ctx); inbound != nil {
|
||||
newInbound := *inbound
|
||||
newInbound.Source = meta.Inbound.Source
|
||||
newInbound.Local = meta.Inbound.Local
|
||||
ctx = session.ContextWithInbound(ctx, &newInbound)
|
||||
}
|
||||
}
|
||||
errors.LogInfo(ctx, "received request for ", meta.Target)
|
||||
msg := &log.AccessMessage{
|
||||
To: meta.Target,
|
||||
Status: log.AccessAccepted,
|
||||
}
|
||||
if inbound := session.InboundFromContext(ctx); inbound != nil && inbound.Source.IsValid() {
|
||||
msg.From = inbound.Source
|
||||
msg.Email = inbound.User.Email
|
||||
}
|
||||
ctx = log.ContextWithAccessMessage(ctx, msg)
|
||||
|
||||
if network := session.AllowedNetworkFromContext(ctx); network != net.Network_Unknown && meta.Target.Network != network {
|
||||
return errors.New("unexpected network ", meta.Target.Network)
|
||||
}
|
||||
|
||||
if meta.GlobalID != [8]byte{} {
|
||||
return w.bindXUDP(ctx, meta, reader)
|
||||
}
|
||||
|
||||
s := &Session{
|
||||
parent: w.carrier, phase: outputOpen,
|
||||
ID: meta.SessionID, target: net.Destination{Network: meta.Target.Network},
|
||||
}
|
||||
s.flow = newInboundFlow(ctx, [8]byte{})
|
||||
s.flow.binding = s
|
||||
w.Lock()
|
||||
admitted := w.admitLocked(s)
|
||||
w.Unlock()
|
||||
if !admitted {
|
||||
s.flow.Interrupt()
|
||||
return errors.New("failed to add new session")
|
||||
}
|
||||
var output buf.Writer = s
|
||||
if meta.Target.Network == net.Network_UDP {
|
||||
output = &flowOutput{s.flow}
|
||||
}
|
||||
go w.dispatchFlow(ctx, meta.Target, s.flow, output)
|
||||
if !meta.Option.Has(OptionData) {
|
||||
return nil
|
||||
}
|
||||
|
||||
return copyFramePayload(reader, s, meta.Target)
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package multiplex_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/common/task"
|
||||
"github.com/xtls/xray-core/proxy/vless/multiplex"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
)
|
||||
|
||||
func newLinkPair() (*transport.Link, *transport.Link) {
|
||||
opt := pipe.WithoutSizeLimit()
|
||||
uplinkReader, uplinkWriter := pipe.New(opt)
|
||||
downlinkReader, downlinkWriter := pipe.New(opt)
|
||||
|
||||
uplink := &transport.Link{
|
||||
Reader: uplinkReader,
|
||||
Writer: downlinkWriter,
|
||||
}
|
||||
|
||||
downlink := &transport.Link{
|
||||
Reader: downlinkReader,
|
||||
Writer: uplinkWriter,
|
||||
}
|
||||
|
||||
return uplink, downlink
|
||||
}
|
||||
|
||||
func TestRegressionOutboundLeak(t *testing.T) {
|
||||
originalOutbounds := []*session.Outbound{{}}
|
||||
serverCtx := session.ContextWithOutbounds(context.Background(), originalOutbounds)
|
||||
|
||||
websiteUplink, websiteDownlink := newLinkPair()
|
||||
|
||||
dispatch := func(ctx context.Context, dest net.Destination, link *transport.Link) error {
|
||||
// Emulate DefaultDispatcher's context mutation while forwarding real data.
|
||||
ob := session.OutboundsFromContext(ctx)[0]
|
||||
ob.Target = dest
|
||||
return task.Run(ctx,
|
||||
func() error { return buf.Copy(link.Reader, websiteDownlink.Writer) },
|
||||
func() error { return buf.Copy(websiteDownlink.Reader, link.Writer) })
|
||||
}
|
||||
|
||||
multiplexServerUplink, multiplexServerDownlink := newLinkPair()
|
||||
multiplex.NewServerWorker(serverCtx, dispatch, multiplexServerUplink)
|
||||
|
||||
client := multiplex.NewClientWorker(context.Background(), *multiplexServerDownlink, multiplex.ClientStrategy{})
|
||||
|
||||
clientCtx := session.ContextWithOutbounds(context.Background(), []*session.Outbound{{
|
||||
Target: net.TCPDestination(net.DomainAddress("www.example.com"), 80),
|
||||
}})
|
||||
|
||||
multiplexClientUplink, multiplexClientDownlink := newLinkPair()
|
||||
|
||||
dispatched := make(chan error, 1)
|
||||
go func() {
|
||||
dispatched <- multiplex.Dispatch(clientCtx, multiplexClientUplink, func(ctx context.Context, s *multiplex.Session) error {
|
||||
if !client.TryAdmit(ctx, s) {
|
||||
return fmt.Errorf("unable to admit test child")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}()
|
||||
defer func() {
|
||||
client.Close()
|
||||
if err := <-dispatched; err != nil {
|
||||
t.Error("failed to dispatch: ", err)
|
||||
}
|
||||
}()
|
||||
|
||||
{
|
||||
b := buf.FromBytes([]byte("hello"))
|
||||
common.Must(multiplexClientDownlink.Writer.WriteMultiBuffer(buf.MultiBuffer{b}))
|
||||
}
|
||||
|
||||
resMb, err := websiteUplink.Reader.ReadMultiBuffer()
|
||||
common.Must(err)
|
||||
res := resMb.String()
|
||||
if res != "hello" {
|
||||
t.Error("upload: ", res)
|
||||
}
|
||||
|
||||
{
|
||||
b := buf.FromBytes([]byte("world"))
|
||||
common.Must(websiteUplink.Writer.WriteMultiBuffer(buf.MultiBuffer{b}))
|
||||
}
|
||||
|
||||
resMb, err = multiplexClientDownlink.Reader.ReadMultiBuffer()
|
||||
common.Must(err)
|
||||
res = resMb.String()
|
||||
if res != "world" {
|
||||
t.Error("download: ", res)
|
||||
}
|
||||
|
||||
outbounds := session.OutboundsFromContext(serverCtx)
|
||||
if outbounds[0] != originalOutbounds[0] {
|
||||
t.Error("outbound got reassigned: ", outbounds[0])
|
||||
}
|
||||
|
||||
if outbounds[0].Target.Address != nil {
|
||||
t.Error("outbound target got leaked: ", outbounds[0].Target.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/common/xudp"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
)
|
||||
|
||||
// Session has one physical owner. Parent guards phase and registry identity;
|
||||
// Flow is immutable after publication; its retained route can outlive this ID.
|
||||
type Session struct {
|
||||
input buf.Reader
|
||||
output buf.Writer
|
||||
parent *carrier
|
||||
ID uint16
|
||||
target net.Destination
|
||||
globalID [8]byte
|
||||
inbound *session.Inbound
|
||||
first bool
|
||||
endFailed bool // immutable after the first local terminal transition
|
||||
phase byte
|
||||
done chan struct{}
|
||||
flow *inboundFlow
|
||||
producer sync.Mutex
|
||||
|
||||
writingResponse atomic.Bool
|
||||
}
|
||||
|
||||
const (
|
||||
outputStarting = iota
|
||||
outputOpen
|
||||
outputDone
|
||||
)
|
||||
|
||||
// NewSession prepares initiating metadata before any physical admission lock.
|
||||
func NewSession(ctx context.Context, link *transport.Link) *Session {
|
||||
outbounds := session.OutboundsFromContext(ctx)
|
||||
target := outbounds[len(outbounds)-1].Target
|
||||
s := &Session{
|
||||
input: link.Reader, output: link.Writer, target: target,
|
||||
globalID: xudp.GetGlobalID(ctx), first: true,
|
||||
}
|
||||
if session.IsReverseMuxFromContext(ctx) {
|
||||
s.inbound = session.InboundFromContext(ctx)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Initiating input is serial; native server callbacks are serialized per offer.
|
||||
// Existing producers own DATA through direct physical admission.
|
||||
func (s *Session) WriteMultiBuffer(raw buf.MultiBuffer) error {
|
||||
c := s.parent
|
||||
c.RLock()
|
||||
live := !c.Closed() && s.phase == outputOpen && c.sessions[s.ID] == s
|
||||
c.RUnlock()
|
||||
if !live {
|
||||
buf.ReleaseMulti(raw)
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
if !c.client {
|
||||
s.producer.Lock()
|
||||
defer s.producer.Unlock()
|
||||
}
|
||||
defer func() { buf.ReleaseMulti(raw) }()
|
||||
for {
|
||||
c.writeMutex.Lock()
|
||||
c.RLock()
|
||||
live := !c.Closed() && s.phase == outputOpen && c.sessions[s.ID] == s
|
||||
c.RUnlock()
|
||||
var frames buf.MultiBuffer
|
||||
var err error
|
||||
if live {
|
||||
frames, err = s.encodeBatch(&raw)
|
||||
}
|
||||
if err = c.writeAndUnlock(frames, err); err != nil {
|
||||
return err
|
||||
}
|
||||
if !live || c.Closed() {
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
if len(raw) == 0 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Session) writePayload(data buf.MultiBuffer) error {
|
||||
// The flow validates server admission for this immutable binding.
|
||||
x := s.flow
|
||||
if x == nil {
|
||||
s.parent.RLock()
|
||||
live := s.phase == outputOpen || s.phase == outputStarting
|
||||
if live {
|
||||
s.writingResponse.Store(true)
|
||||
}
|
||||
s.parent.RUnlock()
|
||||
if !live {
|
||||
buf.ReleaseMulti(data)
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
defer s.writingResponse.Store(false)
|
||||
return s.output.WriteMultiBuffer(data)
|
||||
}
|
||||
err := x.accept(data, s)
|
||||
if err != nil {
|
||||
buf.ReleaseMulti(data)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Session) Close() error {
|
||||
if s.parent.client {
|
||||
s.close(true)
|
||||
return nil
|
||||
}
|
||||
s.producer.Lock()
|
||||
defer s.producer.Unlock()
|
||||
s.close(false)
|
||||
return nil
|
||||
}
|
||||
func (s *Session) Interrupt() { s.close(true) }
|
||||
func (s *Session) WaitClosed() <-chan struct{} { return s.done }
|
||||
|
||||
func (s *Session) CloseWithError(err error) { s.close(err != nil) }
|
||||
|
||||
func (s *Session) close(failed bool) { s.seal(failed, true) }
|
||||
func (s *Session) abort() { s.seal(false, false) }
|
||||
|
||||
func (s *Session) seal(failed, local bool) {
|
||||
c, x := s.parent, s.flow
|
||||
if x != nil {
|
||||
x.access.Lock()
|
||||
defer x.access.Unlock()
|
||||
}
|
||||
c.Lock()
|
||||
s.closeLocked(x, failed, local)
|
||||
c.Unlock()
|
||||
}
|
||||
|
||||
// closeLocked seals the logical route under flow/carrier ownership. The role's
|
||||
// producer or carrier sender owns END; the first local failure flag is immutable.
|
||||
func (s *Session) closeLocked(x *inboundFlow, failed, local bool) {
|
||||
c := s.parent
|
||||
first := s.phase != outputDone
|
||||
// A borrowed peer pointer must not rewrite a client's first terminal state.
|
||||
if !first && (local || c.client) {
|
||||
return
|
||||
}
|
||||
registered := c.sessions[s.ID] == s
|
||||
if s.phase == outputOpen && registered {
|
||||
c.active--
|
||||
}
|
||||
s.phase = outputDone
|
||||
// A terminal row retained in the registry owns a pending END.
|
||||
if registered && local && !c.Closed() {
|
||||
s.endFailed = failed
|
||||
c.queueReadyLocked(s)
|
||||
} else if registered {
|
||||
delete(c.ready, s.ID)
|
||||
delete(c.sessions, s.ID)
|
||||
}
|
||||
if first {
|
||||
if s.done != nil {
|
||||
close(s.done)
|
||||
}
|
||||
if x != nil && x.binding == s {
|
||||
x.binding = nil
|
||||
if x.GlobalID == [8]byte{} {
|
||||
if x.requestErr == nil {
|
||||
x.requestErr = io.EOF
|
||||
}
|
||||
x.responseErr = io.ErrClosedPipe
|
||||
x.response = buf.ReleaseMulti(x.response)
|
||||
x.responseWake.Broadcast()
|
||||
} else {
|
||||
x.Expire = time.Now().Add(time.Minute)
|
||||
}
|
||||
x.requestWake.Broadcast()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var XUDPManager = struct {
|
||||
sync.Mutex
|
||||
Map map[[8]byte]*inboundFlow
|
||||
}{Map: make(map[[8]byte]*inboundFlow)}
|
||||
|
||||
func init() { time.AfterFunc(time.Minute, scheduleXUDPSweep) }
|
||||
|
||||
func scheduleXUDPSweep() {
|
||||
sweepXUDP(time.Now())
|
||||
time.AfterFunc(time.Minute, scheduleXUDPSweep)
|
||||
}
|
||||
|
||||
func sweepXUDP(now time.Time) {
|
||||
var expired []*inboundFlow
|
||||
XUDPManager.Lock()
|
||||
for id, x := range XUDPManager.Map {
|
||||
x.access.Lock()
|
||||
if x.binding == nil && !x.Expire.IsZero() && now.After(x.Expire) {
|
||||
expired = append(expired, x)
|
||||
delete(XUDPManager.Map, id)
|
||||
}
|
||||
x.access.Unlock()
|
||||
}
|
||||
XUDPManager.Unlock()
|
||||
for _, x := range expired {
|
||||
errors.LogDebug(context.Background(), "XUDP del ", x.GlobalID)
|
||||
x.expire()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/transport"
|
||||
"github.com/xtls/xray-core/transport/pipe"
|
||||
)
|
||||
|
||||
func TestCarrierAdmission(t *testing.T) {
|
||||
reader, writer := pipe.New(pipe.WithoutSizeLimit())
|
||||
worker := NewClientWorker(context.Background(), transport.Link{Reader: reader, Writer: buf.Discard}, ClientStrategy{})
|
||||
t.Cleanup(func() { worker.Close(); writer.Close() })
|
||||
for id := uint16(1); id <= 2; id++ {
|
||||
ctx := testOutboundContext()
|
||||
s := NewSession(ctx, &transport.Link{Writer: buf.Discard})
|
||||
if !worker.TryAdmit(ctx, s) || s.ID != id {
|
||||
t.Fatalf("id%d: %v", id, s)
|
||||
}
|
||||
if worker.ActiveConnections() != uint32(id) {
|
||||
t.Fatalf("active: %d", worker.ActiveConnections())
|
||||
}
|
||||
}
|
||||
// Preserve the original explicit-ID publication assertion, with a fully
|
||||
// initialized real physical owner instead of a standalone manager facade.
|
||||
s := &Session{ID: 4, parent: worker.carrier, output: buf.Discard, done: make(chan struct{}), phase: outputOpen}
|
||||
worker.Lock()
|
||||
admitted := worker.admitLocked(s)
|
||||
indexed := worker.sessions[4] == s
|
||||
worker.Unlock()
|
||||
if !admitted || !indexed || s.ID != 4 || worker.ActiveConnections() != 3 {
|
||||
t.Fatal("explicit wire identity not admitted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCarrierIdleRetirement(t *testing.T) {
|
||||
reader, writer := pipe.New(pipe.WithoutSizeLimit())
|
||||
worker := &ClientWorker{carrier: newCarrier(context.Background(), transport.Link{Reader: reader, Writer: buf.Discard}, 20*time.Millisecond, true)}
|
||||
go worker.run(context.Background(), nil)
|
||||
t.Cleanup(func() { worker.Close(); writer.Close() })
|
||||
ctx := testOutboundContext()
|
||||
s := NewSession(ctx, &transport.Link{Writer: buf.Discard})
|
||||
if !worker.TryAdmit(ctx, s) {
|
||||
t.Fatal("session not admitted")
|
||||
}
|
||||
select {
|
||||
case <-worker.WaitClosed():
|
||||
t.Fatal("active carrier retired")
|
||||
case <-time.After(65 * time.Millisecond):
|
||||
}
|
||||
s.Close()
|
||||
select {
|
||||
case <-worker.WaitClosed():
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("empty carrier did not retire")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"github.com/xtls/xray-core/common"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/serial"
|
||||
)
|
||||
|
||||
// encodeBatch moves up to four complete wire frames from raw caller custody.
|
||||
// An offer without buffers contains metadata only.
|
||||
func (s *Session) encodeBatch(mb *buf.MultiBuffer) (frames buf.MultiBuffer, err error) {
|
||||
stream := s.target.Network != net.Network_UDP
|
||||
if stream && (*mb).IsEmpty() {
|
||||
*mb = buf.ReleaseMulti(*mb)
|
||||
}
|
||||
for n := 0; n < 4 && (s.first || len(*mb) != 0); n++ {
|
||||
frame := buf.NewWithSize(1024)
|
||||
frames = append(frames, frame)
|
||||
meta := FrameMetadata{
|
||||
SessionID: s.ID, Target: s.target, GlobalID: s.globalID,
|
||||
Inbound: s.inbound, SessionStatus: SessionStatusKeep,
|
||||
}
|
||||
if s.first {
|
||||
s.first = false
|
||||
meta.SessionStatus = SessionStatusNew
|
||||
}
|
||||
if len(*mb) == 0 {
|
||||
return frames, meta.WriteTo(frame)
|
||||
}
|
||||
var chunk buf.MultiBuffer
|
||||
if stream {
|
||||
*mb, chunk = buf.SplitSize(*mb, 8*1024)
|
||||
} else {
|
||||
mb2, b := buf.SplitFirst(*mb)
|
||||
*mb = mb2
|
||||
chunk = buf.MultiBuffer{b}
|
||||
}
|
||||
if len(chunk) == 1 {
|
||||
frame.UDP = chunk[0].UDP
|
||||
}
|
||||
frames = append(frames, chunk...)
|
||||
meta.Option.Set(OptionData)
|
||||
if err := meta.WriteTo(frame); err != nil {
|
||||
return frames, err
|
||||
}
|
||||
if _, err := serial.WriteUint16(frame, uint16(chunk.Len())); err != nil {
|
||||
return frames, err
|
||||
}
|
||||
}
|
||||
return frames, nil
|
||||
}
|
||||
|
||||
func endFrame(id uint16, failed bool) buf.MultiBuffer {
|
||||
meta := FrameMetadata{SessionID: id, SessionStatus: SessionStatusEnd}
|
||||
if failed {
|
||||
meta.Option.Set(OptionError)
|
||||
}
|
||||
frame := buf.NewWithSize(1024)
|
||||
common.Must(meta.WriteTo(frame))
|
||||
return buf.MultiBuffer{frame}
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
package multiplex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
"github.com/xtls/xray-core/common/errors"
|
||||
"github.com/xtls/xray-core/common/net"
|
||||
"github.com/xtls/xray-core/common/session"
|
||||
"github.com/xtls/xray-core/features/policy"
|
||||
"github.com/xtls/xray-core/features/stats"
|
||||
)
|
||||
|
||||
// inboundFlow owns native route input and persistent binding state. Its response
|
||||
// packet response mailbox retains native bytes until the physical sender claims them.
|
||||
// Locks nest association map -> flow -> one carrier; I/O is outside them.
|
||||
type inboundFlow struct {
|
||||
access sync.Mutex
|
||||
|
||||
requestWake, responseWake sync.Cond
|
||||
request, response buf.MultiBuffer
|
||||
requestErr, responseErr error
|
||||
uplinkCounter stats.Counter
|
||||
uplinkPending int64
|
||||
uplinkBound bool
|
||||
limit int32
|
||||
binding *Session
|
||||
GlobalID [8]byte
|
||||
Expire time.Time
|
||||
}
|
||||
|
||||
func newInboundFlow(ctx context.Context, id [8]byte) *inboundFlow {
|
||||
x := &inboundFlow{limit: policy.BufferPolicyFromContext(ctx).PerConnection, GlobalID: id}
|
||||
x.requestWake.L, x.responseWake.L = &x.access, &x.access
|
||||
return x
|
||||
}
|
||||
|
||||
// SetUplinkCounter binds attempted-input accounting once, including disabled stats.
|
||||
func (x *inboundFlow) SetUplinkCounter(counter stats.Counter) {
|
||||
x.access.Lock()
|
||||
if x.uplinkBound {
|
||||
x.access.Unlock()
|
||||
return
|
||||
}
|
||||
x.uplinkCounter, x.uplinkBound = counter, true
|
||||
pending := x.uplinkPending
|
||||
x.uplinkPending = 0
|
||||
x.access.Unlock()
|
||||
if counter != nil && pending != 0 {
|
||||
counter.Add(pending)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *inboundFlow) ReadMultiBuffer() (buf.MultiBuffer, error) {
|
||||
x.access.Lock()
|
||||
defer x.access.Unlock()
|
||||
return x.readLocked(nil)
|
||||
}
|
||||
|
||||
func (x *inboundFlow) ReadMultiBufferTimeout(duration time.Duration) (buf.MultiBuffer, error) {
|
||||
x.access.Lock()
|
||||
defer x.access.Unlock()
|
||||
if len(x.request) > 0 || x.requestErr != nil {
|
||||
return x.readLocked(nil)
|
||||
}
|
||||
timedOut := false
|
||||
timer := time.AfterFunc(duration, func() {
|
||||
x.access.Lock()
|
||||
timedOut = true
|
||||
x.requestWake.Broadcast()
|
||||
x.access.Unlock()
|
||||
})
|
||||
defer timer.Stop()
|
||||
return x.readLocked(&timedOut)
|
||||
}
|
||||
|
||||
// readLocked has no timeout closure or escaping flag on ordinary native reads.
|
||||
func (x *inboundFlow) readLocked(timedOut *bool) (buf.MultiBuffer, error) {
|
||||
for len(x.request) == 0 && x.requestErr == nil && (timedOut == nil || !*timedOut) {
|
||||
x.requestWake.Wait()
|
||||
}
|
||||
if len(x.request) > 0 {
|
||||
data := x.request
|
||||
x.request = nil
|
||||
x.requestWake.Broadcast()
|
||||
return data, nil
|
||||
}
|
||||
if x.requestErr != nil {
|
||||
return nil, x.requestErr
|
||||
}
|
||||
return nil, buf.ErrReadTimeout
|
||||
}
|
||||
|
||||
// accept leaves rejected data with the parser so a failed retained route can
|
||||
// restart with the very same first packet and destination.
|
||||
func (x *inboundFlow) accept(data buf.MultiBuffer, binding *Session) error {
|
||||
x.access.Lock()
|
||||
if !x.uplinkBound {
|
||||
x.uplinkPending += int64(data.Len())
|
||||
} else if counter := x.uplinkCounter; counter != nil {
|
||||
x.access.Unlock()
|
||||
counter.Add(int64(data.Len()))
|
||||
x.access.Lock()
|
||||
}
|
||||
defer x.access.Unlock()
|
||||
for {
|
||||
if x.requestErr != nil || x.binding != binding || binding.parent.Closed() {
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
if x.limit < 0 || x.request.Len() <= x.limit {
|
||||
if len(x.request) == 0 {
|
||||
x.request = data
|
||||
} else {
|
||||
x.request, _ = buf.MergeMulti(x.request, data)
|
||||
}
|
||||
x.requestWake.Broadcast()
|
||||
return nil
|
||||
}
|
||||
x.requestWake.Wait()
|
||||
}
|
||||
}
|
||||
|
||||
// Interrupt is native request abort. Ordinary wire EOF instead seals this
|
||||
// input in Session.close, preserving payload already accepted from the parser.
|
||||
func (x *inboundFlow) Interrupt() {
|
||||
x.access.Lock()
|
||||
x.requestErr = io.ErrClosedPipe
|
||||
x.request = buf.ReleaseMulti(x.request)
|
||||
x.requestWake.Broadcast()
|
||||
x.access.Unlock()
|
||||
}
|
||||
|
||||
type flowOutput struct{ *inboundFlow }
|
||||
|
||||
func (w *flowOutput) Interrupt() { w.finish(true) }
|
||||
func (w *flowOutput) Close() error { w.finish(false); return nil }
|
||||
func (x *inboundFlow) finish(abort bool) {
|
||||
x.access.Lock()
|
||||
if abort {
|
||||
x.responseErr = io.ErrClosedPipe
|
||||
x.response = buf.ReleaseMulti(x.response)
|
||||
} else if x.responseErr == nil {
|
||||
x.responseErr = io.EOF
|
||||
}
|
||||
if s := x.binding; s != nil {
|
||||
c := s.parent
|
||||
c.Lock()
|
||||
if abort && s.phase == outputOpen {
|
||||
s.closeLocked(x, true, true)
|
||||
} else {
|
||||
c.scheduleLocked(s)
|
||||
}
|
||||
c.Unlock()
|
||||
}
|
||||
x.responseWake.Broadcast()
|
||||
x.access.Unlock()
|
||||
}
|
||||
|
||||
func (x *inboundFlow) expire() {
|
||||
x.access.Lock()
|
||||
if x.requestErr == nil {
|
||||
x.requestErr = io.EOF
|
||||
x.requestWake.Broadcast()
|
||||
}
|
||||
x.access.Unlock()
|
||||
x.finish(true)
|
||||
}
|
||||
|
||||
// WriteMultiBuffer admits the whole raw offer under the original soft policy.
|
||||
// Response-capacity waiters are separate from request readers.
|
||||
func (w *flowOutput) WriteMultiBuffer(data buf.MultiBuffer) error {
|
||||
x := w.inboundFlow
|
||||
x.access.Lock()
|
||||
defer x.access.Unlock()
|
||||
for x.responseErr == nil && x.limit >= 0 && x.response.Len() > x.limit {
|
||||
x.responseWake.Wait()
|
||||
}
|
||||
if x.responseErr != nil {
|
||||
buf.ReleaseMulti(data)
|
||||
return io.ErrClosedPipe
|
||||
}
|
||||
if data.IsEmpty() {
|
||||
buf.ReleaseMulti(data)
|
||||
return nil
|
||||
}
|
||||
if len(x.response) == 0 {
|
||||
x.response = data
|
||||
} else {
|
||||
x.response, _ = buf.MergeMulti(x.response, data)
|
||||
}
|
||||
if s := x.binding; s != nil {
|
||||
s.parent.Lock()
|
||||
s.parent.scheduleLocked(s)
|
||||
s.parent.Unlock()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// packetReady is checked with the flow and carrier locked.
|
||||
func (s *Session) packetReady() bool {
|
||||
x := s.flow
|
||||
return x != nil && x.binding == s &&
|
||||
(s.phase == outputOpen && (len(x.response) != 0 || x.responseErr != nil) ||
|
||||
s.phase == outputStarting && x.requestErr == nil && len(x.response) != 0)
|
||||
}
|
||||
|
||||
// One gated actor claims packet data or retires one exact terminal identity.
|
||||
// It returns custody only; the sender encodes after both logical locks release.
|
||||
func (c *carrier) responseTurn(id uint16, s *Session) (buf.MultiBuffer, bool) {
|
||||
if s != nil && s.flow != nil {
|
||||
s.flow.access.Lock()
|
||||
defer s.flow.access.Unlock()
|
||||
}
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
if c.Closed() {
|
||||
return nil, false
|
||||
}
|
||||
if s == nil {
|
||||
return nil, c.invalidateUnknownLocked(id)
|
||||
}
|
||||
if c.sessions[id] != s {
|
||||
return nil, false
|
||||
}
|
||||
x := s.flow
|
||||
ready := s.packetReady()
|
||||
if ready && len(x.response) == 0 {
|
||||
s.closeLocked(x, x.responseErr == io.ErrClosedPipe, true)
|
||||
}
|
||||
if s.phase == outputDone {
|
||||
delete(c.ready, s.ID)
|
||||
delete(c.sessions, s.ID)
|
||||
return nil, true
|
||||
}
|
||||
if !ready {
|
||||
delete(c.ready, s.ID)
|
||||
return nil, false
|
||||
}
|
||||
n := min(4, len(x.response))
|
||||
data := x.response[:n:n]
|
||||
x.response = x.response[n:]
|
||||
if len(x.response) == 0 {
|
||||
x.response = nil
|
||||
}
|
||||
x.responseWake.Broadcast()
|
||||
// A terminal follow-up cannot run until this DATA turn completes physically.
|
||||
if !s.packetReady() {
|
||||
delete(c.ready, s.ID)
|
||||
}
|
||||
return data, false
|
||||
}
|
||||
|
||||
func (w *ServerWorker) bindXUDP(ctx context.Context, meta *FrameMetadata, reader *buf.BufferedReader) error {
|
||||
data, err := readPacket(reader, meta.Target)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx = session.ContextWithTimeoutOnly(ctx, true)
|
||||
XUDPManager.Lock()
|
||||
for {
|
||||
x := XUDPManager.Map[meta.GlobalID]
|
||||
fresh := x == nil
|
||||
if fresh {
|
||||
x = newInboundFlow(ctx, meta.GlobalID)
|
||||
}
|
||||
x.access.Lock()
|
||||
if previous := x.binding; previous != nil {
|
||||
previous.parent.Lock()
|
||||
if previous.phase == outputStarting {
|
||||
previous.parent.Unlock()
|
||||
x.access.Unlock()
|
||||
XUDPManager.Unlock()
|
||||
buf.ReleaseMulti(data)
|
||||
errors.LogWarningInner(ctx, errors.New("conflict"), "XUDP hit ", meta.GlobalID)
|
||||
return nil
|
||||
}
|
||||
previous.closeLocked(x, true, true)
|
||||
previous.parent.Unlock()
|
||||
}
|
||||
w.Lock()
|
||||
if w.Closed() || w.sessions[meta.SessionID] != nil {
|
||||
w.Unlock()
|
||||
x.access.Unlock()
|
||||
XUDPManager.Unlock()
|
||||
buf.ReleaseMulti(data)
|
||||
return errors.New("failed to add new session")
|
||||
}
|
||||
s := &Session{
|
||||
parent: w.carrier, ID: meta.SessionID, phase: outputStarting,
|
||||
target: net.Destination{Network: net.Network_UDP}, flow: x,
|
||||
}
|
||||
w.invalidateUnknownLocked(s.ID)
|
||||
w.sessions[s.ID] = s
|
||||
XUDPManager.Map[meta.GlobalID] = x
|
||||
x.binding, x.Expire = s, time.Time{}
|
||||
w.scheduleLocked(s)
|
||||
w.Unlock()
|
||||
x.access.Unlock()
|
||||
XUDPManager.Unlock()
|
||||
if fresh {
|
||||
go w.dispatchFlow(ctx, meta.Target, x, &flowOutput{x})
|
||||
}
|
||||
err = x.accept(data, s)
|
||||
|
||||
XUDPManager.Lock()
|
||||
x.access.Lock()
|
||||
w.Lock()
|
||||
live := !w.Closed() && w.sessions[s.ID] == s && x.binding == s && s.phase == outputStarting
|
||||
current := XUDPManager.Map[meta.GlobalID]
|
||||
restart := err != nil && !fresh
|
||||
retry := restart && live && (current == x || current == nil)
|
||||
admitted := live && current == x
|
||||
if restart {
|
||||
s.closeLocked(x, false, false)
|
||||
if retry {
|
||||
x.responseErr = io.ErrClosedPipe
|
||||
x.response = buf.ReleaseMulti(x.response)
|
||||
x.responseWake.Broadcast()
|
||||
delete(XUDPManager.Map, meta.GlobalID)
|
||||
}
|
||||
} else if admitted {
|
||||
w.count++
|
||||
if x.responseErr == nil || len(x.response) != 0 {
|
||||
s.phase = outputOpen
|
||||
w.active++
|
||||
} else {
|
||||
s.closeLocked(x, x.responseErr == io.ErrClosedPipe, true)
|
||||
}
|
||||
w.scheduleLocked(s)
|
||||
}
|
||||
w.Unlock()
|
||||
x.access.Unlock()
|
||||
if retry {
|
||||
// Keep the manager lock until the replacement is registered.
|
||||
continue
|
||||
}
|
||||
XUDPManager.Unlock()
|
||||
if err != nil {
|
||||
buf.ReleaseMulti(data)
|
||||
}
|
||||
if restart {
|
||||
if !live {
|
||||
return nil
|
||||
}
|
||||
x.expire()
|
||||
}
|
||||
if restart || !admitted {
|
||||
s.abort()
|
||||
return errors.New("failed to add new session")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user