From 2e4c3db656e8b2ae73be546acf513a888b436ae8 Mon Sep 17 00:00:00 2001 From: Free-Guy-IR Date: Thu, 3 Dec 2026 06:23:18 +0330 Subject: [PATCH 1/4] fix(speedcap): count a user's download when the client side takes it The user downlink counter counted bytes when the outbound handed them to the dispatcher, before the speed cap's bucket wait and before the inbound wrote them to the client. When a client closed a capped download midway, the read parked in the bucket wait was counted and never sent: 65,536 bytes in every measured abort. On the Dispatch path the bytes still in the downlink pipe and the batch whose write failed were counted as well. - Dispatch path (Shadowsocks, Trojan, VMess, mux sub-sessions): the downlink pipe reader counts a batch when the inbound comes back for the next read, drops the batch it holds when the inbound interrupts it, and at the end of the connection counts a last batch only if the stream finished and the pipe is drained. - DispatchLink path (VLESS, socks, HTTP CONNECT): the user's SizeStatWriter counts after the bucket wait and after the client writer returned without an error. - Uplink is unchanged: it is counted when it arrives from the client. - xray-stats-register-race.patch keeps its changes; only the context of its dispatcher hunks follows the new lines. Evidence on Linux, a throwaway container on the dev box, with the scenario test binary built from this tree (8 Mbit/s cap, raw VLESS and Trojan clients that read part of an endless download, drain and reset): - xray from the previous patch: 8 of 8 aborts per protocol over-counted 65,536 bytes (VLESS 524,288 bytes, 10.000%; Trojan 524,288 bytes, 9.861%); 48 cap changes racing 63 aborts: +4,784,128 bytes. - xray from this patch: 0 bytes on all 16 aborts; 0 bytes in the interleaving run. macOS gave the same per-abort numbers before and after. Not changed: bytes the node's TCP send buffer and a relay still hold when a client aborts are counted as before. --- Dockerfile | 7 + Makefile | 3 +- patches/xray-per-user-speed-cap.patch | 905 ++++++++++++++++++++++++- patches/xray-stats-register-race.patch | 21 +- 4 files changed, 922 insertions(+), 14 deletions(-) diff --git a/Dockerfile b/Dockerfile index 0b57c2b8..6004368c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -145,6 +145,13 @@ RUN git init -q . \ && grep -qF "link.Writer = speedcap.NewWriter(ctx, user.Email, sessionInbound.Tag, speedcap.Downlink, link.Writer)" app/dispatcher/default.go \ && grep -qF "var splice = inbound.CanSpliceCopy == 1 && !speedcap.CappedUser(inbound.User, inbound.Tag)" proxy/proxy.go \ && grep -qF "w, capped, err := spliceUntilCapped(tc, readerConn, inbound)" proxy/proxy.go \ + && grep -qF "downlinkReader.CountDelivered(ctx, c)" app/dispatcher/default.go \ + && ! grep -qF "Writer: outboundLink.Writer," app/dispatcher/default.go \ + && grep -qF "CountWritten: true," app/dispatcher/default.go \ + && grep -qF "CountWritten bool" app/dispatcher/stats.go \ + && grep -qF "func (r *Reader) CountDelivered(ctx context.Context, counter DeliveryCounter) {" transport/pipe/delivery.go \ + && test "$(grep -c 'r.delivery.settle()' transport/pipe/reader.go)" = "2" \ + && grep -qF "r.delivery.finish(false)" transport/pipe/reader.go \ && git apply --verbose /patches/xray-pinned-ca-servername.patch \ && grep -qF 'return errors.New("Pinning CA needs a valid ServerName")' transport/internet/tls/config.go \ && grep -qF "config := tlsConfig.GetTLSConfig(tls.WithDestination(dest))" transport/internet/grpc/dial.go \ diff --git a/Makefile b/Makefile index 3ee73b02..d9922284 100644 --- a/Makefile +++ b/Makefile @@ -287,7 +287,8 @@ test_xray_patches: cd "$(XRAY_SRC)" && CGO_ENABLED=1 GOTOOLCHAIN=local $(GO_TEST_VISIBLE) -race -count=1 -run 'TestEarlyDataConnAddressesBeforeFirstWrite' ./transport/internet/websocket/ cd "$(XRAY_SRC)" && CGO_ENABLED=1 GOTOOLCHAIN=local $(GO_TEST_VISIBLE) -race -count=3 -timeout 300s -run 'TestCloseWithPacketInFlightDoesNotPanic|TestProcessAfterCloseDoesNotPanic|TestProcessWhileClosingDoesNotRaceOrPanic|TestAClosedHandlerNeverBuildsANewTunnel|TestProcessTCPWhileClosingDoesNotRaceOrPanic|TestADialAfterCloseUsesTheTunnelProcessTookUnderTheLock|TestClosingABindTwiceDoesNotPanic' ./proxy/wireguard/ ./proxy/wireguard/gvisortun/ cd "$(XRAY_SRC)" && CGO_ENABLED=1 GOTOOLCHAIN=local $(GO_TEST_VISIBLE) -race -count=1 -timeout 600s ./app/proxyman/speedcap/... - cd "$(XRAY_SRC)" && CGO_ENABLED=1 GOTOOLCHAIN=local $(GO_TEST_VISIBLE) -race -count=1 -run 'TestWrapLinkCapsTheUserAndKeepsTheStatsWriterOutermost' ./app/dispatcher/ + cd "$(XRAY_SRC)" && CGO_ENABLED=1 GOTOOLCHAIN=local $(GO_TEST_VISIBLE) -race -count=1 -run 'TestWrapLinkCapsTheUserAndKeepsTheStatsWriterOutermost|TestADispatchedDownlinkCountsOnlyWhatTheInboundCameBackForMoreAfter|TestALinkedDownlinkCountsOnlyWhatTheClientWriterTook' ./app/dispatcher/ + cd "$(XRAY_SRC)" && CGO_ENABLED=1 GOTOOLCHAIN=local $(GO_TEST_VISIBLE) -race -count=3 ./transport/pipe/ cd "$(XRAY_SRC)" && CGO_ENABLED=1 GOTOOLCHAIN=local $(GO_TEST_VISIBLE) -race -count=1 -timeout 900s -run 'TestSpeedCap' ./testing/scenarios/ install_wg: update_os diff --git a/patches/xray-per-user-speed-cap.patch b/patches/xray-per-user-speed-cap.patch index eede1145..43384400 100644 --- a/patches/xray-per-user-speed-cap.patch +++ b/patches/xray-per-user-speed-cap.patch @@ -1,5 +1,5 @@ diff --git a/app/dispatcher/default.go b/app/dispatcher/default.go -index e6f8965..23f215e 100644 +index e6f8965..a8abd7a 100644 --- a/app/dispatcher/default.go +++ b/app/dispatcher/default.go @@ -7,6 +7,7 @@ import ( @@ -19,7 +19,19 @@ index e6f8965..23f215e 100644 p := d.policy.ForLevel(user.Level) if p.Stats.UserUplink { name := "user>>>" + user.Email + ">>>traffic>>>uplink" -@@ -200,6 +203,10 @@ func WrapLink(ctx context.Context, policyManager policy.Manager, statsManager st +@@ -173,10 +176,7 @@ func (d *DefaultDispatcher) getLink(ctx context.Context) (*transport.Link, *tran + if p.Stats.UserDownlink { + name := "user>>>" + user.Email + ">>>traffic>>>downlink" + if c, _ := stats.GetOrRegisterCounter(d.stats, name); c != nil { +- outboundLink.Writer = &SizeStatWriter{ +- Counter: c, +- Writer: outboundLink.Writer, +- } ++ downlinkReader.CountDelivered(ctx, c) + } + } + +@@ -200,6 +200,10 @@ func WrapLink(ctx context.Context, policyManager policy.Manager, statsManager st user = sessionInbound.User } @@ -30,6 +42,155 @@ index e6f8965..23f215e 100644 link.Reader = &buf.TimeoutWrapperReader{Reader: link.Reader} if user != nil && len(user.Email) > 0 { +@@ -214,8 +218,9 @@ func WrapLink(ctx context.Context, policyManager policy.Manager, statsManager st + name := "user>>>" + user.Email + ">>>traffic>>>downlink" + if c, _ := stats.GetOrRegisterCounter(statsManager, name); c != nil { + link.Writer = &SizeStatWriter{ +- Counter: c, +- Writer: link.Writer, ++ Counter: c, ++ Writer: link.Writer, ++ CountWritten: true, + } + } + } +diff --git a/app/dispatcher/delivered_test.go b/app/dispatcher/delivered_test.go +new file mode 100644 +index 0000000..f375872 +--- /dev/null ++++ b/app/dispatcher/delivered_test.go +@@ -0,0 +1,131 @@ ++package dispatcher ++ ++import ( ++ "context" ++ "errors" ++ "testing" ++ ++ "github.com/xtls/xray-core/app/policy" ++ "github.com/xtls/xray-core/app/stats" ++ "github.com/xtls/xray-core/common/buf" ++ "github.com/xtls/xray-core/common/net" ++ "github.com/xtls/xray-core/common/protocol" ++ "github.com/xtls/xray-core/common/session" ++ "github.com/xtls/xray-core/transport" ++ "github.com/xtls/xray-core/transport/pipe" ++) ++ ++const deliveredEmail = "delivered@test" ++ ++func deliveredStats(t *testing.T) (*stats.Manager, *policy.Instance) { ++ t.Helper() ++ ctx := context.Background() ++ manager, err := stats.NewManager(ctx, &stats.Config{}) ++ if err != nil { ++ t.Fatal(err) ++ } ++ policies, err := policy.New(ctx, &policy.Config{Level: map[uint32]*policy.Policy{ ++ 0: {Stats: &policy.Policy_Stats{UserUplink: true, UserDownlink: true}}, ++ }}) ++ if err != nil { ++ t.Fatal(err) ++ } ++ return manager, policies ++} ++ ++func deliveredContext(parent context.Context) context.Context { ++ return session.ContextWithInbound(parent, &session.Inbound{ ++ User: &protocol.MemoryUser{Email: deliveredEmail}, ++ Source: net.TCPDestination(net.LocalHostIP, 40000), ++ }) ++} ++ ++func bytesOf(size int) buf.MultiBuffer { ++ b := buf.New() ++ b.Extend(int32(size)) ++ return buf.MultiBuffer{b} ++} ++ ++func counted(t *testing.T, manager *stats.Manager, direction string) int64 { ++ t.Helper() ++ c := manager.GetCounter("user>>>" + deliveredEmail + ">>>traffic>>>" + direction) ++ if c == nil { ++ t.Fatalf("no %s counter was registered", direction) ++ } ++ return c.Value() ++} ++ ++func TestADispatchedDownlinkCountsOnlyWhatTheInboundCameBackForMoreAfter(t *testing.T) { ++ manager, policies := deliveredStats(t) ++ d := &DefaultDispatcher{policy: policies, stats: manager} ++ ctx, cancel := context.WithCancel(deliveredContext(context.Background())) ++ defer cancel() ++ inbound, outbound := d.getLink(ctx) ++ ++ for range 3 { ++ if err := outbound.Writer.WriteMultiBuffer(bytesOf(1000)); err != nil { ++ t.Fatal(err) ++ } ++ } ++ if got := counted(t, manager, "downlink"); got != 0 { ++ t.Fatalf("%d downlink bytes were counted while they still sat in the pipe", got) ++ } ++ mb, err := inbound.Reader.ReadMultiBuffer() ++ if err != nil || mb.Len() != 3000 { ++ t.Fatalf("the inbound read %d bytes, %v", mb.Len(), err) ++ } ++ buf.ReleaseMulti(mb) ++ if got := counted(t, manager, "downlink"); got != 0 { ++ t.Fatalf("%d downlink bytes were counted before the inbound came back for more", got) ++ } ++ if err := outbound.Writer.WriteMultiBuffer(bytesOf(500)); err != nil { ++ t.Fatal(err) ++ } ++ mb, err = inbound.Reader.ReadMultiBuffer() ++ if err != nil || mb.Len() != 500 { ++ t.Fatalf("the inbound read %d bytes, %v", mb.Len(), err) ++ } ++ buf.ReleaseMulti(mb) ++ if got := counted(t, manager, "downlink"); got != 3000 { ++ t.Fatalf("the downlink counter holds %d, want the 3000 bytes the inbound came back after", got) ++ } ++ if err := outbound.Writer.WriteMultiBuffer(bytesOf(8000)); err != nil { ++ t.Fatal(err) ++ } ++ inbound.Reader.(*pipe.Reader).Interrupt() ++ if got := counted(t, manager, "downlink"); got != 3000 { ++ t.Fatalf("the downlink counter holds %d after the inbound gave up, want 3000", got) ++ } ++ ++ if err := inbound.Writer.WriteMultiBuffer(bytesOf(700)); err != nil && !errors.Is(err, context.Canceled) { ++ t.Fatal(err) ++ } ++ if got := counted(t, manager, "uplink"); got != 700 { ++ t.Fatalf("the uplink counter holds %d, want the 700 bytes the client sent", got) ++ } ++} ++ ++type failingWriter struct{} ++ ++func (failingWriter) WriteMultiBuffer(mb buf.MultiBuffer) error { ++ buf.ReleaseMulti(mb) ++ return errors.New("the client is gone") ++} ++ ++func TestALinkedDownlinkCountsOnlyWhatTheClientWriterTook(t *testing.T) { ++ manager, policies := deliveredStats(t) ++ accepted := WrapLink(deliveredContext(context.Background()), policies, manager, &transport.Link{Reader: buf.NewReader(nil), Writer: buf.Discard}) ++ if err := accepted.Writer.WriteMultiBuffer(bytesOf(1200)); err != nil { ++ t.Fatal(err) ++ } ++ if got := counted(t, manager, "downlink"); got != 1200 { ++ t.Fatalf("the downlink counter holds %d after a delivered write of 1200", got) ++ } ++ refused := WrapLink(deliveredContext(context.Background()), policies, manager, &transport.Link{Reader: buf.NewReader(nil), Writer: failingWriter{}}) ++ if err := refused.Writer.WriteMultiBuffer(bytesOf(800)); err == nil { ++ t.Fatal("the failing client writer reported success") ++ } ++ if got := counted(t, manager, "downlink"); got != 1200 { ++ t.Fatalf("the downlink counter holds %d, a write the client never took was counted", got) ++ } ++} diff --git a/app/dispatcher/speedcap_test.go b/app/dispatcher/speedcap_test.go new file mode 100644 index 0000000..0674c1a @@ -138,6 +299,37 @@ index 0000000..0674c1a + mb, _ := endlessReader{}.ReadMultiBuffer() + return mb +} +diff --git a/app/dispatcher/stats.go b/app/dispatcher/stats.go +index 8fac019..1d2ae17 100644 +--- a/app/dispatcher/stats.go ++++ b/app/dispatcher/stats.go +@@ -7,13 +7,22 @@ import ( + ) + + type SizeStatWriter struct { +- Counter stats.Counter +- Writer buf.Writer ++ Counter stats.Counter ++ Writer buf.Writer ++ CountWritten bool + } + + func (w *SizeStatWriter) WriteMultiBuffer(mb buf.MultiBuffer) error { +- w.Counter.Add(int64(mb.Len())) +- return w.Writer.WriteMultiBuffer(mb) ++ size := int64(mb.Len()) ++ if !w.CountWritten { ++ w.Counter.Add(size) ++ return w.Writer.WriteMultiBuffer(mb) ++ } ++ if err := w.Writer.WriteMultiBuffer(mb); err != nil { ++ return err ++ } ++ w.Counter.Add(size) ++ return nil + } + + func (w *SizeStatWriter) Close() error { diff --git a/app/proxyman/speedcap/bucket.go b/app/proxyman/speedcap/bucket.go new file mode 100644 index 0000000..7612a90 @@ -2463,6 +2655,310 @@ index dbd81d6..bbc7ae1 100644 func readV(ctx context.Context, reader buf.Reader, writer buf.Writer, timer signal.ActivityUpdater, readCounter stats.Counter) error { errors.LogDebug(ctx, "CopyRawConn (maybe) readv") if err := buf.Copy(reader, writer, buf.UpdateActivity(timer), buf.AddToStatCounter(readCounter)); err != nil { +diff --git a/testing/scenarios/speedcap_delivered_test.go b/testing/scenarios/speedcap_delivered_test.go +new file mode 100644 +index 0000000..a625589 +--- /dev/null ++++ b/testing/scenarios/speedcap_delivered_test.go +@@ -0,0 +1,298 @@ ++package scenarios ++ ++import ( ++ "context" ++ "crypto/sha256" ++ "encoding/binary" ++ "encoding/hex" ++ "errors" ++ "fmt" ++ "math/rand" ++ gonet "net" ++ "sync" ++ "sync/atomic" ++ "testing" ++ "time" ++ ++ "github.com/xtls/xray-core/app/commander" ++ "github.com/xtls/xray-core/app/proxyman/command" ++ "github.com/xtls/xray-core/app/router" ++ "github.com/xtls/xray-core/app/stats" ++ statscmd "github.com/xtls/xray-core/app/stats/command" ++ "github.com/xtls/xray-core/common/net" ++ "github.com/xtls/xray-core/common/protocol" ++ "github.com/xtls/xray-core/common/serial" ++ "github.com/xtls/xray-core/common/uuid" ++ core "github.com/xtls/xray-core/core" ++ "github.com/xtls/xray-core/proxy/trojan" ++ "github.com/xtls/xray-core/proxy/vless" ++ vlessinbound "github.com/xtls/xray-core/proxy/vless/inbound" ++ "github.com/xtls/xray-core/testing/servers/tcp" ++ "google.golang.org/grpc" ++ "google.golang.org/grpc/credentials/insecure" ++) ++ ++const deliveredUser = "alice" ++ ++type deliveredLab struct { ++ apiPort net.Port ++ target streamTarget ++ vlessPort net.Port ++ trojanPort net.Port ++ vlessID uuid.UUID ++ trojanKey string ++ stats statscmd.StatsServiceClient ++} ++ ++func startDeliveredLab(t *testing.T) *deliveredLab { ++ t.Helper() ++ secret := uuid.New() ++ lab := &deliveredLab{ ++ apiPort: tcp.PickPort(), ++ target: startStreamServer(t, nil), ++ vlessPort: tcp.PickPort(), ++ trojanPort: tcp.PickPort(), ++ vlessID: uuid.New(), ++ trojanKey: "delivered-" + secret.String(), ++ } ++ server := &core.Config{ ++ App: []*serial.TypedMessage{ ++ serial.ToTypedMessage(&commander.Config{ ++ Tag: "api", ++ Service: []*serial.TypedMessage{serial.ToTypedMessage(&command.Config{}), serial.ToTypedMessage(&statscmd.Config{})}, ++ }), ++ serial.ToTypedMessage(&stats.Config{}), ++ serial.ToTypedMessage(&router.Config{Rule: []*router.RoutingRule{{ ++ InboundTag: []string{"api"}, ++ TargetTag: &router.RoutingRule_Tag{Tag: "api"}, ++ }}}), ++ speedCapPolicy(), ++ }, ++ Inbound: []*core.InboundHandlerConfig{ ++ apiInbound("api", lab.apiPort), ++ { ++ Tag: "vless", ++ ReceiverSettings: listenOn(lab.vlessPort, nil), ++ ProxySettings: serial.ToTypedMessage(&vlessinbound.Config{ ++ Decryption: "none", ++ Clients: []*protocol.User{{Email: deliveredUser, Account: serial.ToTypedMessage(&vless.Account{Id: lab.vlessID.String()})}}, ++ }), ++ }, ++ { ++ Tag: "trojan", ++ ReceiverSettings: listenOn(lab.trojanPort, nil), ++ ProxySettings: serial.ToTypedMessage(&trojan.ServerConfig{ ++ Users: []*protocol.User{{Email: deliveredUser, Account: serial.ToTypedMessage(&trojan.Account{Password: lab.trojanKey})}}, ++ }), ++ }, ++ }, ++ Outbound: []*core.OutboundHandlerConfig{allowingFreedom(lab.target)}, ++ } ++ startCapturedXray(t, server) ++ waitListening(t, lab.apiPort, lab.vlessPort, lab.trojanPort) ++ conn, err := grpc.NewClient(fmt.Sprintf("127.0.0.1:%d", lab.apiPort), grpc.WithTransportCredentials(insecure.NewCredentials())) ++ if err != nil { ++ t.Fatal(err) ++ } ++ t.Cleanup(func() { conn.Close() }) ++ lab.stats = statscmd.NewStatsServiceClient(conn) ++ return lab ++} ++ ++func (lab *deliveredLab) downlink(t *testing.T, reset bool) int64 { ++ t.Helper() ++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) ++ defer cancel() ++ response, err := lab.stats.GetStats(ctx, &statscmd.GetStatsRequest{Name: "user>>>" + deliveredUser + ">>>traffic>>>downlink", Reset_: reset}) ++ if err != nil { ++ return 0 ++ } ++ return response.GetStat().GetValue() ++} ++ ++func (lab *deliveredLab) settledDownlink(t *testing.T) int64 { ++ t.Helper() ++ last, stableSince := lab.downlink(t, false), time.Now() ++ for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline); { ++ time.Sleep(50 * time.Millisecond) ++ if value := lab.downlink(t, false); value != last { ++ last, stableSince = value, time.Now() ++ continue ++ } ++ if time.Since(stableSince) >= 400*time.Millisecond { ++ break ++ } ++ } ++ return lab.downlink(t, true) ++} ++ ++type deliveredProtocol struct { ++ name string ++ port func(*deliveredLab) net.Port ++ request func(*deliveredLab) []byte ++ header int64 ++} ++ ++var deliveredProtocols = []deliveredProtocol{ ++ {name: "vless", port: func(lab *deliveredLab) net.Port { return lab.vlessPort }, request: (*deliveredLab).vlessRequest, header: 2}, ++ {name: "trojan", port: func(lab *deliveredLab) net.Port { return lab.trojanPort }, request: (*deliveredLab).trojanRequest, header: 0}, ++} ++ ++func (lab *deliveredLab) vlessRequest() []byte { ++ request := []byte{0} ++ request = append(request, lab.vlessID.Bytes()...) ++ request = append(request, 0, 1) ++ request = binary.BigEndian.AppendUint16(request, uint16(lab.target.port)) ++ request = append(request, 1) ++ return append(request, lab.target.ip.To4()...) ++} ++ ++func (lab *deliveredLab) trojanRequest() []byte { ++ sum := sha256.Sum224([]byte(lab.trojanKey)) ++ request := []byte(hex.EncodeToString(sum[:])) ++ request = append(request, '\r', '\n', 1, 1) ++ request = append(request, lab.target.ip.To4()...) ++ request = binary.BigEndian.AppendUint16(request, uint16(lab.target.port)) ++ return append(request, '\r', '\n') ++} ++ ++func abortedDownload(lab *deliveredLab, p deliveredProtocol, abortAfter int64) (int64, error) { ++ conn, err := (&gonet.Dialer{Timeout: 5 * time.Second}).Dial("tcp4", fmt.Sprintf("127.0.0.1:%d", p.port(lab))) ++ if err != nil { ++ return 0, err ++ } ++ tcpConn := conn.(*gonet.TCPConn) ++ defer func() { ++ tcpConn.SetLinger(0) ++ tcpConn.Close() ++ }() ++ if _, err := tcpConn.Write(p.request(lab)); err != nil { ++ return 0, err ++ } ++ buffer := make([]byte, 256<<10) ++ var received int64 ++ tcpConn.SetReadDeadline(time.Now().Add(30 * time.Second)) ++ for received < abortAfter+p.header { ++ n, err := tcpConn.Read(buffer) ++ received += int64(n) ++ if err != nil { ++ return received - p.header, fmt.Errorf("the download ended after %d bytes: %w", received, err) ++ } ++ } ++ for { ++ tcpConn.SetReadDeadline(time.Now().Add(5 * time.Millisecond)) ++ n, err := tcpConn.Read(buffer) ++ received += int64(n) ++ if err != nil { ++ var timeout gonet.Error ++ if errors.As(err, &timeout) && timeout.Timeout() { ++ return received - p.header, nil ++ } ++ return received - p.header, err ++ } ++ } ++} ++ ++func TestSpeedCapCountsOnlyTheBytesAnAbortedClientWasSent(t *testing.T) { ++ lab := startDeliveredLab(t) ++ setUserSpeeds(t, lab.apiPort, "vless", speedCapOperation(false, 0, speedEntry{email: deliveredUser, down: 8_000_000, revision: 1})) ++ if _, err := abortedDownload(lab, deliveredProtocols[0], 1_200_000); err != nil { ++ t.Fatal(err) ++ } ++ lab.settledDownlink(t) ++ ++ const aborts = 8 ++ for _, p := range deliveredProtocols { ++ var received, counted int64 ++ var exact int ++ var diffs []int64 ++ for i := range aborts { ++ got, err := abortedDownload(lab, p, int64(500_000+i*37_000)) ++ if err != nil { ++ t.Fatalf("%s abort %d: %v", p.name, i, err) ++ } ++ value := lab.settledDownlink(t) ++ received += got ++ counted += value ++ diffs = append(diffs, value-got) ++ if value == got { ++ exact++ ++ } ++ } ++ t.Logf("%s: %d aborted downloads, the client was sent %d bytes, the user was counted %d, over-count %d (%.3f%%), per abort %v", ++ p.name, aborts, received, counted, counted-received, float64(counted-received)*100/float64(received), diffs) ++ outliers := 0 ++ for _, diff := range diffs { ++ if diff != 0 { ++ outliers++ ++ } ++ if diff > 64<<10 || diff < -(64<<10) { ++ outliers = aborts ++ } ++ } ++ if outliers > 1 { ++ t.Errorf("%s: %d of %d aborted downloads were not counted exactly (per abort %v), counted %d against %d bytes sent", p.name, aborts-exact, aborts, diffs, counted, received) ++ } ++ } ++} ++ ++func TestSpeedCapChangesRacingAbortedDownloadsKeepTheCountExact(t *testing.T) { ++ lab := startDeliveredLab(t) ++ revision := atomic.Uint64{} ++ setCap := func(down uint64) { ++ setUserSpeeds(t, lab.apiPort, "vless", speedCapOperation(false, 0, speedEntry{email: deliveredUser, down: down, revision: revision.Add(1)})) ++ } ++ setCap(8_000_000) ++ lab.settledDownlink(t) ++ ++ ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second) ++ defer cancel() ++ var received, aborted atomic.Int64 ++ var wg sync.WaitGroup ++ errs := make(chan error, 8) ++ for client := range 3 { ++ wg.Add(1) ++ go func() { ++ defer wg.Done() ++ rng := rand.New(rand.NewSource(int64(client))) ++ for i := 0; ctx.Err() == nil; i++ { ++ p := deliveredProtocols[(client+i)%len(deliveredProtocols)] ++ got, err := abortedDownload(lab, p, int64(60_000+rng.Intn(300_000))) ++ received.Add(got) ++ if err != nil { ++ errs <- fmt.Errorf("client %d %s download %d: %w", client, p.name, i, err) ++ return ++ } ++ aborted.Add(1) ++ } ++ }() ++ } ++ rates := []uint64{4_000_000, 16_000_000, 8_000_000, 30_000_000, 2_000_000} ++ var changes int ++ var counted, previous int64 ++ for ctx.Err() == nil { ++ time.Sleep(250 * time.Millisecond) ++ setCap(rates[changes%len(rates)]) ++ changes++ ++ value := lab.downlink(t, false) ++ if value < previous { ++ t.Errorf("the downlink counter went back from %d to %d", previous, value) ++ } ++ previous = value ++ } ++ wg.Wait() ++ close(errs) ++ for err := range errs { ++ t.Error(err) ++ } ++ counted = lab.settledDownlink(t) ++ diff := counted - received.Load() ++ t.Logf("%d cap changes raced %d aborted downloads: the clients were sent %d bytes, the user was counted %d, difference %d", changes, aborted.Load(), received.Load(), counted, diff) ++ if aborted.Load() < 15 || changes < 20 { ++ t.Fatalf("the race was too thin: %d aborted downloads, %d cap changes", aborted.Load(), changes) ++ } ++ limit := int64(64<<10) * max(2, aborted.Load()/8) ++ if diff > limit || diff < -limit { ++ t.Fatalf("cap changes racing aborted downloads left the count %d bytes away from what the clients were sent (%d counted, %d sent, limit %d)", diff, counted, received.Load(), limit) ++ } ++} diff --git a/testing/scenarios/speedcap_test.go b/testing/scenarios/speedcap_test.go new file mode 100644 index 0000000..60f3963 @@ -3754,3 +4250,408 @@ index 0000000..9034e13 + defer s.mu.Unlock() + return highWater(s.floor, s.records) +} +diff --git a/transport/pipe/delivery.go b/transport/pipe/delivery.go +new file mode 100644 +index 0000000..f16b3e1 +--- /dev/null ++++ b/transport/pipe/delivery.go +@@ -0,0 +1,109 @@ ++package pipe ++ ++import ( ++ "context" ++ "sync" ++ ++ "github.com/xtls/xray-core/common/buf" ++) ++ ++type DeliveryCounter interface { ++ Add(int64) int64 ++} ++ ++type delivery struct { ++ sync.Mutex ++ counter DeliveryCounter ++ pending int64 ++ done bool ++ stop func() bool ++} ++ ++func (r *Reader) CountDelivered(ctx context.Context, counter DeliveryCounter) { ++ d := &delivery{counter: counter} ++ r.delivery = d ++ stop := context.AfterFunc(ctx, func() { ++ d.resolve(r.pipe.drained()) ++ }) ++ d.Lock() ++ d.stop = stop ++ d.Unlock() ++} ++ ++func (r *Reader) observe(mb buf.MultiBuffer, err error) { ++ if r.delivery == nil { ++ return ++ } ++ if err == nil { ++ r.delivery.hold(mb) ++ return ++ } ++ if r.pipe.ended() { ++ r.delivery.finish(true) ++ } ++} ++ ++func (d *delivery) settle() { ++ if d == nil { ++ return ++ } ++ d.Lock() ++ n := d.pending ++ d.pending = 0 ++ d.Unlock() ++ if n > 0 { ++ d.counter.Add(n) ++ } ++} ++ ++func (d *delivery) hold(mb buf.MultiBuffer) { ++ if mb.IsEmpty() { ++ return ++ } ++ d.Lock() ++ defer d.Unlock() ++ if !d.done { ++ d.pending += int64(mb.Len()) ++ } ++} ++ ++func (d *delivery) resolve(count bool) { ++ d.Lock() ++ n := d.pending ++ d.pending = 0 ++ d.Unlock() ++ if count && n > 0 { ++ d.counter.Add(n) ++ } ++} ++ ++func (d *delivery) finish(count bool) { ++ if d == nil { ++ return ++ } ++ d.Lock() ++ n := d.pending ++ d.pending = 0 ++ stop := d.stop ++ d.stop = nil ++ d.done = true ++ d.Unlock() ++ if stop != nil { ++ stop() ++ } ++ if count && n > 0 { ++ d.counter.Add(n) ++ } ++} ++ ++func (p *pipe) drained() bool { ++ p.Lock() ++ defer p.Unlock() ++ return p.state == closed && p.data.IsEmpty() ++} ++ ++func (p *pipe) ended() bool { ++ p.Lock() ++ defer p.Unlock() ++ return p.state == errord || (p.state == closed && p.data.IsEmpty()) ++} +diff --git a/transport/pipe/delivery_test.go b/transport/pipe/delivery_test.go +new file mode 100644 +index 0000000..9acaf21 +--- /dev/null ++++ b/transport/pipe/delivery_test.go +@@ -0,0 +1,246 @@ ++package pipe_test ++ ++import ( ++ "context" ++ "io" ++ "math/rand" ++ "sync" ++ "sync/atomic" ++ "testing" ++ "time" ++ ++ "github.com/xtls/xray-core/common/buf" ++ . "github.com/xtls/xray-core/transport/pipe" ++) ++ ++type deliveredCounter struct { ++ value atomic.Int64 ++} ++ ++func (c *deliveredCounter) Add(n int64) int64 { ++ return c.value.Add(n) ++} ++ ++func batch(size int) buf.MultiBuffer { ++ b := buf.New() ++ b.Extend(int32(size)) ++ return buf.MultiBuffer{b} ++} ++ ++func mustWrite(t *testing.T, w *Writer, size int) { ++ t.Helper() ++ if err := w.WriteMultiBuffer(batch(size)); err != nil { ++ t.Fatal(err) ++ } ++} ++ ++func mustRead(t *testing.T, r *Reader, want int32) { ++ t.Helper() ++ mb, err := r.ReadMultiBuffer() ++ if err != nil { ++ t.Fatal(err) ++ } ++ if mb.Len() != want { ++ t.Fatalf("read %d bytes, want %d", mb.Len(), want) ++ } ++ buf.ReleaseMulti(mb) ++} ++ ++func requireCounted(t *testing.T, c *deliveredCounter, want int64) { ++ t.Helper() ++ if got := c.value.Load(); got != want { ++ t.Fatalf("counted %d delivered bytes, want %d", got, want) ++ } ++} ++ ++func TestABatchIsCountedOnlyWhenTheReaderComesBackForMore(t *testing.T) { ++ reader, writer := New(WithSizeLimit(1 << 20)) ++ counter := &deliveredCounter{} ++ reader.CountDelivered(context.Background(), counter) ++ ++ mustWrite(t, writer, 1000) ++ requireCounted(t, counter, 0) ++ mustRead(t, reader, 1000) ++ requireCounted(t, counter, 0) ++ mustWrite(t, writer, 300) ++ mustRead(t, reader, 300) ++ requireCounted(t, counter, 1000) ++ writer.Close() ++ if _, err := reader.ReadMultiBuffer(); err != io.EOF { ++ t.Fatalf("read after close returned %v, want EOF", err) ++ } ++ requireCounted(t, counter, 1300) ++} ++ ++func TestTheBatchHeldWhenTheReaderIsInterruptedIsNeverCounted(t *testing.T) { ++ reader, writer := New(WithSizeLimit(1 << 20)) ++ counter := &deliveredCounter{} ++ reader.CountDelivered(context.Background(), counter) ++ ++ mustWrite(t, writer, 700) ++ mustRead(t, reader, 700) ++ mustWrite(t, writer, 900) ++ mustRead(t, reader, 900) ++ reader.Interrupt() ++ if _, err := reader.ReadMultiBuffer(); err == nil { ++ t.Fatal("a read after the interrupt returned no error") ++ } ++ requireCounted(t, counter, 700) ++} ++ ++func TestBytesLeftInThePipeAreNeverCounted(t *testing.T) { ++ reader, writer := New(WithSizeLimit(1 << 20)) ++ counter := &deliveredCounter{} ++ ctx, cancel := context.WithCancel(context.Background()) ++ reader.CountDelivered(ctx, counter) ++ ++ mustWrite(t, writer, 400) ++ mustRead(t, reader, 400) ++ mustWrite(t, writer, 5000) ++ reader.Interrupt() ++ cancel() ++ time.Sleep(50 * time.Millisecond) ++ requireCounted(t, counter, 0) ++} ++ ++func TestTheLastBatchOfAFinishedStreamIsCountedWhenItsConnectionEnds(t *testing.T) { ++ reader, writer := New(WithSizeLimit(1 << 20)) ++ counter := &deliveredCounter{} ++ ctx, cancel := context.WithCancel(context.Background()) ++ reader.CountDelivered(ctx, counter) ++ ++ mustWrite(t, writer, 250) ++ writer.Close() ++ mustRead(t, reader, 250) ++ requireCounted(t, counter, 0) ++ cancel() ++ deadline := time.Now().Add(2 * time.Second) ++ for counter.value.Load() != 250 && time.Now().Before(deadline) { ++ time.Sleep(5 * time.Millisecond) ++ } ++ requireCounted(t, counter, 250) ++} ++ ++func TestTheBatchHeldWhenTheConnectionEndsMidStreamIsNeverCounted(t *testing.T) { ++ reader, writer := New(WithSizeLimit(1 << 20)) ++ counter := &deliveredCounter{} ++ ctx, cancel := context.WithCancel(context.Background()) ++ reader.CountDelivered(ctx, counter) ++ ++ mustWrite(t, writer, 250) ++ mustRead(t, reader, 250) ++ cancel() ++ time.Sleep(50 * time.Millisecond) ++ requireCounted(t, counter, 0) ++ mustWrite(t, writer, 10) ++ mustRead(t, reader, 10) ++ mustWrite(t, writer, 20) ++ mustRead(t, reader, 20) ++ requireCounted(t, counter, 10) ++} ++ ++func TestATimedOutReadKeepsCounting(t *testing.T) { ++ reader, writer := New(WithSizeLimit(1 << 20)) ++ counter := &deliveredCounter{} ++ reader.CountDelivered(context.Background(), counter) ++ ++ mustWrite(t, writer, 128) ++ if mb, err := reader.ReadMultiBufferTimeout(time.Second); err != nil || mb.Len() != 128 { ++ t.Fatalf("timed read returned %d bytes, %v", mb.Len(), err) ++ } ++ if _, err := reader.ReadMultiBufferTimeout(20 * time.Millisecond); err != buf.ErrReadTimeout { ++ t.Fatalf("an empty timed read returned %v, want a timeout", err) ++ } ++ requireCounted(t, counter, 128) ++ mustWrite(t, writer, 64) ++ mustRead(t, reader, 64) ++ mustWrite(t, writer, 1) ++ mustRead(t, reader, 1) ++ requireCounted(t, counter, 192) ++} ++ ++func TestAnInjectedErrorDoesNotEndCounting(t *testing.T) { ++ reader, writer := New(WithSizeLimit(1 << 20)) ++ counter := &deliveredCounter{} ++ reader.CountDelivered(context.Background(), counter) ++ ++ mustWrite(t, writer, 100) ++ mustRead(t, reader, 100) ++ reader.ReturnAnError(io.EOF) ++ if _, err := reader.ReadMultiBuffer(); err != io.EOF { ++ t.Fatalf("the injected error came back as %v", err) ++ } ++ reader.Recover() ++ requireCounted(t, counter, 100) ++ mustWrite(t, writer, 30) ++ mustRead(t, reader, 30) ++ mustWrite(t, writer, 5) ++ mustRead(t, reader, 5) ++ requireCounted(t, counter, 130) ++} ++ ++func TestAPipeWithoutACounterReadsAsBefore(t *testing.T) { ++ reader, writer := New(WithSizeLimit(1 << 20)) ++ mustWrite(t, writer, 10) ++ mustRead(t, reader, 10) ++ reader.Interrupt() ++ if _, err := reader.ReadMultiBuffer(); err == nil { ++ t.Fatal("a read after the interrupt returned no error") ++ } ++} ++ ++func TestConcurrentInterruptsAndConnectionEndsCountOnlyBatchesTheReaderCameBackAfter(t *testing.T) { ++ for round := range 300 { ++ reader, writer := New(WithSizeLimit(64 << 10)) ++ counter := &deliveredCounter{} ++ ctx, cancel := context.WithCancel(context.Background()) ++ reader.CountDelivered(ctx, counter) ++ rng := rand.New(rand.NewSource(int64(round))) ++ sizes := rand.New(rand.NewSource(int64(round) + 1_000_000)) ++ stopAfter := time.Duration(rng.Intn(3000)) * time.Microsecond ++ closeWriter := round%3 == 0 ++ ++ var wg sync.WaitGroup ++ wg.Add(3) ++ go func() { ++ defer wg.Done() ++ for { ++ if err := writer.WriteMultiBuffer(batch(1 + sizes.Intn(4000))); err != nil { ++ return ++ } ++ } ++ }() ++ var settled, last int64 ++ go func() { ++ defer wg.Done() ++ for { ++ mb, err := reader.ReadMultiBuffer() ++ if err != nil { ++ return ++ } ++ settled += last ++ last = int64(mb.Len()) ++ buf.ReleaseMulti(mb) ++ } ++ }() ++ go func() { ++ defer wg.Done() ++ time.Sleep(stopAfter) ++ if closeWriter { ++ writer.Close() ++ return ++ } ++ reader.Interrupt() ++ }() ++ wg.Wait() ++ cancel() ++ time.Sleep(time.Millisecond) ++ got := counter.value.Load() ++ if closeWriter && got != settled+last { ++ t.Fatalf("round %d: the stream ended cleanly after %d bytes, counted %d", round, settled+last, got) ++ } ++ if got != settled && got != settled+last { ++ t.Fatalf("round %d: counted %d, the reader came back after %d bytes and held %d more", round, got, settled, last) ++ } ++ } ++} +diff --git a/transport/pipe/reader.go b/transport/pipe/reader.go +index 79f0ac0..d3db3b7 100644 +--- a/transport/pipe/reader.go ++++ b/transport/pipe/reader.go +@@ -8,22 +8,30 @@ import ( + + // Reader is a buf.Reader that reads content from a pipe. + type Reader struct { +- pipe *pipe ++ pipe *pipe ++ delivery *delivery + } + + // ReadMultiBuffer implements buf.Reader. + func (r *Reader) ReadMultiBuffer() (buf.MultiBuffer, error) { +- return r.pipe.ReadMultiBuffer() ++ r.delivery.settle() ++ mb, err := r.pipe.ReadMultiBuffer() ++ r.observe(mb, err) ++ return mb, err + } + + // ReadMultiBufferTimeout reads content from a pipe within the given duration, or returns buf.ErrTimeout otherwise. + func (r *Reader) ReadMultiBufferTimeout(d time.Duration) (buf.MultiBuffer, error) { +- return r.pipe.ReadMultiBufferTimeout(d) ++ r.delivery.settle() ++ mb, err := r.pipe.ReadMultiBufferTimeout(d) ++ r.observe(mb, err) ++ return mb, err + } + + // Interrupt implements common.Interruptible. + func (r *Reader) Interrupt() { + r.pipe.Interrupt() ++ r.delivery.finish(false) + } + + // ReturnAnError makes ReadMultiBuffer return an error, only once. diff --git a/patches/xray-stats-register-race.patch b/patches/xray-stats-register-race.patch index 26c5e2a0..0db44a1d 100644 --- a/patches/xray-stats-register-race.patch +++ b/patches/xray-stats-register-race.patch @@ -7,10 +7,10 @@ that does not exist at the pin are left out (the trackOnlineIP helper, TUN inbou restructured WireGuard client and server), and the pin names the online map field onlineMap. diff --git a/app/dispatcher/default.go b/app/dispatcher/default.go -index e6f8965..5441ff3 100644 +index a8abd7a..50145b9 100644 --- a/app/dispatcher/default.go +++ b/app/dispatcher/default.go -@@ -163,7 +163,7 @@ func (d *DefaultDispatcher) getLink(ctx context.Context) (*transport.Link, *tran +@@ -166,7 +166,7 @@ func (d *DefaultDispatcher) getLink(ctx context.Context) (*transport.Link, *tran p := d.policy.ForLevel(user.Level) if p.Stats.UserUplink { name := "user>>>" + user.Email + ">>>traffic>>>uplink" @@ -19,16 +19,15 @@ index e6f8965..5441ff3 100644 inboundLink.Writer = &SizeStatWriter{ Counter: c, Writer: inboundLink.Writer, -@@ -172,7 +172,7 @@ func (d *DefaultDispatcher) getLink(ctx context.Context) (*transport.Link, *tran +@@ -175,14 +175,14 @@ func (d *DefaultDispatcher) getLink(ctx context.Context) (*transport.Link, *tran } if p.Stats.UserDownlink { name := "user>>>" + user.Email + ">>>traffic>>>downlink" - if c, _ := stats.GetOrRegisterCounter(d.stats, name); c != nil { + if c, _ := d.stats.GetOrRegisterCounter(name); c != nil { - outboundLink.Writer = &SizeStatWriter{ - Counter: c, - Writer: outboundLink.Writer, -@@ -182,7 +182,7 @@ func (d *DefaultDispatcher) getLink(ctx context.Context) (*transport.Link, *tran + downlinkReader.CountDelivered(ctx, c) + } + } if p.Stats.UserOnline { name := "user>>>" + user.Email + ">>>online" @@ -37,7 +36,7 @@ index e6f8965..5441ff3 100644 userIP := sessionInbound.Source.Address.String() om.AddIP(userIP) context.AfterFunc(ctx, func() { om.RemoveIP(userIP) }) -@@ -206,13 +206,13 @@ func WrapLink(ctx context.Context, policyManager policy.Manager, statsManager st +@@ -210,13 +210,13 @@ func WrapLink(ctx context.Context, policyManager policy.Manager, statsManager st p := policyManager.ForLevel(user.Level) if p.Stats.UserUplink { name := "user>>>" + user.Email + ">>>traffic>>>uplink" @@ -51,9 +50,9 @@ index e6f8965..5441ff3 100644 - if c, _ := stats.GetOrRegisterCounter(statsManager, name); c != nil { + if c, _ := statsManager.GetOrRegisterCounter(name); c != nil { link.Writer = &SizeStatWriter{ - Counter: c, - Writer: link.Writer, -@@ -221,7 +221,7 @@ func WrapLink(ctx context.Context, policyManager policy.Manager, statsManager st + Counter: c, + Writer: link.Writer, +@@ -226,7 +226,7 @@ func WrapLink(ctx context.Context, policyManager policy.Manager, statsManager st } if p.Stats.UserOnline { name := "user>>>" + user.Email + ">>>online" From 5f333defabf8528504f056f21f89d57e00ff09c7 Mon Sep 17 00:00:00 2001 From: Free-Guy-IR Date: Thu, 3 Dec 2026 06:24:14 +0330 Subject: [PATCH 2/4] chore: report 0.6.30 NodeVersion goes 0.6.29 to 0.6.30, one patch step from the highest 0.6 value on any branch of the fork on GitHub (0.6.29 on main, feat/003-speed-cap and ci-003-speed-cap; checked on 2026-12-03), for the node whose core counts a user's download when the client side takes it. TestNodeVersionIsPinned failed against the 0.6.29 constant and passes after the bump. The three upstream-waiver rows that cite the constant follow. --- .github/upstream-waivers.txt | 6 +++--- controller/base_info_test.go | 4 ++-- controller/controller.go | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/upstream-waivers.txt b/.github/upstream-waivers.txt index 66cc76af..778768c4 100644 --- a/.github/upstream-waivers.txt +++ b/.github/upstream-waivers.txt @@ -29,13 +29,13 @@ fa79e3b565d6d482aca2a3f44ed2cd4275905b44 rejected: upstream PR #61 (branch pr-61 fbb0110881cb03804dded5b7778b78dbb67da72d rejected: upstream merge of origin/dev into feat/mtproto-telemt on the open, not merged PR #61 branch pr-61, whose conflict resolution carries changes of its own; PR #61 adds a telemt MTProto backend, the Telegram proxy, and the owner ordered the Telegram proxy out of the fork on 2026-11-10 (641d19c1) and confirmed on 2026-12-02 that it stays out; on the wire it would also take BackendType MTPROTO = 2, reserved by number and by name in the fork since it removed SING_BOX; if upstream merges it, review it only for changes outside the MTProto backend branch:pr-61 7be885ff5410ac7fdb92fa21cf7901a416be5f05 superseded: upstream #86 makes xray Core.Started() take c.mu; the fork closed the same race lock-free in cc27180 (Started reads an atomic coreState snapshot, liveness from waitDone), because c.mu in Started puts every REST/gRPC request behind Stop's kill and 5 s wait (docs/upstream-parity.md); upstream's TestCoreStarted tests and their -race CI step are carried in backend/xray/core_started_test.go d359a8f7c478044c0fb80afcda207c6d122affd5 not-applicable: upstream #117 only makes StartOrAttach restart an unhealthy backend instead of treating a same-config Start as a heartbeat; the fork does not carry StartOrAttach (see ca24af0b, rejected) and every fork Start runs ReplaceBackend (controller/rpc/base.go), so an unhealthy backend is always restarted -47857d43fe777f30f9ecc5f2ffe4ca0b037507cb not-applicable: upstream v0.5.5 release commit, whose only change sets controller.NodeVersion to 0.5.5; the fork versions its node on its own line (NodeVersion 0.6.29, pinned by TestNodeVersionIsPinned) and must not report an upstream version, and every v0.5.5 change is tracked here commit by commit +47857d43fe777f30f9ecc5f2ffe4ca0b037507cb not-applicable: upstream v0.5.5 release commit, whose only change sets controller.NodeVersion to 0.5.5; the fork versions its node on its own line (NodeVersion 0.6.30, pinned by TestNodeVersionIsPinned) and must not report an upstream version, and every v0.5.5 change is tracked here commit by commit 88d5e75db62190d8566caf826536c801465c1482 superseded: upstream #96 (released in node v0.5.6, 675bdaa) is ported from the node v0.5.7 (739eab94) end state by the fork commit "feat(xray): masque inbound on proto field 12": message Masque { string pass = 1; } byte-identical, MasqueAccount/NewMasqueAccount (empty pass skips the user), the masque inbound cases in config.go, user.go and config_clone.go, and the masque_test.go and api/masque_test.go tests; the Proxy field is masque = 12, not 7, because the fork Proxy already uses 7 for Hysteria2 and 8 to 11 for OpenVPN, the reserved MTProto slot, TUIC and L2TP (common/masque_wire_test.go pins the wire tag 0x62); built on xray-core 676eaf66f8f0 243b818307790393d21b41154c99b0d052e89a59 superseded: pre-squash commit (feat: add Masque proxy support) of upstream PR #96 on branch masque, squash-merged as 88d5e75 (released in node v0.5.6, 675bdaa), which the fork ports from the node v0.5.7 end state in its commit feat(xray): masque inbound on proto field 12, with masque = 12 instead of 7 (see the 88d5e75 row) branch:masque f0877ce629e84aae6099e9bf5c6f47837dff78a8 superseded: pre-squash commit (feat(xray): upgrade to v26.9.30 prerelease and use native MASQUE accounts) of upstream PR #96 on branch masque, squash-merged as 88d5e75; the node agent compiles against its go.mod pin xray-core 676eaf66f8f0 (the v26.11.9 release tag commit), which carries the native MASQUE accounts, while the image's xray binary is held on v26.3.27 (d2758a023cd7), which has no proxy/masque, and ports the #96 end state in feat(xray): masque inbound on proto field 12 (see the 88d5e75 row) branch:masque b7442879ef0f67b692474e0e668d65f29df8de49 superseded: merge of dev into branch masque (parents f0877ce and 3a3d5c5) inside upstream PR #96, squash-merged as 88d5e75; it brings no content beyond dev and the masque commits, which are tracked on their own rows and through 88d5e75 branch:masque -675bdaa24a3a67847f2094e518f1ae4d8460aa01 not-applicable: upstream v0.5.6 release commit, whose only change sets controller.NodeVersion to 0.5.6; the fork versions its node on its own line (NodeVersion 0.6.29, pinned by TestNodeVersionIsPinned) and must not report an upstream version, and every v0.5.6 change is tracked here commit by commit -739eab94a9343d9f0035baf7162796844109f4c4 not-applicable: upstream v0.5.7 release commit, whose only change sets controller.NodeVersion to 0.5.7; the fork versions its node on its own line (NodeVersion 0.6.29, pinned by TestNodeVersionIsPinned) and must not report an upstream version, and every v0.5.7 change is tracked here commit by commit +675bdaa24a3a67847f2094e518f1ae4d8460aa01 not-applicable: upstream v0.5.6 release commit, whose only change sets controller.NodeVersion to 0.5.6; the fork versions its node on its own line (NodeVersion 0.6.30, pinned by TestNodeVersionIsPinned) and must not report an upstream version, and every v0.5.6 change is tracked here commit by commit +739eab94a9343d9f0035baf7162796844109f4c4 not-applicable: upstream v0.5.7 release commit, whose only change sets controller.NodeVersion to 0.5.7; the fork versions its node on its own line (NodeVersion 0.6.30, pinned by TestNodeVersionIsPinned) and must not report an upstream version, and every v0.5.7 change is tracked here commit by commit ebb0d02944bdf4f7166819d31466a224f0daf7e2 superseded: upstream commit of 2026-11-02, released in node v0.5.7 (739eab9, 2026-11-03), for the Ubuntu 26.04 AppArmor wg profile that makes wg set ... private-key fail with fopen: Permission denied on a key file under /tmp in the WireGuard E2E tests; the fork fixed the same failure on 2026-10-29 in b8679894 (on main), which writes the E2E client key with os.CreateTemp under /etc/wireguard, the one key path that profile allows, and with it TestIntegrationE2ESyncUser, TestIntegrationE2ESyncUsers and TestIntegrationE2EUpdateUsers pass on ubuntu-latest (wireguard-integration job 123832855477 on b8679894, no Permission denied in its log); upstream's key-file half is the same change, its chmod 0600 is already the os.CreateTemp mode, and its fallback to the default temp dir would hit the same denial; its other half, unloading the wg and wg-quick AppArmor profiles with apparmor_parser -R and aa-disable from TestMain and from the install_wg Makefile target, is not taken: it weakens the host's AppArmor confinement from a test binary and a package installer, and the fork's fix needs none of it 36dc7a4a78a075d20ed6c82297c8097fd2a6462f not-applicable: removes the .gitlab-ci.yml that upstream #64 (e03754d) added for the contributor's own GitLab pipeline; the fork ported #64 on 2026-11-10 in c755202a without that file, and no commit on main has ever added a .gitlab-ci.yml (git log origin/main -- .gitlab-ci.yml is empty on 2026-11-11), so there is nothing to delete 689f2665e2157c93d1ee65cb6426d4684a53056a pending: dev-only: upstream #120 adds a telemt MTProto backend, the Telegram proxy, in no upstream tag yet (newest tag v0.5.7, 739eab9, checked 2026-12-02); the owner ordered the Telegram proxy out of the fork on 2026-11-10 (641d19c1) and confirmed on 2026-12-02 that it stays out, so the backend itself is never ported, and on the wire it would also take BackendType 2 and Proxy 8, which the fork keeps reserved and uses for open_vpn; the same commit adds a generic retry-later sync error (backend/errors.go RetryLaterError, answered as HTTP 503 by controller/rest/sync_errors.go and as gRPC Unavailable by controller/rpc/sync_errors.go), which is ported or refused on its own once a release contains it until:2026-12-31 diff --git a/controller/base_info_test.go b/controller/base_info_test.go index ec05b280..7bb33c74 100644 --- a/controller/base_info_test.go +++ b/controller/base_info_test.go @@ -77,7 +77,7 @@ func TestBaseInfoResponseWithoutDegradation(t *testing.T) { } func TestNodeVersionIsPinned(t *testing.T) { - if NodeVersion != "0.6.29" { - t.Fatalf("NodeVersion = %q, want %q", NodeVersion, "0.6.29") + if NodeVersion != "0.6.30" { + t.Fatalf("NodeVersion = %q, want %q", NodeVersion, "0.6.30") } } diff --git a/controller/controller.go b/controller/controller.go index ef8f2f6c..944d84e6 100644 --- a/controller/controller.go +++ b/controller/controller.go @@ -21,7 +21,7 @@ import ( "github.com/pasarguard/node/pkg/sysstats" ) -const NodeVersion = "0.6.29" +const NodeVersion = "0.6.30" const keepAliveGrace = 5 * time.Second From 03ac8fe7ffc57b132d083de74ab14279ff4a0a8e Mon Sep 17 00:00:00 2001 From: Free-Guy-IR Date: Thu, 3 Dec 2026 07:56:04 +0330 Subject: [PATCH 3/4] fix(speedcap): count a delivered batch whenever the inbound reads again 2e4c3db6 dropped the batch an inbound held when the inbound interrupted the downlink pipe, and counted a held batch at the end of the connection only if the stream had finished and the pipe was empty. Both rules lost bytes that had reached the client: - a client that resets right after the last byte makes the inbound interrupt the pipe before its copy loop reads again, so the last delivered batch was never counted (Linux, 600 Trojan downloads of 300,000 bytes: 170,414,400 counted for 180,000,000 received); - a plain HTTP proxy stops reading after the response, so its last batch waited for an origin that keeps its connection open (Linux, 8 responses of 20,082 bytes: 120,492 counted for 160,656). Now a batch the inbound took from the pipe is counted when the inbound enters its next read, whatever happened in between, and is never counted if the inbound does not come back after it (its write failed). Interrupt is the upstream one again and the pipe keeps no context hook. The plain HTTP handler settles the batch it holds after it wrote the response. Linux, throwaway container, scenario test binary from this tree: - 0.6.29 core: the capped abort test over-counted 65,536 bytes on each VLESS abort and between 65,536 and 1,245,184 bytes on each Trojan abort (3,932,160 bytes, 74.4%, over 8 aborts); the reset-after-last-byte and plain HTTP tests counted exactly. - 2e4c3db6: the abort tests counted exactly; the two new tests lost the bytes above. - this commit: all four tests count to the byte. The 65,536 bytes per abort in 2e4c3db6's message are the smallest over-count seen on the 0.6.29 core, not the only one. --- Dockerfile | 7 +- Makefile | 2 +- patches/xray-per-user-speed-cap.patch | 547 ++++++++++++++++--------- patches/xray-stats-register-race.patch | 4 +- 4 files changed, 367 insertions(+), 193 deletions(-) diff --git a/Dockerfile b/Dockerfile index 6004368c..65c4a674 100644 --- a/Dockerfile +++ b/Dockerfile @@ -145,13 +145,14 @@ RUN git init -q . \ && grep -qF "link.Writer = speedcap.NewWriter(ctx, user.Email, sessionInbound.Tag, speedcap.Downlink, link.Writer)" app/dispatcher/default.go \ && grep -qF "var splice = inbound.CanSpliceCopy == 1 && !speedcap.CappedUser(inbound.User, inbound.Tag)" proxy/proxy.go \ && grep -qF "w, capped, err := spliceUntilCapped(tc, readerConn, inbound)" proxy/proxy.go \ - && grep -qF "downlinkReader.CountDelivered(ctx, c)" app/dispatcher/default.go \ + && grep -qF "downlinkReader.CountDelivered(c)" app/dispatcher/default.go \ && ! grep -qF "Writer: outboundLink.Writer," app/dispatcher/default.go \ && grep -qF "CountWritten: true," app/dispatcher/default.go \ && grep -qF "CountWritten bool" app/dispatcher/stats.go \ - && grep -qF "func (r *Reader) CountDelivered(ctx context.Context, counter DeliveryCounter) {" transport/pipe/delivery.go \ + && grep -qF "func (r *Reader) CountDelivered(counter DeliveryCounter) {" transport/pipe/delivery.go \ && test "$(grep -c 'r.delivery.settle()' transport/pipe/reader.go)" = "2" \ - && grep -qF "r.delivery.finish(false)" transport/pipe/reader.go \ + && test "$(grep -c 'r.delivery.hold(mb)' transport/pipe/reader.go)" = "2" \ + && grep -qF "delivered.SettleDelivered()" proxy/http/server.go \ && git apply --verbose /patches/xray-pinned-ca-servername.patch \ && grep -qF 'return errors.New("Pinning CA needs a valid ServerName")' transport/internet/tls/config.go \ && grep -qF "config := tlsConfig.GetTLSConfig(tls.WithDestination(dest))" transport/internet/grpc/dial.go \ diff --git a/Makefile b/Makefile index d9922284..e42d93ec 100644 --- a/Makefile +++ b/Makefile @@ -289,7 +289,7 @@ test_xray_patches: cd "$(XRAY_SRC)" && CGO_ENABLED=1 GOTOOLCHAIN=local $(GO_TEST_VISIBLE) -race -count=1 -timeout 600s ./app/proxyman/speedcap/... cd "$(XRAY_SRC)" && CGO_ENABLED=1 GOTOOLCHAIN=local $(GO_TEST_VISIBLE) -race -count=1 -run 'TestWrapLinkCapsTheUserAndKeepsTheStatsWriterOutermost|TestADispatchedDownlinkCountsOnlyWhatTheInboundCameBackForMoreAfter|TestALinkedDownlinkCountsOnlyWhatTheClientWriterTook' ./app/dispatcher/ cd "$(XRAY_SRC)" && CGO_ENABLED=1 GOTOOLCHAIN=local $(GO_TEST_VISIBLE) -race -count=3 ./transport/pipe/ - cd "$(XRAY_SRC)" && CGO_ENABLED=1 GOTOOLCHAIN=local $(GO_TEST_VISIBLE) -race -count=1 -timeout 900s -run 'TestSpeedCap' ./testing/scenarios/ + cd "$(XRAY_SRC)" && CGO_ENABLED=1 GOTOOLCHAIN=local $(GO_TEST_VISIBLE) -race -count=1 -timeout 900s -run 'TestSpeedCap|TestUserDownlinkCounts' ./testing/scenarios/ install_wg: update_os ifeq ($(UNAME_S),Linux) diff --git a/patches/xray-per-user-speed-cap.patch b/patches/xray-per-user-speed-cap.patch index 43384400..7552b95e 100644 --- a/patches/xray-per-user-speed-cap.patch +++ b/patches/xray-per-user-speed-cap.patch @@ -1,5 +1,5 @@ diff --git a/app/dispatcher/default.go b/app/dispatcher/default.go -index e6f8965..a8abd7a 100644 +index e6f8965..781d886 100644 --- a/app/dispatcher/default.go +++ b/app/dispatcher/default.go @@ -7,6 +7,7 @@ import ( @@ -27,7 +27,7 @@ index e6f8965..a8abd7a 100644 - Counter: c, - Writer: outboundLink.Writer, - } -+ downlinkReader.CountDelivered(ctx, c) ++ downlinkReader.CountDelivered(c) } } @@ -56,10 +56,10 @@ index e6f8965..a8abd7a 100644 } diff --git a/app/dispatcher/delivered_test.go b/app/dispatcher/delivered_test.go new file mode 100644 -index 0000000..f375872 +index 0000000..173beb9 --- /dev/null +++ b/app/dispatcher/delivered_test.go -@@ -0,0 +1,131 @@ +@@ -0,0 +1,137 @@ +package dispatcher + +import ( @@ -158,6 +158,12 @@ index 0000000..f375872 + if got := counted(t, manager, "downlink"); got != 3000 { + t.Fatalf("the downlink counter holds %d after the inbound gave up, want 3000", got) + } ++ if _, err := inbound.Reader.ReadMultiBuffer(); err == nil { ++ t.Fatal("a read after the interrupt returned no error") ++ } ++ if got := counted(t, manager, "downlink"); got != 3500 { ++ t.Fatalf("the downlink counter holds %d after the inbound came back from delivering 500 more, want 3500", got) ++ } + + if err := inbound.Writer.WriteMultiBuffer(bytesOf(700)); err != nil && !errors.Is(err, context.Canceled) { + t.Fatal(err) @@ -2591,6 +2597,20 @@ index 0000000..47bdfc5 + t.Fatalf("an equal tombstone with other tags was not a no-op: %+v", result) + } +} +diff --git a/proxy/http/server.go b/proxy/http/server.go +index 0deecad..fa8327d 100644 +--- a/proxy/http/server.go ++++ b/proxy/http/server.go +@@ -299,6 +299,9 @@ func (s *Server) handlePlainHTTP(ctx context.Context, request *http.Request, wri + if err := response.Write(writer); err != nil { + return errors.New("failed to write response").Base(err).AtWarning() + } ++ if delivered, ok := link.Reader.(interface{ SettleDelivered() }); ok { ++ delivered.SettleDelivered() ++ } + return nil + } + diff --git a/proxy/proxy.go b/proxy/proxy.go index dbd81d6..bbc7ae1 100644 --- a/proxy/proxy.go @@ -2657,27 +2677,36 @@ index dbd81d6..bbc7ae1 100644 if err := buf.Copy(reader, writer, buf.UpdateActivity(timer), buf.AddToStatCounter(readCounter)); err != nil { diff --git a/testing/scenarios/speedcap_delivered_test.go b/testing/scenarios/speedcap_delivered_test.go new file mode 100644 -index 0000000..a625589 +index 0000000..a16f7fd --- /dev/null +++ b/testing/scenarios/speedcap_delivered_test.go -@@ -0,0 +1,298 @@ +@@ -0,0 +1,528 @@ ++//go:build linux || darwin ++ +package scenarios + +import ( ++ "bufio" + "context" + "crypto/sha256" ++ "encoding/base64" + "encoding/binary" + "encoding/hex" + "errors" + "fmt" ++ "io" + "math/rand" + gonet "net" ++ "net/http" ++ "strings" + "sync" + "sync/atomic" ++ "syscall" + "testing" + "time" + + "github.com/xtls/xray-core/app/commander" ++ "github.com/xtls/xray-core/app/policy" + "github.com/xtls/xray-core/app/proxyman/command" + "github.com/xtls/xray-core/app/router" + "github.com/xtls/xray-core/app/stats" @@ -2687,6 +2716,7 @@ index 0000000..a625589 + "github.com/xtls/xray-core/common/serial" + "github.com/xtls/xray-core/common/uuid" + core "github.com/xtls/xray-core/core" ++ httpproxy "github.com/xtls/xray-core/proxy/http" + "github.com/xtls/xray-core/proxy/trojan" + "github.com/xtls/xray-core/proxy/vless" + vlessinbound "github.com/xtls/xray-core/proxy/vless/inbound" @@ -2707,30 +2737,63 @@ index 0000000..a625589 + stats statscmd.StatsServiceClient +} + ++func deliveredApps(level *policy.Policy) []*serial.TypedMessage { ++ return []*serial.TypedMessage{ ++ serial.ToTypedMessage(&commander.Config{ ++ Tag: "api", ++ Service: []*serial.TypedMessage{serial.ToTypedMessage(&command.Config{}), serial.ToTypedMessage(&statscmd.Config{})}, ++ }), ++ serial.ToTypedMessage(&stats.Config{}), ++ serial.ToTypedMessage(&router.Config{Rule: []*router.RoutingRule{{ ++ InboundTag: []string{"api"}, ++ TargetTag: &router.RoutingRule_Tag{Tag: "api"}, ++ }}}), ++ serial.ToTypedMessage(&policy.Config{Level: map[uint32]*policy.Policy{0: level}}), ++ } ++} ++ ++func immediatePolicy() *policy.Policy { ++ return &policy.Policy{ ++ Timeout: &policy.Policy_Timeout{UplinkOnly: &policy.Second{Value: 0}, DownlinkOnly: &policy.Second{Value: 0}}, ++ Stats: &policy.Policy_Stats{UserUplink: true, UserDownlink: true}, ++ } ++} ++ ++func lingeringPolicy() *policy.Policy { ++ return &policy.Policy{ ++ Timeout: &policy.Policy_Timeout{UplinkOnly: &policy.Second{Value: 2}, DownlinkOnly: &policy.Second{Value: 2}}, ++ Stats: &policy.Policy_Stats{UserUplink: true, UserDownlink: true}, ++ } ++} ++ ++func dialStats(t *testing.T, apiPort net.Port) statscmd.StatsServiceClient { ++ t.Helper() ++ conn, err := grpc.NewClient(fmt.Sprintf("127.0.0.1:%d", apiPort), grpc.WithTransportCredentials(insecure.NewCredentials())) ++ if err != nil { ++ t.Fatal(err) ++ } ++ t.Cleanup(func() { conn.Close() }) ++ return statscmd.NewStatsServiceClient(conn) ++} ++ +func startDeliveredLab(t *testing.T) *deliveredLab { + t.Helper() ++ return startDeliveredLabFor(t, startStreamServer(t, nil), immediatePolicy()) ++} ++ ++func startDeliveredLabFor(t *testing.T, target streamTarget, level *policy.Policy) *deliveredLab { ++ t.Helper() + secret := uuid.New() + lab := &deliveredLab{ + apiPort: tcp.PickPort(), -+ target: startStreamServer(t, nil), ++ target: target, + vlessPort: tcp.PickPort(), + trojanPort: tcp.PickPort(), + vlessID: uuid.New(), + trojanKey: "delivered-" + secret.String(), + } + server := &core.Config{ -+ App: []*serial.TypedMessage{ -+ serial.ToTypedMessage(&commander.Config{ -+ Tag: "api", -+ Service: []*serial.TypedMessage{serial.ToTypedMessage(&command.Config{}), serial.ToTypedMessage(&statscmd.Config{})}, -+ }), -+ serial.ToTypedMessage(&stats.Config{}), -+ serial.ToTypedMessage(&router.Config{Rule: []*router.RoutingRule{{ -+ InboundTag: []string{"api"}, -+ TargetTag: &router.RoutingRule_Tag{Tag: "api"}, -+ }}}), -+ speedCapPolicy(), -+ }, ++ App: deliveredApps(level), + Inbound: []*core.InboundHandlerConfig{ + apiInbound("api", lab.apiPort), + { @@ -2753,32 +2816,25 @@ index 0000000..a625589 + } + startCapturedXray(t, server) + waitListening(t, lab.apiPort, lab.vlessPort, lab.trojanPort) -+ conn, err := grpc.NewClient(fmt.Sprintf("127.0.0.1:%d", lab.apiPort), grpc.WithTransportCredentials(insecure.NewCredentials())) -+ if err != nil { -+ t.Fatal(err) -+ } -+ t.Cleanup(func() { conn.Close() }) -+ lab.stats = statscmd.NewStatsServiceClient(conn) ++ lab.stats = dialStats(t, lab.apiPort) + return lab +} + -+func (lab *deliveredLab) downlink(t *testing.T, reset bool) int64 { -+ t.Helper() ++func userDownlink(stats statscmd.StatsServiceClient, user string, reset bool) int64 { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() -+ response, err := lab.stats.GetStats(ctx, &statscmd.GetStatsRequest{Name: "user>>>" + deliveredUser + ">>>traffic>>>downlink", Reset_: reset}) ++ response, err := stats.GetStats(ctx, &statscmd.GetStatsRequest{Name: "user>>>" + user + ">>>traffic>>>downlink", Reset_: reset}) + if err != nil { + return 0 + } + return response.GetStat().GetValue() +} + -+func (lab *deliveredLab) settledDownlink(t *testing.T) int64 { -+ t.Helper() -+ last, stableSince := lab.downlink(t, false), time.Now() ++func settledUserDownlink(stats statscmd.StatsServiceClient, user string) int64 { ++ last, stableSince := userDownlink(stats, user, false), time.Now() + for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline); { + time.Sleep(50 * time.Millisecond) -+ if value := lab.downlink(t, false); value != last { ++ if value := userDownlink(stats, user, false); value != last { + last, stableSince = value, time.Now() + continue + } @@ -2786,7 +2842,35 @@ index 0000000..a625589 + break + } + } -+ return lab.downlink(t, true) ++ return userDownlink(stats, user, true) ++} ++ ++func (lab *deliveredLab) downlink(t *testing.T, reset bool) int64 { ++ t.Helper() ++ return userDownlink(lab.stats, deliveredUser, reset) ++} ++ ++func (lab *deliveredLab) settledDownlink(t *testing.T) int64 { ++ t.Helper() ++ return settledUserDownlink(lab.stats, deliveredUser) ++} ++ ++func drainNow(conn *gonet.TCPConn, buffer []byte) int64 { ++ raw, err := conn.SyscallConn() ++ if err != nil { ++ return 0 ++ } ++ var drained int64 ++ raw.Read(func(fd uintptr) bool { ++ for { ++ n, err := syscall.Read(int(fd), buffer) ++ if n <= 0 || err != nil { ++ return true ++ } ++ drained += int64(n) ++ } ++ }) ++ return drained +} + +type deliveredProtocol struct { @@ -2849,7 +2933,7 @@ index 0000000..a625589 + if err != nil { + var timeout gonet.Error + if errors.As(err, &timeout) && timeout.Timeout() { -+ return received - p.header, nil ++ return received + drainNow(tcpConn, buffer) - p.header, nil + } + return received - p.header, err + } @@ -2959,6 +3043,172 @@ index 0000000..a625589 + t.Fatalf("cap changes racing aborted downloads left the count %d bytes away from what the clients were sent (%d counted, %d sent, limit %d)", diff, counted, received.Load(), limit) + } +} ++ ++func startFiniteTarget(t *testing.T, size int) streamTarget { ++ t.Helper() ++ ip := targetHostAddress(t) ++ listener, err := gonet.Listen("tcp4", gonet.JoinHostPort(ip.String(), "0")) ++ if err != nil { ++ t.Fatal(err) ++ } ++ t.Cleanup(func() { listener.Close() }) ++ payload := make([]byte, size) ++ go func() { ++ for { ++ conn, err := listener.Accept() ++ if err != nil { ++ return ++ } ++ go func() { ++ defer conn.Close() ++ conn.Write(payload) ++ }() ++ } ++ }() ++ return streamTarget{ip: ip, port: net.Port(listener.Addr().(*gonet.TCPAddr).Port)} ++} ++ ++func resetAfterTheLastByte(lab *deliveredLab, p deliveredProtocol, size int64, buffer []byte) (int64, error) { ++ conn, err := (&gonet.Dialer{Timeout: 5 * time.Second}).Dial("tcp4", fmt.Sprintf("127.0.0.1:%d", p.port(lab))) ++ if err != nil { ++ return 0, err ++ } ++ tcpConn := conn.(*gonet.TCPConn) ++ defer func() { ++ tcpConn.SetLinger(0) ++ tcpConn.Close() ++ }() ++ if _, err := tcpConn.Write(p.request(lab)); err != nil { ++ return 0, err ++ } ++ tcpConn.SetReadDeadline(time.Now().Add(20 * time.Second)) ++ var received int64 ++ for received < size+p.header { ++ n, err := tcpConn.Read(buffer[:min(int64(len(buffer)), size+p.header-received)]) ++ received += int64(n) ++ if err != nil { ++ return received - p.header, err ++ } ++ } ++ return received - p.header, nil ++} ++ ++func TestUserDownlinkCountsADownloadResetRightAfterItsLastByte(t *testing.T) { ++ const size = 300_000 ++ lab := startDeliveredLabFor(t, startFiniteTarget(t, size), lingeringPolicy()) ++ lab.settledDownlink(t) ++ const workers, downloads = 6, 100 ++ for _, p := range deliveredProtocols { ++ var received, failed atomic.Int64 ++ var wg sync.WaitGroup ++ for range workers { ++ wg.Add(1) ++ go func() { ++ defer wg.Done() ++ buffer := make([]byte, 64<<10) ++ for range downloads { ++ got, err := resetAfterTheLastByte(lab, p, size, buffer) ++ received.Add(got) ++ if err != nil { ++ failed.Add(1) ++ } ++ } ++ }() ++ } ++ wg.Wait() ++ counted := lab.settledDownlink(t) ++ t.Logf("%s: %d downloads of %d bytes reset right after their last byte, the clients got %d bytes, the user was counted %d, difference %d", p.name, workers*downloads, size, received.Load(), counted, counted-received.Load()) ++ if failed.Load() != 0 { ++ t.Errorf("%s: %d downloads did not get all %d bytes", p.name, failed.Load(), size) ++ } ++ if counted != received.Load() { ++ t.Errorf("%s: the user was counted %d bytes for %d bytes the clients got", p.name, counted, received.Load()) ++ } ++ } ++} ++ ++func startLingeringHTTPOrigin(t *testing.T, body int, linger time.Duration) (streamTarget, int64) { ++ t.Helper() ++ ip := targetHostAddress(t) ++ listener, err := gonet.Listen("tcp4", gonet.JoinHostPort(ip.String(), "0")) ++ if err != nil { ++ t.Fatal(err) ++ } ++ t.Cleanup(func() { listener.Close() }) ++ response := []byte(fmt.Sprintf("HTTP/1.1 200 OK\r\nContent-Length: %d\r\nContent-Type: application/octet-stream\r\n\r\n", body) + strings.Repeat("r", body)) ++ go func() { ++ for { ++ conn, err := listener.Accept() ++ if err != nil { ++ return ++ } ++ go func() { ++ defer conn.Close() ++ reader := bufio.NewReader(conn) ++ for { ++ line, err := reader.ReadString('\n') ++ if err != nil { ++ return ++ } ++ if line == "\r\n" { ++ break ++ } ++ } ++ conn.Write(response) ++ time.Sleep(linger) ++ }() ++ } ++ }() ++ return streamTarget{ip: ip, port: net.Port(listener.Addr().(*gonet.TCPAddr).Port)}, int64(len(response)) ++} ++ ++func TestUserDownlinkCountsEveryPlainHTTPResponseItDelivered(t *testing.T) { ++ const body = 20_000 ++ origin, responseSize := startLingeringHTTPOrigin(t, body, 300*time.Millisecond) ++ apiPort, httpPort := tcp.PickPort(), tcp.PickPort() ++ server := &core.Config{ ++ App: deliveredApps(lingeringPolicy()), ++ Inbound: []*core.InboundHandlerConfig{ ++ apiInbound("api", apiPort), ++ { ++ Tag: "http", ++ ReceiverSettings: listenOn(httpPort, nil), ++ ProxySettings: serial.ToTypedMessage(&httpproxy.ServerConfig{Accounts: map[string]string{deliveredUser: "delivered-http"}}), ++ }, ++ }, ++ Outbound: []*core.OutboundHandlerConfig{allowingFreedom(origin)}, ++ } ++ startCapturedXray(t, server) ++ waitListening(t, apiPort, httpPort) ++ stats := dialStats(t, apiPort) ++ settledUserDownlink(stats, deliveredUser) ++ auth := base64.StdEncoding.EncodeToString([]byte(deliveredUser + ":delivered-http")) ++ ++ const requests = 8 ++ var counted int64 ++ for i := range requests { ++ conn, err := (&gonet.Dialer{Timeout: 5 * time.Second}).Dial("tcp4", fmt.Sprintf("127.0.0.1:%d", httpPort)) ++ if err != nil { ++ t.Fatal(err) ++ } ++ conn.SetDeadline(time.Now().Add(10 * time.Second)) ++ fmt.Fprintf(conn, "GET http://%s:%d/file HTTP/1.1\r\nHost: %s:%d\r\nProxy-Authorization: Basic %s\r\n\r\n", origin.ip, origin.port, origin.ip, origin.port, auth) ++ response, err := http.ReadResponse(bufio.NewReader(conn), nil) ++ if err != nil { ++ t.Fatalf("request %d: %v", i, err) ++ } ++ got, err := io.Copy(io.Discard, response.Body) ++ if err != nil || got != body { ++ t.Fatalf("request %d: the client got %d body bytes, %v", i, got, err) ++ } ++ conn.Close() ++ counted += settledUserDownlink(stats, deliveredUser) ++ } ++ t.Logf("%d plain HTTP responses of %d bytes from an origin that keeps its connection 300 ms after each: the user was counted %d of %d", requests, responseSize, counted, responseSize*requests) ++ if counted != responseSize*requests { ++ t.Fatalf("the user was counted %d bytes for %d plain HTTP responses of %d bytes", counted, requests, responseSize) ++ } ++} diff --git a/testing/scenarios/speedcap_test.go b/testing/scenarios/speedcap_test.go new file mode 100644 index 0000000..60f3963 @@ -4252,15 +4502,14 @@ index 0000000..9034e13 +} diff --git a/transport/pipe/delivery.go b/transport/pipe/delivery.go new file mode 100644 -index 0000000..f16b3e1 +index 0000000..4159d5e --- /dev/null +++ b/transport/pipe/delivery.go -@@ -0,0 +1,109 @@ +@@ -0,0 +1,42 @@ +package pipe + +import ( -+ "context" -+ "sync" ++ "sync/atomic" + + "github.com/xtls/xray-core/common/buf" +) @@ -4270,111 +4519,44 @@ index 0000000..f16b3e1 +} + +type delivery struct { -+ sync.Mutex + counter DeliveryCounter -+ pending int64 -+ done bool -+ stop func() bool ++ pending atomic.Int64 +} + -+func (r *Reader) CountDelivered(ctx context.Context, counter DeliveryCounter) { -+ d := &delivery{counter: counter} -+ r.delivery = d -+ stop := context.AfterFunc(ctx, func() { -+ d.resolve(r.pipe.drained()) -+ }) -+ d.Lock() -+ d.stop = stop -+ d.Unlock() ++func (r *Reader) CountDelivered(counter DeliveryCounter) { ++ r.delivery = &delivery{counter: counter} +} + -+func (r *Reader) observe(mb buf.MultiBuffer, err error) { -+ if r.delivery == nil { -+ return -+ } -+ if err == nil { -+ r.delivery.hold(mb) -+ return -+ } -+ if r.pipe.ended() { -+ r.delivery.finish(true) -+ } ++func (r *Reader) SettleDelivered() { ++ r.delivery.settle() +} + +func (d *delivery) settle() { + if d == nil { + return + } -+ d.Lock() -+ n := d.pending -+ d.pending = 0 -+ d.Unlock() -+ if n > 0 { ++ if n := d.pending.Swap(0); n > 0 { + d.counter.Add(n) + } +} + +func (d *delivery) hold(mb buf.MultiBuffer) { -+ if mb.IsEmpty() { -+ return -+ } -+ d.Lock() -+ defer d.Unlock() -+ if !d.done { -+ d.pending += int64(mb.Len()) -+ } -+} -+ -+func (d *delivery) resolve(count bool) { -+ d.Lock() -+ n := d.pending -+ d.pending = 0 -+ d.Unlock() -+ if count && n > 0 { -+ d.counter.Add(n) -+ } -+} -+ -+func (d *delivery) finish(count bool) { + if d == nil { + return + } -+ d.Lock() -+ n := d.pending -+ d.pending = 0 -+ stop := d.stop -+ d.stop = nil -+ d.done = true -+ d.Unlock() -+ if stop != nil { -+ stop() -+ } -+ if count && n > 0 { -+ d.counter.Add(n) ++ if n := int64(mb.Len()); n > 0 { ++ d.pending.Add(n) + } +} -+ -+func (p *pipe) drained() bool { -+ p.Lock() -+ defer p.Unlock() -+ return p.state == closed && p.data.IsEmpty() -+} -+ -+func (p *pipe) ended() bool { -+ p.Lock() -+ defer p.Unlock() -+ return p.state == errord || (p.state == closed && p.data.IsEmpty()) -+} diff --git a/transport/pipe/delivery_test.go b/transport/pipe/delivery_test.go new file mode 100644 -index 0000000..9acaf21 +index 0000000..6fa5301 --- /dev/null +++ b/transport/pipe/delivery_test.go -@@ -0,0 +1,246 @@ +@@ -0,0 +1,242 @@ +package pipe_test + +import ( -+ "context" + "io" + "math/rand" + "sync" @@ -4426,10 +4608,15 @@ index 0000000..9acaf21 + } +} + -+func TestABatchIsCountedOnlyWhenTheReaderComesBackForMore(t *testing.T) { ++func countedPipe() (*Reader, *Writer, *deliveredCounter) { + reader, writer := New(WithSizeLimit(1 << 20)) + counter := &deliveredCounter{} -+ reader.CountDelivered(context.Background(), counter) ++ reader.CountDelivered(counter) ++ return reader, writer, counter ++} ++ ++func TestABatchIsCountedOnlyWhenTheReaderComesBackForMore(t *testing.T) { ++ reader, writer, counter := countedPipe() + + mustWrite(t, writer, 1000) + requireCounted(t, counter, 0) @@ -4445,16 +4632,24 @@ index 0000000..9acaf21 + requireCounted(t, counter, 1300) +} + -+func TestTheBatchHeldWhenTheReaderIsInterruptedIsNeverCounted(t *testing.T) { -+ reader, writer := New(WithSizeLimit(1 << 20)) -+ counter := &deliveredCounter{} -+ reader.CountDelivered(context.Background(), counter) ++func TestABatchTheReaderNeverComesBackAfterIsNeverCounted(t *testing.T) { ++ reader, writer, counter := countedPipe() + + mustWrite(t, writer, 700) + mustRead(t, reader, 700) + mustWrite(t, writer, 900) + mustRead(t, reader, 900) + reader.Interrupt() ++ time.Sleep(20 * time.Millisecond) ++ requireCounted(t, counter, 700) ++} ++ ++func TestAReaderThatComesBackAfterAnInterruptCountsTheBatchItDelivered(t *testing.T) { ++ reader, writer, counter := countedPipe() ++ ++ mustWrite(t, writer, 700) ++ mustRead(t, reader, 700) ++ reader.Interrupt() + if _, err := reader.ReadMultiBuffer(); err == nil { + t.Fatal("a read after the interrupt returned no error") + } @@ -4462,60 +4657,36 @@ index 0000000..9acaf21 +} + +func TestBytesLeftInThePipeAreNeverCounted(t *testing.T) { -+ reader, writer := New(WithSizeLimit(1 << 20)) -+ counter := &deliveredCounter{} -+ ctx, cancel := context.WithCancel(context.Background()) -+ reader.CountDelivered(ctx, counter) ++ reader, writer, counter := countedPipe() + + mustWrite(t, writer, 400) + mustRead(t, reader, 400) + mustWrite(t, writer, 5000) + reader.Interrupt() -+ cancel() -+ time.Sleep(50 * time.Millisecond) -+ requireCounted(t, counter, 0) -+} -+ -+func TestTheLastBatchOfAFinishedStreamIsCountedWhenItsConnectionEnds(t *testing.T) { -+ reader, writer := New(WithSizeLimit(1 << 20)) -+ counter := &deliveredCounter{} -+ ctx, cancel := context.WithCancel(context.Background()) -+ reader.CountDelivered(ctx, counter) -+ -+ mustWrite(t, writer, 250) -+ writer.Close() -+ mustRead(t, reader, 250) -+ requireCounted(t, counter, 0) -+ cancel() -+ deadline := time.Now().Add(2 * time.Second) -+ for counter.value.Load() != 250 && time.Now().Before(deadline) { -+ time.Sleep(5 * time.Millisecond) ++ if _, err := reader.ReadMultiBuffer(); err == nil { ++ t.Fatal("a read after the interrupt returned no error") + } -+ requireCounted(t, counter, 250) ++ requireCounted(t, counter, 400) +} + -+func TestTheBatchHeldWhenTheConnectionEndsMidStreamIsNeverCounted(t *testing.T) { -+ reader, writer := New(WithSizeLimit(1 << 20)) -+ counter := &deliveredCounter{} -+ ctx, cancel := context.WithCancel(context.Background()) -+ reader.CountDelivered(ctx, counter) ++func TestSettleCountsTheBatchAReaderThatStopsReadingDelivered(t *testing.T) { ++ reader, writer, counter := countedPipe() + + mustWrite(t, writer, 250) + mustRead(t, reader, 250) -+ cancel() -+ time.Sleep(50 * time.Millisecond) + requireCounted(t, counter, 0) ++ reader.SettleDelivered() ++ requireCounted(t, counter, 250) ++ reader.SettleDelivered() + mustWrite(t, writer, 10) + mustRead(t, reader, 10) -+ mustWrite(t, writer, 20) -+ mustRead(t, reader, 20) -+ requireCounted(t, counter, 10) ++ mustWrite(t, writer, 1) ++ mustRead(t, reader, 1) ++ requireCounted(t, counter, 260) +} + +func TestATimedOutReadKeepsCounting(t *testing.T) { -+ reader, writer := New(WithSizeLimit(1 << 20)) -+ counter := &deliveredCounter{} -+ reader.CountDelivered(context.Background(), counter) ++ reader, writer, counter := countedPipe() + + mustWrite(t, writer, 128) + if mb, err := reader.ReadMultiBufferTimeout(time.Second); err != nil || mb.Len() != 128 { @@ -4533,9 +4704,7 @@ index 0000000..9acaf21 +} + +func TestAnInjectedErrorDoesNotEndCounting(t *testing.T) { -+ reader, writer := New(WithSizeLimit(1 << 20)) -+ counter := &deliveredCounter{} -+ reader.CountDelivered(context.Background(), counter) ++ reader, writer, counter := countedPipe() + + mustWrite(t, writer, 100) + mustRead(t, reader, 100) @@ -4556,22 +4725,22 @@ index 0000000..9acaf21 + reader, writer := New(WithSizeLimit(1 << 20)) + mustWrite(t, writer, 10) + mustRead(t, reader, 10) ++ reader.SettleDelivered() + reader.Interrupt() + if _, err := reader.ReadMultiBuffer(); err == nil { + t.Fatal("a read after the interrupt returned no error") + } +} + -+func TestConcurrentInterruptsAndConnectionEndsCountOnlyBatchesTheReaderCameBackAfter(t *testing.T) { ++func TestConcurrentInterruptsAndClosesCountEveryBatchTheReaderCameBackAfter(t *testing.T) { + for round := range 300 { + reader, writer := New(WithSizeLimit(64 << 10)) + counter := &deliveredCounter{} -+ ctx, cancel := context.WithCancel(context.Background()) -+ reader.CountDelivered(ctx, counter) ++ reader.CountDelivered(counter) + rng := rand.New(rand.NewSource(int64(round))) + sizes := rand.New(rand.NewSource(int64(round) + 1_000_000)) + stopAfter := time.Duration(rng.Intn(3000)) * time.Microsecond -+ closeWriter := round%3 == 0 ++ giveUp := round%3 == 2 + + var wg sync.WaitGroup + wg.Add(3) @@ -4583,7 +4752,8 @@ index 0000000..9acaf21 + } + } + }() -+ var settled, last int64 ++ var delivered, held int64 ++ stop := make(chan struct{}) + go func() { + defer wg.Done() + for { @@ -4591,37 +4761,46 @@ index 0000000..9acaf21 + if err != nil { + return + } -+ settled += last -+ last = int64(mb.Len()) ++ delivered += held ++ held = int64(mb.Len()) + buf.ReleaseMulti(mb) ++ if giveUp { ++ select { ++ case <-stop: ++ return ++ default: ++ } ++ } ++ delivered += held ++ held = 0 + } + }() + go func() { + defer wg.Done() + time.Sleep(stopAfter) -+ if closeWriter { ++ if giveUp { ++ close(stop) ++ time.Sleep(time.Millisecond) ++ reader.Interrupt() ++ return ++ } ++ if round%3 == 0 { + writer.Close() + return + } + reader.Interrupt() + }() + wg.Wait() -+ cancel() -+ time.Sleep(time.Millisecond) -+ got := counter.value.Load() -+ if closeWriter && got != settled+last { -+ t.Fatalf("round %d: the stream ended cleanly after %d bytes, counted %d", round, settled+last, got) -+ } -+ if got != settled && got != settled+last { -+ t.Fatalf("round %d: counted %d, the reader came back after %d bytes and held %d more", round, got, settled, last) ++ if got := counter.value.Load(); got != delivered { ++ t.Fatalf("round %d: counted %d, the reader delivered and came back after %d bytes (held %d when it gave up)", round, got, delivered, held) + } + } +} diff --git a/transport/pipe/reader.go b/transport/pipe/reader.go -index 79f0ac0..d3db3b7 100644 +index 79f0ac0..9ba2eb1 100644 --- a/transport/pipe/reader.go +++ b/transport/pipe/reader.go -@@ -8,22 +8,30 @@ import ( +@@ -8,17 +8,24 @@ import ( // Reader is a buf.Reader that reads content from a pipe. type Reader struct { @@ -4635,7 +4814,7 @@ index 79f0ac0..d3db3b7 100644 - return r.pipe.ReadMultiBuffer() + r.delivery.settle() + mb, err := r.pipe.ReadMultiBuffer() -+ r.observe(mb, err) ++ r.delivery.hold(mb) + return mb, err } @@ -4644,14 +4823,8 @@ index 79f0ac0..d3db3b7 100644 - return r.pipe.ReadMultiBufferTimeout(d) + r.delivery.settle() + mb, err := r.pipe.ReadMultiBufferTimeout(d) -+ r.observe(mb, err) ++ r.delivery.hold(mb) + return mb, err } // Interrupt implements common.Interruptible. - func (r *Reader) Interrupt() { - r.pipe.Interrupt() -+ r.delivery.finish(false) - } - - // ReturnAnError makes ReadMultiBuffer return an error, only once. diff --git a/patches/xray-stats-register-race.patch b/patches/xray-stats-register-race.patch index 0db44a1d..7661b0eb 100644 --- a/patches/xray-stats-register-race.patch +++ b/patches/xray-stats-register-race.patch @@ -7,7 +7,7 @@ that does not exist at the pin are left out (the trackOnlineIP helper, TUN inbou restructured WireGuard client and server), and the pin names the online map field onlineMap. diff --git a/app/dispatcher/default.go b/app/dispatcher/default.go -index a8abd7a..50145b9 100644 +index 781d886..f0ad2a1 100644 --- a/app/dispatcher/default.go +++ b/app/dispatcher/default.go @@ -166,7 +166,7 @@ func (d *DefaultDispatcher) getLink(ctx context.Context) (*transport.Link, *tran @@ -25,7 +25,7 @@ index a8abd7a..50145b9 100644 name := "user>>>" + user.Email + ">>>traffic>>>downlink" - if c, _ := stats.GetOrRegisterCounter(d.stats, name); c != nil { + if c, _ := d.stats.GetOrRegisterCounter(name); c != nil { - downlinkReader.CountDelivered(ctx, c) + downlinkReader.CountDelivered(c) } } From a2a11cf2c4336e798c4b235e62c4b7cf6cda3826 Mon Sep 17 00:00:00 2001 From: Free-Guy-IR Date: Thu, 3 Dec 2026 08:20:54 +0330 Subject: [PATCH 4/4] fix(speedcap): settle a plain HTTP batch only after relaying the origin's response From the second review of 03ac8fe7: - The plain HTTP handler also settled the batch it held when it answered 503 itself because the origin's response did not parse. Six broken origin responses of 20,013 bytes, the client got only xray's 503 (594 bytes): 120,078 bytes counted before, 0 now (macOS, review test with XRAY_RAY_BUFFER_SIZE=1; the 0.6.29 core also counted 120,078). Data an origin sends after Content-Length is still counted, as on 0.6.29. - The abort tests drained the client socket right after a read whose deadline had passed, so the drain never read; the deadline is cleared first now. - docs/upstream-parity.md says the stats register race patch's dispatcher hunks have the speed cap patch's code as context. --- Dockerfile | 1 + docs/upstream-parity.md | 5 ++++- patches/xray-per-user-speed-cap.patch | 19 ++++++++++++++----- 3 files changed, 19 insertions(+), 6 deletions(-) diff --git a/Dockerfile b/Dockerfile index 65c4a674..f93b8e55 100644 --- a/Dockerfile +++ b/Dockerfile @@ -153,6 +153,7 @@ RUN git init -q . \ && test "$(grep -c 'r.delivery.settle()' transport/pipe/reader.go)" = "2" \ && test "$(grep -c 'r.delivery.hold(mb)' transport/pipe/reader.go)" = "2" \ && grep -qF "delivered.SettleDelivered()" proxy/http/server.go \ + && grep -qF "ok && relayed {" proxy/http/server.go \ && git apply --verbose /patches/xray-pinned-ca-servername.patch \ && grep -qF 'return errors.New("Pinning CA needs a valid ServerName")' transport/internet/tls/config.go \ && grep -qF "config := tlsConfig.GetTLSConfig(tls.WithDestination(dest))" transport/internet/grpc/dial.go \ diff --git a/docs/upstream-parity.md b/docs/upstream-parity.md index 739d5040..1aedeb7b 100644 --- a/docs/upstream-parity.md +++ b/docs/upstream-parity.md @@ -1501,7 +1501,10 @@ shipped. - hunks for code that does not exist at the pin are left out: the `trackOnlineIP` helper, TUN inbound stats, and the restructured WireGuard client and server; - the pin names the online map field `onlineMap`, not `onlineMaps`; - - the interface keeps the pin's doc comment for `UnregisterOnlineMap`. + - the interface keeps the pin's doc comment for `UnregisterOnlineMap`; + - the context of its dispatcher hunks is the speed cap patch's code, which attaches the user downlink counter to + the downlink pipe reader in `getLink` and counts `WrapLink`'s downlink after the write; its own changed lines are + the same. - **Test:** `TestPerUserStatsCountEveryByteOnceUnderConcurrentFirstTrafficAndReset` starts 16 connections per user at once through `dispatcher.WrapLink`, with a `QueryStats` reset poller running throughout. It checks that every byte is counted exactly once and that every IP reaches the online map, over 200 rounds under `-race`. diff --git a/patches/xray-per-user-speed-cap.patch b/patches/xray-per-user-speed-cap.patch index 7552b95e..1cc0239a 100644 --- a/patches/xray-per-user-speed-cap.patch +++ b/patches/xray-per-user-speed-cap.patch @@ -2598,14 +2598,22 @@ index 0000000..47bdfc5 + } +} diff --git a/proxy/http/server.go b/proxy/http/server.go -index 0deecad..fa8327d 100644 +index 0deecad..bbc3bdc 100644 --- a/proxy/http/server.go +++ b/proxy/http/server.go -@@ -299,6 +299,9 @@ func (s *Server) handlePlainHTTP(ctx context.Context, request *http.Request, wri +@@ -268,6 +268,7 @@ func (s *Server) handlePlainHTTP(ctx context.Context, request *http.Request, wri + responseDone := func() error { + responseReader := bufio.NewReaderSize(&buf.BufferedReader{Reader: link.Reader}, buf.Size) + response, err := readResponseAndHandle100Continue(responseReader, request, writer) ++ relayed := err == nil + if err == nil { + http_proto.RemoveHopByHopHeaders(response.Header) + if response.ContentLength >= 0 { +@@ -299,6 +300,9 @@ func (s *Server) handlePlainHTTP(ctx context.Context, request *http.Request, wri if err := response.Write(writer); err != nil { return errors.New("failed to write response").Base(err).AtWarning() } -+ if delivered, ok := link.Reader.(interface{ SettleDelivered() }); ok { ++ if delivered, ok := link.Reader.(interface{ SettleDelivered() }); ok && relayed { + delivered.SettleDelivered() + } return nil @@ -2677,10 +2685,10 @@ index dbd81d6..bbc7ae1 100644 if err := buf.Copy(reader, writer, buf.UpdateActivity(timer), buf.AddToStatCounter(readCounter)); err != nil { diff --git a/testing/scenarios/speedcap_delivered_test.go b/testing/scenarios/speedcap_delivered_test.go new file mode 100644 -index 0000000..a16f7fd +index 0000000..46a937e --- /dev/null +++ b/testing/scenarios/speedcap_delivered_test.go -@@ -0,0 +1,528 @@ +@@ -0,0 +1,529 @@ +//go:build linux || darwin + +package scenarios @@ -2933,6 +2941,7 @@ index 0000000..a16f7fd + if err != nil { + var timeout gonet.Error + if errors.As(err, &timeout) && timeout.Timeout() { ++ tcpConn.SetReadDeadline(time.Time{}) + return received + drainNow(tcpConn, buffer) - p.header, nil + } + return received - p.header, err