diff -ruN a/proxy/tun/rayray_limits.go b/proxy/tun/rayray_limits.go --- a/proxy/tun/rayray_limits.go 1970-01-01 03:00:00 +++ b/proxy/tun/rayray_limits.go 2026-11-09 20:04:25 @@ -0,0 +1,86 @@ +package tun + +import ( + "os" + "runtime" + "strconv" + "sync/atomic" + "time" + + "github.com/xtls/xray-core/common/errors" +) + +// RayRay patch: limits for a phone, where the whole network extension has about 50 MB. Every open connection +// keeps buffers, and a heavy page opens hundreds of them: past the limits a new TCP connection's SYN is not +// answered (the system sends it again a moment later) and no new UDP flow is opened: memory stays far from the limit. +var ( + // tcpMaxConns and udpMaxFlows are XRAY_TUN_MAX_TCP and XRAY_TUN_MAX_UDP from the env of the config; 0 is no limit. + // Atomic: a stack still closing after a quick restart reads them while the new one's start writes them + tcpMaxConns, udpMaxFlows atomic.Int64 + // udpQueueLimit bounds the packets waiting for one UDP flow; more are dropped. On iOS 128 instead of 1024: + // a full queue is a megabyte, and a flow that falls that far behind is better served by dropping. Set once, + // before any stack starts + udpQueueLimit = queueLimit() +) + +// readLimits takes the limits once the config, with its env, is read: when the tun starts +func readLimits() { + tcpMaxConns.Store(envLimit("XRAY_TUN_MAX_TCP")) + udpMaxFlows.Store(envLimit("XRAY_TUN_MAX_UDP")) +} + +const ( + // roomAfter is how long new connections are refused before the quietest open one is closed. The refusal alone + // protects memory in a burst; it must not go on for good when the open ones hang and nothing else frees a place + roomAfter = 5 * time.Second + // roomEvery is the least time between two closes, roomLogEvery between two lines in the log + roomEvery = 100 * time.Millisecond + roomLogEvery = 5 * time.Second +) + +// makeRoom is called for every SYN refused at the limit and returns the connection to close now, if any. s.mu is held +func (s *stack) makeRoom() *tcpConn { + now := time.Now() + if s.refusedSince.IsZero() { + s.refusedSince = now + return nil + } + if now.Sub(s.refusedSince) < roomAfter || now.Sub(s.roomMadeAt) < roomEvery { + return nil + } + s.roomMadeAt = now + var quietest *tcpConn + for _, c := range s.conns { + if quietest == nil || c.active.Load() < quietest.active.Load() { + quietest = c + } + } + if now.Sub(s.roomLoggedAt) >= roomLogEvery { + s.roomLoggedAt = now + errors.LogWarning(s.ctx, "[tun] connection limit reached for 5 s, the quietest connection is closed") + } + return quietest +} + +// accepted is called for every SYN under the limit. A close is why it got in, so one within roomAfter of a close does +// not start the wait over: a page opening many connections is let in at roomEvery. s.mu is held +func (s *stack) accepted() { + if time.Since(s.roomMadeAt) >= roomAfter { + s.refusedSince = time.Time{} + } +} + +func queueLimit() int { + if runtime.GOOS == "ios" { + return 128 + } + return 1024 +} + +func envLimit(key string) int64 { + n, err := strconv.ParseInt(os.Getenv(key), 10, 64) + if err != nil || n < 0 { + return 0 + } + return n +} diff -ruN a/proxy/tun/stack.go b/proxy/tun/stack.go --- a/proxy/tun/stack.go 2026-11-09 20:03:46 +++ b/proxy/tun/stack.go 2026-11-09 20:04:25 @@ -8,6 +8,7 @@ "math/rand/v2" gonet "net" "net/netip" + "runtime" "slices" "sync" "sync/atomic" @@ -81,6 +82,9 @@ // sockets are the ports that DialUDP has opened sockets map[netip.AddrPort]*udpSocket closed bool + // RayRay patch: since when SYNs are refused at the limit without one accepted, zero if the last was accepted; + // and when the last connection was closed for that and logged (see rayray_limits.go) + refusedSince, roomMadeAt, roomLoggedAt time.Time // opening is how many of conns wait for the answer to their SYN or SYN-ACK opening atomic.Int32 // fragments are the packets that are larger than a link on their way and come in parts. @@ -111,6 +115,10 @@ if options.Remote { s.window = tcpLargeWindow } + if runtime.GOOS == "ios" { + s.window = tcpWindowIOS + } + readLimits() for i := range s.identification { s.identification[i].Store(rand.Uint32()) } @@ -333,6 +341,28 @@ } if s.opening.Load() >= tcpOpening { + return + } + // RayRay patch: no new connection past the limit (see rayray_limits.go); the system tries it again + limit := tcpMaxConns.Load() + var quietest *tcpConn + s.mu.Lock() + full := limit > 0 && int64(len(s.conns)) >= limit + if full { + quietest = s.makeRoom() + } else { + s.accepted() + } + s.mu.Unlock() + if quietest != nil { + // as Close of the stack does, and without s.mu: reset takes it under c.mu + quietest.mu.Lock() + if quietest.err == nil { + quietest.reset() + } + quietest.mu.Unlock() + } + if full { return } c = newTCPConn(s, f) diff -ruN a/proxy/tun/tcp_lightweight.go b/proxy/tun/tcp_lightweight.go --- a/proxy/tun/tcp_lightweight.go 2026-11-09 20:03:46 +++ b/proxy/tun/tcp_lightweight.go 2026-11-09 20:04:25 @@ -9,6 +9,7 @@ "net/netip" "slices" "sync" + "sync/atomic" "time" "github.com/xtls/xray-core/common/buf" @@ -29,6 +30,10 @@ // and the most that it sends to the system before that is acknowledged. More than that, for several // connections at once, is more packets than the queue of a tun holds (500 on Linux) tcpWindow = 256 << 10 + // RayRay patch: on iOS the window is 64 KB. Its way is only between the system and this stack on the + // same phone, a round trip well under a millisecond, so a smaller window is as fast; and the network + // extension has about 50 MB in all, which dozens of connections of a heavy page with 256 KB each run into + tcpWindowIOS = 64 << 10 // tcpLargeWindow is the same for a tun that takes and gives segments that are larger than its MTU: those are // few, and a way with a longer round trip, as a router has to what is behind it, is not held back by it tcpLargeWindow = 1 << 20 @@ -122,6 +127,10 @@ stack *stack flow flow src, dst net.Destination + // active is when the system or the proxy last gave it something, in Unix nanoseconds. RayRay patch: it tells which + // connection is the quietest when one has to go (see rayray_limits.go). Atomic: that is read under stack.mu, + // which is taken under c.mu, so c.mu is out of reach there + active atomic.Int64 // ip is the IP header of what is sent, without the length ip [ipv6HeaderSize]byte // ipSize is the size of that header @@ -231,6 +240,7 @@ c.sndUna = rand.Uint32() c.sndNxt = c.sndUna + 1 c.stampBase = rand.Uint32() + c.active.Store(time.Now().UnixNano()) return c } @@ -445,6 +455,7 @@ // input takes a segment of the connection. It returns false if the connection is gone // and the segment is the start of another one func (c *tcpConn) input(s segment) bool { + c.active.Store(time.Now().UnixNano()) c.mu.Lock() defer c.mu.Unlock() if c.err != nil { @@ -1114,6 +1125,7 @@ // WriteMultiBuffer implements buf.Writer. It is not called again before it returns func (c *tcpConn) WriteMultiBuffer(mb buf.MultiBuffer) error { + c.active.Store(time.Now().UnixNano()) c.mu.Lock() defer c.mu.Unlock() // without the empty ones diff -ruN a/proxy/tun/udp_fullcone.go b/proxy/tun/udp_fullcone.go --- a/proxy/tun/udp_fullcone.go 2026-11-09 20:03:46 +++ b/proxy/tun/udp_fullcone.go 2026-11-09 20:03:46 @@ -52,6 +52,11 @@ defer u.Unlock() conn, found = u.udpConns[src] + if limit := udpMaxFlows.Load(); !found && limit > 0 && int64(len(u.udpConns)) >= limit { + // RayRay patch: no new flow past the limit (see rayray_limits.go) + data.Release() + return + } if !found { conn = &udpConn{handler: u, queue: newPacketQueue(udpQueueLimit), src: src, dst: dst} u.udpConns[src] = conn @@ -163,9 +168,6 @@ func (c *udpConn) SetWriteDeadline(t time.Time) error { return nil } - -// udpQueueLimit bounds the packets waiting for one UDP flow; more are dropped. -const udpQueueLimit = 1024 // packetQueue holds the packets waiting for one UDP flow. Unlike a buffered // channel of the same bound it only allocates for packets actually queued, so