From bfa9ea1d2b4875efe810ea6081e97093295c9171 Mon Sep 17 00:00:00 2001 From: wwqgtxx Date: Tue, 14 Jul 2026 08:49:22 +0800 Subject: [PATCH] feat: support brutal for shadowquic (mihomo private extension) --- adapter/outbound/shadowquic.go | 11 +- docs/config.yaml | 7 +- listener/config/shadowquic.go | 35 +++--- listener/inbound/shadowquic.go | 66 ++++++----- listener/shadowquic/server.go | 18 +-- transport/shadowquic/client.go | 48 +++++++- transport/shadowquic/congestion.go | 51 ++++++++ transport/shadowquic/extension_brutal.go | 92 +++++++++++++++ transport/shadowquic/server.go | 59 +++++++++- transport/shadowquic/state.go | 11 ++ transport/tuic/congestion_v2/brutal.go | 144 +++++++++++++++++++++++ 11 files changed, 480 insertions(+), 62 deletions(-) create mode 100644 transport/shadowquic/extension_brutal.go create mode 100644 transport/tuic/congestion_v2/brutal.go diff --git a/adapter/outbound/shadowquic.go b/adapter/outbound/shadowquic.go index 3561a1d28..6a5fabe34 100644 --- a/adapter/outbound/shadowquic.go +++ b/adapter/outbound/shadowquic.go @@ -6,6 +6,7 @@ import ( "strconv" "time" + "github.com/metacubex/mihomo/common/utils" "github.com/metacubex/mihomo/component/ca" C "github.com/metacubex/mihomo/constant" "github.com/metacubex/mihomo/ntp" @@ -39,6 +40,8 @@ type ShadowQuicOption struct { ZeroRTT bool `proxy:"zero-rtt,omitempty"` KeepAliveInterval int `proxy:"keep-alive-interval,omitempty"` CongestionController string `proxy:"congestion-controller,omitempty"` + Up string `proxy:"up,omitempty"` + Down string `proxy:"down,omitempty"` CWND int `proxy:"cwnd,omitempty"` BBRProfile string `proxy:"bbr-profile,omitempty"` ReceiveWindowConn int `proxy:"recv-window-conn,omitempty"` @@ -171,13 +174,17 @@ func NewShadowQuic(option ShadowQuicOption) (*ShadowQuic, error) { } outbound.dialer = option.NewDialer(outbound.DialOptions()) outbound.client = shadowquic.NewClient(&shadowquic.ClientOption{ - UDPOverStream: option.UDPOverStream, + UDPOverStream: option.UDPOverStream, + CongestionController: option.CongestionController, + SendBPS: utils.StringToBps(option.Up), + ReceiveBPS: utils.StringToBps(option.Down), + CWND: option.CWND, + BBRProfile: option.BBRProfile, Dial: func(ctx context.Context) (*quic.Conn, error) { _, quicConn, err := shadowquic.DialQuic(ctx, outbound.addr, outbound.DialOptions(), outbound.dialer, outbound.tlsConfig, outbound.quicConfig, option.ZeroRTT) if err != nil { return nil, err } - shadowquic.SetCongestionController(quicConn, option.CongestionController, option.CWND, option.BBRProfile) return quicConn, nil }, }) diff --git a/docs/config.yaml b/docs/config.yaml index 22fda5672..1e18890e7 100644 --- a/docs/config.yaml +++ b/docs/config.yaml @@ -1459,6 +1459,8 @@ proxies: # socks5 # zero-rtt: false # 官方 server 的 0-RTT 路径可能在 JLS 认证完成前读取用户状态(已确认影响 v0.3.11);使用官方 server 时必须在服务端关闭 zero-rtt # keep-alive-interval: 10000 # congestion-controller: bbr # Available: "cubic", "new_reno", "bbr". Default: "cubic" + # up: 100 Mbps # enables brutal; client upload speed; requires mihomo ShadowQuic on both ends + # down: 100 Mbps # enables brutal; requested client download speed, capped by listener up; requires mihomo ShadowQuic on both ends # cwnd: 10 # default: 32 # bbr-profile: "" # Available: "standard", "conservative", "aggressive". Default: "standard" # max-datagram-frame-size: 1400 @@ -2184,7 +2186,10 @@ listeners: # - h3 # quic-versions: [v1] # 本机手动配置及探测失败时的版本;支持 v1/v2 # zero-rtt: true - # congestion-controller: bbr + # congestion-controller: bbr # Available: "cubic", "new_reno", "bbr". Default: "cubic" + # up: 100 Mbps # enables brutal; server upload/client download speed cap; requires mihomo ShadowQuic on both ends + # down: 100 Mbps # enables brutal; requested server download/client upload speed; requires mihomo ShadowQuic on both ends + # ignore-client-bandwidth: false # for brutal; ignore outbound down and use listener down/auto instead # cwnd: 10 # default: 32 # bbr-profile: "" # Available: "standard", "conservative", "aggressive". Default: "standard" # max-idle-time: 30000 diff --git a/listener/config/shadowquic.go b/listener/config/shadowquic.go index 7ab8fd0e2..265e45961 100644 --- a/listener/config/shadowquic.go +++ b/listener/config/shadowquic.go @@ -20,22 +20,25 @@ type ShadowQuicJLSUpstream struct { } type ShadowQuicServer struct { - Enable bool `yaml:"enable" json:"enable"` - Listen string `yaml:"listen" json:"listen"` - Users []ShadowQuicUser `yaml:"users" json:"users,omitempty"` - JLSUpstream ShadowQuicJLSUpstream `yaml:"jls-upstream" json:"jls-upstream"` - ALPN []string `yaml:"alpn" json:"alpn,omitempty"` - QUICVersions []string `yaml:"quic-versions" json:"quic-versions,omitempty"` - ZeroRTT bool `yaml:"zero-rtt" json:"zero-rtt,omitempty"` - CongestionController string `yaml:"congestion-controller" json:"congestion-controller,omitempty"` - MaxIdleTime int `yaml:"max-idle-time" json:"max-idle-time,omitempty"` - MaxDatagramFrameSize int `yaml:"max-datagram-frame-size" json:"max-datagram-frame-size,omitempty"` - ReceiveWindowConn int `yaml:"recv-window-conn" json:"recv-window-conn,omitempty"` - ReceiveWindow int `yaml:"recv-window" json:"recv-window,omitempty"` - DisableMTUDiscovery bool `yaml:"disable-mtu-discovery" json:"disable-mtu-discovery,omitempty"` - CWND int `yaml:"cwnd" json:"cwnd,omitempty"` - BBRProfile string `yaml:"bbr-profile" json:"bbr-profile,omitempty"` - MuxOption sing.MuxOption `yaml:"mux-option" json:"mux-option,omitempty"` + Enable bool `yaml:"enable" json:"enable"` + Listen string `yaml:"listen" json:"listen"` + Users []ShadowQuicUser `yaml:"users" json:"users,omitempty"` + JLSUpstream ShadowQuicJLSUpstream `yaml:"jls-upstream" json:"jls-upstream"` + ALPN []string `yaml:"alpn" json:"alpn,omitempty"` + QUICVersions []string `yaml:"quic-versions" json:"quic-versions,omitempty"` + ZeroRTT bool `yaml:"zero-rtt" json:"zero-rtt,omitempty"` + CongestionController string `yaml:"congestion-controller" json:"congestion-controller,omitempty"` + Up string `yaml:"up" json:"up,omitempty"` + Down string `yaml:"down" json:"down,omitempty"` + IgnoreClientBandwidth bool `yaml:"ignore-client-bandwidth" json:"ignore-client-bandwidth,omitempty"` + MaxIdleTime int `yaml:"max-idle-time" json:"max-idle-time,omitempty"` + MaxDatagramFrameSize int `yaml:"max-datagram-frame-size" json:"max-datagram-frame-size,omitempty"` + ReceiveWindowConn int `yaml:"recv-window-conn" json:"recv-window-conn,omitempty"` + ReceiveWindow int `yaml:"recv-window" json:"recv-window,omitempty"` + DisableMTUDiscovery bool `yaml:"disable-mtu-discovery" json:"disable-mtu-discovery,omitempty"` + CWND int `yaml:"cwnd" json:"cwnd,omitempty"` + BBRProfile string `yaml:"bbr-profile" json:"bbr-profile,omitempty"` + MuxOption sing.MuxOption `yaml:"mux-option" json:"mux-option,omitempty"` } func (s ShadowQuicServer) String() string { diff --git a/listener/inbound/shadowquic.go b/listener/inbound/shadowquic.go index 63d84960e..eef49b627 100644 --- a/listener/inbound/shadowquic.go +++ b/listener/inbound/shadowquic.go @@ -12,20 +12,23 @@ import ( type ShadowQuicOption struct { BaseOption - Users []ShadowQuicUser `inbound:"users,omitempty"` - JLSUpstream ShadowQuicJLSUpstream `inbound:"jls-upstream"` - ALPN []string `inbound:"alpn,omitempty"` - QUICVersions []string `inbound:"quic-versions,omitempty"` - ZeroRTT bool `inbound:"zero-rtt,omitempty"` - CongestionController string `inbound:"congestion-controller,omitempty"` - MaxIdleTime int `inbound:"max-idle-time,omitempty"` - MaxDatagramFrameSize int `inbound:"max-datagram-frame-size,omitempty"` - ReceiveWindowConn int `inbound:"recv-window-conn,omitempty"` - ReceiveWindow int `inbound:"recv-window,omitempty"` - DisableMTUDiscovery bool `inbound:"disable-mtu-discovery,omitempty"` - CWND int `inbound:"cwnd,omitempty"` - BBRProfile string `inbound:"bbr-profile,omitempty"` - MuxOption MuxOption `inbound:"mux-option,omitempty"` + Users []ShadowQuicUser `inbound:"users,omitempty"` + JLSUpstream ShadowQuicJLSUpstream `inbound:"jls-upstream"` + ALPN []string `inbound:"alpn,omitempty"` + QUICVersions []string `inbound:"quic-versions,omitempty"` + ZeroRTT bool `inbound:"zero-rtt,omitempty"` + CongestionController string `inbound:"congestion-controller,omitempty"` + Up string `inbound:"up,omitempty"` + Down string `inbound:"down,omitempty"` + IgnoreClientBandwidth bool `inbound:"ignore-client-bandwidth,omitempty"` + MaxIdleTime int `inbound:"max-idle-time,omitempty"` + MaxDatagramFrameSize int `inbound:"max-datagram-frame-size,omitempty"` + ReceiveWindowConn int `inbound:"recv-window-conn,omitempty"` + ReceiveWindow int `inbound:"recv-window,omitempty"` + DisableMTUDiscovery bool `inbound:"disable-mtu-discovery,omitempty"` + CWND int `inbound:"cwnd,omitempty"` + BBRProfile string `inbound:"bbr-profile,omitempty"` + MuxOption MuxOption `inbound:"mux-option,omitempty"` } type ShadowQuicUser struct { @@ -78,22 +81,25 @@ func NewShadowQuic(options *ShadowQuicOption) (*ShadowQuic, error) { Base: base, config: options, ss: LC.ShadowQuicServer{ - Enable: true, - Listen: base.RawAddress(), - Users: utils.Map(options.Users, ShadowQuicUser.Build), - JLSUpstream: options.JLSUpstream.Build(), - ALPN: options.ALPN, - QUICVersions: options.QUICVersions, - ZeroRTT: options.ZeroRTT, - CongestionController: options.CongestionController, - MaxIdleTime: options.MaxIdleTime, - MaxDatagramFrameSize: options.MaxDatagramFrameSize, - ReceiveWindowConn: options.ReceiveWindowConn, - ReceiveWindow: options.ReceiveWindow, - DisableMTUDiscovery: options.DisableMTUDiscovery, - CWND: options.CWND, - BBRProfile: options.BBRProfile, - MuxOption: options.MuxOption.Build(), + Enable: true, + Listen: base.RawAddress(), + Users: utils.Map(options.Users, ShadowQuicUser.Build), + JLSUpstream: options.JLSUpstream.Build(), + ALPN: options.ALPN, + QUICVersions: options.QUICVersions, + ZeroRTT: options.ZeroRTT, + CongestionController: options.CongestionController, + Up: options.Up, + Down: options.Down, + IgnoreClientBandwidth: options.IgnoreClientBandwidth, + MaxIdleTime: options.MaxIdleTime, + MaxDatagramFrameSize: options.MaxDatagramFrameSize, + ReceiveWindowConn: options.ReceiveWindowConn, + ReceiveWindow: options.ReceiveWindow, + DisableMTUDiscovery: options.DisableMTUDiscovery, + CWND: options.CWND, + BBRProfile: options.BBRProfile, + MuxOption: options.MuxOption.Build(), }, }, nil } diff --git a/listener/shadowquic/server.go b/listener/shadowquic/server.go index 49afb9d36..3f3a163b9 100644 --- a/listener/shadowquic/server.go +++ b/listener/shadowquic/server.go @@ -10,6 +10,7 @@ import ( "github.com/metacubex/mihomo/adapter/inbound" "github.com/metacubex/mihomo/common/sockopt" + "github.com/metacubex/mihomo/common/utils" "github.com/metacubex/mihomo/component/ca" C "github.com/metacubex/mihomo/constant" LC "github.com/metacubex/mihomo/listener/config" @@ -156,13 +157,16 @@ func New(config LC.ShadowQuicServer, lc C.InboundListenConfig, tunnel C.Tunnel, } option := &shadowquic.ServerOption{ - HandleTcpFn: handleTcpFn, - HandleUdpFn: handleUdpFn, - TLSConfig: tlsConfig, - QUICConfig: quicConfig, - CongestionController: config.CongestionController, - CWND: config.CWND, - BBRProfile: config.BBRProfile, + HandleTcpFn: handleTcpFn, + HandleUdpFn: handleUdpFn, + TLSConfig: tlsConfig, + QUICConfig: quicConfig, + CongestionController: config.CongestionController, + SendBPS: utils.StringToBps(config.Up), + ReceiveBPS: utils.StringToBps(config.Down), + IgnoreClientBandwidth: config.IgnoreClientBandwidth, + CWND: config.CWND, + BBRProfile: config.BBRProfile, } sl := &Listener{config: config} diff --git a/transport/shadowquic/client.go b/transport/shadowquic/client.go index 0f55ff5f0..ba053cedb 100644 --- a/transport/shadowquic/client.go +++ b/transport/shadowquic/client.go @@ -14,8 +14,13 @@ import ( type DialFunc func(ctx context.Context) (*quic.Conn, error) type ClientOption struct { - Dial DialFunc - UDPOverStream bool + Dial DialFunc + UDPOverStream bool + CongestionController string + SendBPS uint64 + ReceiveBPS uint64 + CWND int + BBRProfile string } type Client struct { @@ -47,10 +52,49 @@ func (c *Client) getConn(ctx context.Context) (*connState, error) { if err != nil { return nil, err } + if err = c.configureCongestion(ctx, quicConn); err != nil { + _ = quicConn.CloseWithError(0, err.Error()) + return nil, err + } c.conn = newConnState(quicConn) return c.conn, nil } +func (c *Client) configureCongestion(ctx context.Context, quicConn *quic.Conn) error { + if !c.brutalEnabled() { + SetCongestionController(quicConn, c.option.CongestionController, c.option.CWND, c.option.BBRProfile) + return nil + } + + stream, err := quicConn.OpenStreamSync(ctx) + if err != nil { + return err + } + defer stream.Close() + + if err = WriteBrutalNegotiationRequest(stream, c.option.ReceiveBPS); err != nil { + return err + } + rx, rxAuto, err := ReadBrutalNegotiationResponse(stream) + if err != nil { + return err + } + actualTx := rx + if actualTx == 0 || actualTx > c.option.SendBPS { + actualTx = c.option.SendBPS + } + if !rxAuto && actualTx > 0 { + setBrutalCongestionController(quicConn, actualTx) + } else { + SetCongestionController(quicConn, "bbr", c.option.CWND, c.option.BBRProfile) + } + return nil +} + +func (c *Client) brutalEnabled() bool { + return c.option.SendBPS > 0 || c.option.ReceiveBPS > 0 +} + func (c *Client) DialContext(ctx context.Context, metadata *C.Metadata) (net.Conn, error) { state, err := c.getConn(ctx) if err != nil { diff --git a/transport/shadowquic/congestion.go b/transport/shadowquic/congestion.go index 42ed97fa7..8cc4fb830 100644 --- a/transport/shadowquic/congestion.go +++ b/transport/shadowquic/congestion.go @@ -46,6 +46,15 @@ func SetCongestionController(quicConn *quic.Conn, cc string, cwnd int, profile s } } +func setBrutalCongestionController(quicConn *quic.Conn, bps uint64) { + if bps == 0 { + return + } + quicConn.SetCongestionControl(newCongestionAdapter( + congestionv2.NewBrutalSender(bps), + )) +} + func newCongestionAdapter(cc oldcongestion.CongestionControl) jcongestion.CongestionControl { return &congestionAdapter{cc: cc} } @@ -121,6 +130,48 @@ func (a *congestionAdapter) GetCongestionWindow() jcongestion.ByteCount { return jcongestion.ByteCount(a.cc.GetCongestionWindow()) } +func (a *congestionAdapter) OnCongestionEventEx(priorInFlight jcongestion.ByteCount, eventTime jmonotime.Time, ackedPackets []jcongestion.AckedPacketInfo, lostPackets []jcongestion.LostPacketInfo) { + ex, ok := a.cc.(oldcongestion.CongestionControlEx) + if !ok { + return + } + ex.OnCongestionEventEx( + oldcongestion.ByteCount(priorInFlight), + oldmonotime.Time(eventTime), + adaptAckedPacketInfo(ackedPackets), + adaptLostPacketInfo(lostPackets), + ) +} + +func adaptAckedPacketInfo(packets []jcongestion.AckedPacketInfo) []oldcongestion.AckedPacketInfo { + if len(packets) == 0 { + return nil + } + adapted := make([]oldcongestion.AckedPacketInfo, len(packets)) + for i, packet := range packets { + adapted[i] = oldcongestion.AckedPacketInfo{ + PacketNumber: oldcongestion.PacketNumber(packet.PacketNumber), + BytesAcked: oldcongestion.ByteCount(packet.BytesAcked), + ReceivedTime: oldmonotime.Time(packet.ReceivedTime), + } + } + return adapted +} + +func adaptLostPacketInfo(packets []jcongestion.LostPacketInfo) []oldcongestion.LostPacketInfo { + if len(packets) == 0 { + return nil + } + adapted := make([]oldcongestion.LostPacketInfo, len(packets)) + for i, packet := range packets { + adapted[i] = oldcongestion.LostPacketInfo{ + PacketNumber: oldcongestion.PacketNumber(packet.PacketNumber), + BytesLost: oldcongestion.ByteCount(packet.BytesLost), + } + } + return adapted +} + type rttStatsProviderAdapter struct { provider jcongestion.RTTStatsProvider } diff --git a/transport/shadowquic/extension_brutal.go b/transport/shadowquic/extension_brutal.go new file mode 100644 index 000000000..b181b6ab9 --- /dev/null +++ b/transport/shadowquic/extension_brutal.go @@ -0,0 +1,92 @@ +package shadowquic + +import ( + "encoding/binary" + "errors" + "io" +) + +const ( + // Private mihomo extension opcode: ASCII "mihomo" + extension id 1. + extensionOpcodeMihomoBrutal uint64 = 0x6d69686f6d6f0001 + + brutalNegotiationVersion byte = 1 + brutalNegotiationHeaderLen = 1 + 1 + 2 // version + flags + payload length + brutalNegotiationMinPayloadLen = 8 // rx + brutalNegotiationMaxPayloadLen = 64 + + brutalNegotiationFlagRxAuto byte = 1 << 0 +) + +var ( + errInvalidBrutalNegotiation = errors.New("shadowquic: invalid brutal negotiation") + errUnsupportedBrutalVersion = errors.New("shadowquic: unsupported brutal negotiation version") +) + +// WriteBrutalNegotiationRequest writes a mihomo-only private extension request. +// JLS already authenticates users; rx follows Hysteria2 semantics: the desired +// receive bandwidth in bytes per second, with 0 meaning unknown/auto. +// +// The extension body uses a tiny versioned frame: +// +// version(1) | flags(1) | payload length(2) | payload +// +// Version 1 defines the first 8 payload bytes as rx. Readers deliberately +// ignore unknown flags and payload bytes after rx so future optional fields can +// be appended without changing the extension opcode. +func WriteBrutalNegotiationRequest(w io.Writer, rx uint64) error { + var buf [1 + 8 + brutalNegotiationHeaderLen + brutalNegotiationMinPayloadLen]byte + buf[0] = CommandExtension + binary.BigEndian.PutUint64(buf[1:9], extensionOpcodeMihomoBrutal) + writeBrutalNegotiationFrame(buf[9:], 0, rx) + return writeFull(w, buf[:]) +} + +func ReadBrutalNegotiationRequest(r io.Reader) (uint64, error) { + rx, _, err := readBrutalNegotiationFrame(r) + return rx, err +} + +func WriteBrutalNegotiationResponse(w io.Writer, rx uint64, rxAuto bool) error { + var buf [brutalNegotiationHeaderLen + brutalNegotiationMinPayloadLen]byte + var flags byte + if rxAuto { + flags |= brutalNegotiationFlagRxAuto + } + writeBrutalNegotiationFrame(buf[:], flags, rx) + return writeFull(w, buf[:]) +} + +func ReadBrutalNegotiationResponse(r io.Reader) (rx uint64, rxAuto bool, err error) { + rx, flags, err := readBrutalNegotiationFrame(r) + if err != nil { + return 0, false, err + } + return rx, flags&brutalNegotiationFlagRxAuto != 0, nil +} + +func writeBrutalNegotiationFrame(buf []byte, flags byte, rx uint64) { + buf[0] = brutalNegotiationVersion + buf[1] = flags + binary.BigEndian.PutUint16(buf[2:4], brutalNegotiationMinPayloadLen) + binary.BigEndian.PutUint64(buf[4:12], rx) +} + +func readBrutalNegotiationFrame(r io.Reader) (rx uint64, flags byte, err error) { + var header [brutalNegotiationHeaderLen]byte + if _, err = io.ReadFull(r, header[:]); err != nil { + return 0, 0, err + } + if header[0] != brutalNegotiationVersion { + return 0, 0, errUnsupportedBrutalVersion + } + payloadLen := int(binary.BigEndian.Uint16(header[2:4])) + if payloadLen < brutalNegotiationMinPayloadLen || payloadLen > brutalNegotiationMaxPayloadLen { + return 0, 0, errInvalidBrutalNegotiation + } + payload := make([]byte, payloadLen) + if _, err = io.ReadFull(r, payload); err != nil { + return 0, 0, err + } + return binary.BigEndian.Uint64(payload[:8]), header[1], nil +} diff --git a/transport/shadowquic/server.go b/transport/shadowquic/server.go index 8e75e53cc..288fa37d0 100644 --- a/transport/shadowquic/server.go +++ b/transport/shadowquic/server.go @@ -2,6 +2,7 @@ package shadowquic import ( "context" + "errors" "fmt" "net" @@ -21,9 +22,12 @@ type ServerOption struct { TLSConfig *tls.Config QUICConfig *quic.Config - CongestionController string - CWND int - BBRProfile string + CongestionController string + SendBPS uint64 + ReceiveBPS uint64 + IgnoreClientBandwidth bool + CWND int + BBRProfile string } type Server struct { @@ -45,7 +49,9 @@ func (s *Server) Serve() error { if err != nil { return err } - SetCongestionController(conn, s.option.CongestionController, s.option.CWND, s.option.BBRProfile) + if !s.brutalRequired() { + SetCongestionController(conn, s.option.CongestionController, s.option.CWND, s.option.BBRProfile) + } state := newConnState(conn) go s.handleConnection(state) } @@ -73,6 +79,10 @@ func (s *Server) handleStream(state *connState, stream *quic.Stream) { _ = conn.Close() return } + if command != CommandExtension && s.brutalRequired() && !state.isBrutalNegotiated() { + _ = conn.Close() + return + } switch command { case CommandConnect: @@ -112,6 +122,41 @@ func (s *Server) handleStream(state *connState, stream *quic.Stream) { } } +func (s *Server) brutalRequired() bool { + return s.option.SendBPS > 0 || s.option.ReceiveBPS > 0 +} + +func (s *Server) handleBrutalNegotiation(state *connState, conn net.Conn) { + rx, err := ReadBrutalNegotiationRequest(conn) + if err != nil { + return + } + rxAuto, err := s.configureBrutalCongestion(state.quicConn, rx) + if err != nil { + return + } + state.markBrutalNegotiated() + if err = WriteBrutalNegotiationResponse(conn, s.option.ReceiveBPS, rxAuto); err != nil { + return + } +} + +func (s *Server) configureBrutalCongestion(quicConn *quic.Conn, clientRx uint64) (bool, error) { + if s.option.ReceiveBPS > 0 && s.option.IgnoreClientBandwidth && clientRx == 0 { + return false, errors.New("shadowquic: brutal negotiation failed") + } + if !(s.option.ReceiveBPS == 0 && s.option.IgnoreClientBandwidth) && clientRx > 0 { + rx := clientRx + if s.option.SendBPS > 0 && rx > s.option.SendBPS { + rx = s.option.SendBPS + } + setBrutalCongestionController(quicConn, rx) + return false, nil + } + SetCongestionController(quicConn, "bbr", s.option.CWND, s.option.BBRProfile) + return true, nil +} + func (s *Server) handleExtension(state *connState, conn net.Conn) { defer conn.Close() @@ -120,6 +165,12 @@ func (s *Server) handleExtension(state *connState, conn net.Conn) { return } switch opcode { + case extensionOpcodeMihomoBrutal: + if state == nil || s.option == nil { + _ = WriteExtensionErrorResult(conn, extensionErrNotAvailable, "") + return + } + s.handleBrutalNegotiation(state, conn) case extensionOpcodeConn: subcommand, err := readExtensionSubcommand(conn) if err != nil { diff --git a/transport/shadowquic/state.go b/transport/shadowquic/state.go index dc2a3b64c..d018078be 100644 --- a/transport/shadowquic/state.go +++ b/transport/shadowquic/state.go @@ -5,6 +5,7 @@ import ( "io" "net" "sync" + "sync/atomic" "github.com/metacubex/mihomo/transport/socks5" @@ -35,6 +36,8 @@ type connState struct { nextID uint16 activeSend map[uint16]struct{} recv map[uint16]*recvSlot + + brutalNegotiated atomic.Bool } type recvSlot struct { @@ -81,6 +84,14 @@ func (s *connState) closeWithError(code quic.ApplicationErrorCode, message strin return s.quicConn.CloseWithError(code, message) } +func (s *connState) markBrutalNegotiated() { + s.brutalNegotiated.Store(true) +} + +func (s *connState) isBrutalNegotiated() bool { + return s.brutalNegotiated.Load() +} + func (s *connState) handleDatagrams() { for { message, err := s.quicConn.ReceiveDatagram(s.ctx) diff --git a/transport/tuic/congestion_v2/brutal.go b/transport/tuic/congestion_v2/brutal.go new file mode 100644 index 000000000..68944e767 --- /dev/null +++ b/transport/tuic/congestion_v2/brutal.go @@ -0,0 +1,144 @@ +package congestion + +import ( + "time" + + "github.com/metacubex/quic-go/congestion" + "github.com/metacubex/quic-go/monotime" +) + +const ( + brutalPacketInfoSlotCount = 5 // slot index is based on seconds, so this samples the recent 5 seconds. + brutalMinSampleCount = 50 + brutalMinAckRate = 0.8 + brutalCongestionWindowFactor = 2 + brutalInitialCongestionWindow = congestion.ByteCount(10240) +) + +var _ congestion.CongestionControlEx = (*BrutalSender)(nil) + +type BrutalSender struct { + rttStats congestion.RTTStatsProvider + bps congestion.ByteCount + maxDatagramSize congestion.ByteCount + pacer *Pacer + + packetInfoSlots [brutalPacketInfoSlotCount]brutalPacketInfo + ackRate float64 +} + +type brutalPacketInfo struct { + timestamp int64 + ackCount uint64 + lossCount uint64 +} + +func NewBrutalSender(bps uint64) *BrutalSender { + b := &BrutalSender{ + bps: congestion.ByteCount(bps), + maxDatagramSize: congestion.InitialPacketSize, + ackRate: 1, + } + b.pacer = NewPacer(func() congestion.ByteCount { + return congestion.ByteCount(float64(b.bps) / b.ackRate) + }) + return b +} + +func (b *BrutalSender) SetRTTStatsProvider(rttStats congestion.RTTStatsProvider) { + b.rttStats = rttStats +} + +func (b *BrutalSender) TimeUntilSend(bytesInFlight congestion.ByteCount) monotime.Time { + return b.pacer.TimeUntilSend() +} + +func (b *BrutalSender) HasPacingBudget(now monotime.Time) bool { + return b.pacer.Budget(now) >= b.maxDatagramSize +} + +func (b *BrutalSender) CanSend(bytesInFlight congestion.ByteCount) bool { + return bytesInFlight <= b.GetCongestionWindow() +} + +func (b *BrutalSender) GetCongestionWindow() congestion.ByteCount { + if b.rttStats == nil { + return brutalInitialCongestionWindow + } + rtt := b.rttStats.SmoothedRTT() + if rtt <= 0 { + return brutalInitialCongestionWindow + } + cwnd := congestion.ByteCount(float64(b.bps) * rtt.Seconds() * brutalCongestionWindowFactor / b.ackRate) + if cwnd < b.maxDatagramSize { + cwnd = b.maxDatagramSize + } + return cwnd +} + +func (b *BrutalSender) OnPacketSent(sentTime monotime.Time, bytesInFlight congestion.ByteCount, packetNumber congestion.PacketNumber, bytes congestion.ByteCount, isRetransmittable bool) { + b.pacer.SentPacket(sentTime, bytes) +} + +func (b *BrutalSender) OnPacketAcked(number congestion.PacketNumber, ackedBytes congestion.ByteCount, priorInFlight congestion.ByteCount, eventTime monotime.Time) { + // Brutal uses OnCongestionEventEx to update ACK rate from acked/lost packet counts. +} + +func (b *BrutalSender) OnCongestionEvent(number congestion.PacketNumber, lostBytes congestion.ByteCount, priorInFlight congestion.ByteCount) { + // Brutal uses OnCongestionEventEx to update ACK rate from acked/lost packet counts. +} + +func (b *BrutalSender) OnCongestionEventEx(priorInFlight congestion.ByteCount, eventTime monotime.Time, ackedPackets []congestion.AckedPacketInfo, lostPackets []congestion.LostPacketInfo) { + currentTimestamp := int64(time.Duration(eventTime) / time.Second) + slot := currentTimestamp % brutalPacketInfoSlotCount + if b.packetInfoSlots[slot].timestamp == currentTimestamp { + b.packetInfoSlots[slot].lossCount += uint64(len(lostPackets)) + b.packetInfoSlots[slot].ackCount += uint64(len(ackedPackets)) + } else { + b.packetInfoSlots[slot] = brutalPacketInfo{ + timestamp: currentTimestamp, + ackCount: uint64(len(ackedPackets)), + lossCount: uint64(len(lostPackets)), + } + } + b.updateAckRate(currentTimestamp) +} + +func (b *BrutalSender) SetMaxDatagramSize(size congestion.ByteCount) { + b.maxDatagramSize = size + b.pacer.SetMaxDatagramSize(size) +} + +func (b *BrutalSender) InSlowStart() bool { + return false +} + +func (b *BrutalSender) InRecovery() bool { + return false +} + +func (b *BrutalSender) MaybeExitSlowStart() {} + +func (b *BrutalSender) OnRetransmissionTimeout(packetsRetransmitted bool) {} + +func (b *BrutalSender) updateAckRate(currentTimestamp int64) { + minTimestamp := currentTimestamp - brutalPacketInfoSlotCount + var ackCount, lossCount uint64 + for _, info := range b.packetInfoSlots { + if info.timestamp < minTimestamp { + continue + } + ackCount += info.ackCount + lossCount += info.lossCount + } + if ackCount+lossCount < brutalMinSampleCount { + b.ackRate = 1 + return + } + rate := float64(ackCount) / float64(ackCount+lossCount) + if rate < brutalMinAckRate { + b.ackRate = brutalMinAckRate + return + } + b.ackRate = rate +}