Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions transport/internet/finalmask/sudoku/sudoku_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import (
vin "github.com/xtls/xray-core/proxy/vless/inbound"
vout "github.com/xtls/xray-core/proxy/vless/outbound"
testingtcp "github.com/xtls/xray-core/testing/servers/tcp"
testingudp "github.com/xtls/xray-core/testing/servers/udp"
"github.com/xtls/xray-core/transport/internet"
hytransport "github.com/xtls/xray-core/transport/internet/hysteria"
"github.com/xtls/xray-core/transport/internet/reality"
Expand Down Expand Up @@ -350,12 +351,11 @@ func runHysteria2Case(t *testing.T, bin string, mode trafficMode, payloadSize in
backend := startXOREchoServer(t)
defer backend.Close()

serverPort := testingtcp.PickPort()
relayPort := testingtcp.PickPort()
clientPort := testingtcp.PickPort()

relay := startUDPRelay(t, int(relayPort), int(serverPort))
relay := startUDPRelay(t)
defer relay.Close()
serverPort := xnet.Port(relay.target.Port)
relayPort := relay.conn.LocalAddr().(*stdnet.UDPAddr).Port
clientPort := testingtcp.PickPort()

ct, ctHash := cert.MustGenerate(nil, cert.CommonName("localhost"), cert.DNSNames("localhost"))
auth := "hy2-auth-secret"
Expand Down Expand Up @@ -1128,13 +1128,14 @@ func (w *captureWriter) Write(p []byte) (int, error) {
return len(p), nil
}

func startUDPRelay(t *testing.T, listenPort, targetPort int) *udpRelay {
func startUDPRelay(t *testing.T) *udpRelay {
t.Helper()
conn, err := stdnet.ListenPacket("udp", fmt.Sprintf("127.0.0.1:%d", listenPort))
conn, err := stdnet.ListenPacket("udp4", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
targetAddr := &stdnet.UDPAddr{IP: stdnet.IPv4(127, 0, 0, 1), Port: targetPort}
// Pick the server port while the relay already owns its UDP port.
targetAddr := &stdnet.UDPAddr{IP: stdnet.IPv4(127, 0, 0, 1), Port: int(testingudp.PickPort())}
r := &udpRelay{
conn: conn,
target: targetAddr,
Expand Down
135 changes: 60 additions & 75 deletions transport/internet/splithttp/client.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
package splithttp

import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/http/httptrace"
Expand Down Expand Up @@ -34,10 +32,7 @@ type DefaultDialerClient struct {
transportConfig *Config
client *http.Client
closed atomic.Bool
httpVersion string
// pool of net.Conn, created using dialUploadConn
uploadRawPool *sync.Pool
dialUploadConn func(ctxInner context.Context) (net.Conn, error)
uploadTransport *http.Transport // HTTP/1.1 packet uploads only
}

func (c *DefaultDialerClient) IsClosed() bool {
Expand Down Expand Up @@ -98,88 +93,78 @@ func (c *DefaultDialerClient) OpenStream(ctx context.Context, url string, sessio
return
}

// The transport may close a request before retrying a stale idle connection.
// Keep unread buffers until RoundTrip returns, releasing consumed ones as we go.
type packetBody struct {
mu sync.Mutex
data buf.MultiBufferContainer
}

func (b *packetBody) Read(p []byte) (int, error) {
b.mu.Lock()
defer b.mu.Unlock()
return b.data.Read(p)
}

func (b *packetBody) release() {
b.mu.Lock()
defer b.mu.Unlock()
b.data.Close()
}

func (c *DefaultDialerClient) PostPacket(ctx context.Context, url string, sessionId string, seqStr string, payload buf.MultiBuffer) error {
method := c.transportConfig.GetNormalizedUplinkHTTPMethod()
req, err := http.NewRequestWithContext(context.WithoutCancel(ctx), method, url, nil)
if err != nil {
buf.ReleaseMulti(payload)
return err
}
c.transportConfig.FillPacketRequest(req, sessionId, seqStr, payload)

if c.httpVersion != "1.1" {
resp, err := c.client.Do(req)
if err != nil {
c.closed.Store(true)
return err
}

io.Copy(io.Discard, resp.Body)
defer resp.Body.Close()

if resp.StatusCode != 200 {
return errors.New("bad status code:", resp.Status)
}
} else {
// stringify the entire HTTP/1.1 request so it can be
// safely retried. if instead req.Write is called multiple
// times, the body is already drained after the first
// request
requestBuff := new(bytes.Buffer)
requestBuff.Grow(512 + int(req.ContentLength))
common.Must(req.Write(requestBuff))

var uploadConn any
var h1UploadConn *H1Conn

for {
uploadConn = c.uploadRawPool.Get()
newConnection := uploadConn == nil
if newConnection {
newConn, err := c.dialUploadConn(context.WithoutCancel(ctx))
if err != nil {
return err
}
h1UploadConn = NewH1Conn(newConn)
uploadConn = h1UploadConn
} else {
h1UploadConn = uploadConn.(*H1Conn)

// TODO: Replace 0 here with a config value later
// Or add some other condition for optimization purposes
if h1UploadConn.UnreadedResponsesCount > 0 {
resp, err := http.ReadResponse(h1UploadConn.RespBufReader, req)
if err != nil {
c.closed.Store(true)
return fmt.Errorf("error while reading response: %s", err.Error())
}
io.Copy(io.Discard, resp.Body)
defer resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("got non-200 error response code: %d", resp.StatusCode)
}
}
}

_, err := h1UploadConn.Write(requestBuff.Bytes())
// if the write failed, we try another connection from
// the pool, until the write on a new connection fails.
// failed writes to a pooled connection are normal when
// the connection has been closed in the meantime.
if err == nil {
break
} else if newConnection {
return err
placement := c.transportConfig.GetNormalizedUplinkDataPlacement()
if c.uploadTransport != nil && (placement == PlacementBody || placement == PlacementAuto) {
body := &packetBody{data: buf.MultiBufferContainer{MultiBuffer: payload}}
defer body.release()
size := payload.Len()
req.Header = c.transportConfig.GetRequestHeader()
req.ContentLength = int64(size)
req.Body = io.NopCloser(body)
req.GetBody = func() (io.ReadCloser, error) {
body.mu.Lock()
defer body.mu.Unlock()
if body.data.Len() != size {
return nil, io.ErrUnexpectedEOF
}
return io.NopCloser(body), nil
}

c.uploadRawPool.Put(uploadConn)
c.transportConfig.applyPacketMeta(req, sessionId, seqStr)
} else if err := c.transportConfig.FillPacketRequest(req, sessionId, seqStr, payload); err != nil {
return err
}

return nil
var resp *http.Response
if c.uploadTransport != nil {
// Keep the packet on this origin and let Transport handle stale idle connections.
ctx, cancel := context.WithTimeout(req.Context(), net.ConnIdleTimeout)
defer cancel()
resp, err = c.uploadTransport.RoundTrip(req.WithContext(ctx))
} else {
resp, err = c.client.Do(req)
}
if err != nil {
c.closed.Store(true)
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return errors.New("bad status code:", resp.Status)
}
_, err = io.Copy(io.Discard, resp.Body)
return err
}

// HTTP/1.1 and HTTP/2 will close itself, we only handle HTTP/3 here
func (c *DefaultDialerClient) Close() error {
if c.uploadTransport != nil {
c.uploadTransport.CloseIdleConnections()
}
transport := c.client.Transport
if h3Transport, ok := transport.(*http3.Transport); ok {
h3Transport.Close()
Expand Down
7 changes: 5 additions & 2 deletions transport/internet/splithttp/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,11 @@ func (c *Config) FillPacketRequest(request *http.Request, sessionId string, seqS
}
}

c.applyPacketMeta(request, sessionId, seqStr)
return nil
}

func (c *Config) applyPacketMeta(request *http.Request, sessionId, seqStr string) {
length := int(c.GetNormalizedXPaddingBytes().rand())
config := XPaddingConfig{Length: length}

Expand All @@ -376,8 +381,6 @@ func (c *Config) FillPacketRequest(request *http.Request, sessionId string, seqS

c.ApplyXPaddingToRequest(request, config)
c.ApplyMetaToRequest(request, sessionId, seqStr)

return nil
}

func (c *Config) ExtractMetaFromRequest(req *http.Request, path string) (sessionId string, seqStr string) {
Expand Down
127 changes: 73 additions & 54 deletions transport/internet/splithttp/dialer.go
Original file line number Diff line number Diff line change
Expand Up @@ -281,9 +281,13 @@ func createHTTPClient(dest net.Destination, streamSettings *internet.MemoryStrea
client: &http.Client{
Transport: transport,
},
httpVersion: httpVersion,
uploadRawPool: &sync.Pool{},
dialUploadConn: dialContext,
}
if httpVersion == "1.1" {
// The chunked download workaround must not disable upload reuse.
client.uploadTransport = transport.(*http.Transport).Clone()
client.uploadTransport.DisableKeepAlives = false
client.uploadTransport.DisableCompression = true
client.uploadTransport.MaxIdleConnsPerHost = max(1, transportConfig.GetNormalizedScMaxBufferedPosts())
}

return client
Expand Down Expand Up @@ -478,63 +482,78 @@ func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.Me

dynamicHTTPClient := httpClient
dynamicXmuxClient := xmuxClient
for {
// by offloading the uploads into a buffered pipe, multiple conn.Write
// calls get automatically batched together into larger POST requests.
// without batching, bandwidth is extremely limited.
remainder, err := uploadPipeReader.ReadMultiBuffer()
if err != nil {
break
var remainder buf.MultiBuffer
defer func() { buf.ReleaseMulti(remainder) }()
var pending []<-chan struct{}
window := max(1, transportConfiguration.GetNormalizedScMaxBufferedPosts())
failed := done.New()
for !failed.Done() {
// Keep the next batch in the bounded pipe until it can be sent.
if scMinPostsIntervalMs.From > 0 && !lastWrite.IsZero() {
time.Sleep(time.Duration(scMinPostsIntervalMs.rand())*time.Millisecond - time.Since(lastWrite))
}

doSplit := atomic.Bool{}
for doSplit.Store(true); doSplit.Load(); {
var chunk buf.MultiBuffer
remainder, chunk = buf.SplitSize(remainder, maxUploadSize)
if chunk.IsEmpty() {
break
if len(pending) >= window {
select {
case <-pending[0]:
pending = pending[1:]
case <-failed.Wait():
}
}
if failed.Done() {
return
}
if remainder.IsEmpty() {
var err error
remainder, err = uploadPipeReader.ReadMultiBuffer()
if err != nil {
return
}
}
var chunk buf.MultiBuffer
remainder, chunk = buf.SplitSize(remainder, maxUploadSize)
if chunk.IsEmpty() {
continue
}
seqStr := strconv.FormatInt(seq, 10)
seq++
lastWrite = time.Now()
if dynamicXmuxClient != nil && (dynamicXmuxClient.LeftRequests.Add(-1) <= 0 ||
(dynamicXmuxClient.UnreusableAt != time.Time{} && lastWrite.After(dynamicXmuxClient.UnreusableAt))) {
dynamicHTTPClient, dynamicXmuxClient = getHTTPClient(ctx, dest, streamSettings)
}

wroteRequest := done.New()

ctx := httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{
WroteRequest: func(httptrace.WroteRequestInfo) {
client, direct := dynamicHTTPClient.(*DefaultDialerClient)
var ack chan struct{}
if direct && client.uploadTransport != nil {
// Bound the sequence gap even if later responses arrive first.
ack = make(chan struct{})
pending = append(pending, ack)
}
wroteRequest := done.New()
reqCtx := httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{
WroteRequest: func(info httptrace.WroteRequestInfo) {
// Transport may retry a failed write on a stale connection.
if info.Err == nil {
wroteRequest.Close()
},
})

seqStr := strconv.FormatInt(seq, 10)
seq += 1

if scMinPostsIntervalMs.From > 0 {
time.Sleep(time.Duration(scMinPostsIntervalMs.rand())*time.Millisecond - time.Since(lastWrite))
}
},
})
go func(hClient DialerClient) {
err := hClient.PostPacket(reqCtx, requestURL.String(), sessionId, seqStr, chunk)
if err != nil {
errors.LogInfoInner(ctx, err, "failed to send upload")
failed.Close()
uploadPipeReader.Interrupt()
}

lastWrite = time.Now()

if dynamicXmuxClient != nil && (dynamicXmuxClient.LeftRequests.Add(-1) <= 0 ||
(dynamicXmuxClient.UnreusableAt != time.Time{} && lastWrite.After(dynamicXmuxClient.UnreusableAt))) {
dynamicHTTPClient, dynamicXmuxClient = getHTTPClient(ctx, dest, streamSettings)
if ack != nil {
close(ack)
}

go func(hClient DialerClient) {
err := hClient.PostPacket(
ctx,
requestURL.String(),
sessionId,
seqStr,
chunk,
)
wroteRequest.Close()
if err != nil {
errors.LogInfoInner(ctx, err, "failed to send upload")
uploadPipeReader.Interrupt()
doSplit.Store(false)
}
}(dynamicHTTPClient)

if _, ok := dynamicHTTPClient.(*DefaultDialerClient); ok {
<-wroteRequest.Wait()
wroteRequest.Close()
}(dynamicHTTPClient)
if direct {
select {
case <-wroteRequest.Wait():
case <-failed.Wait():
}
}
}
Expand Down
Loading
Loading