From aea5ce4142a504366a388773dd1993039203636c Mon Sep 17 00:00:00 2001 From: wwqgtxx Date: Sun, 12 Jul 2026 22:28:43 +0800 Subject: [PATCH] feat: support shadowquic outbound and listener --- adapter/outbound/shadowquic.go | 302 ++++++++++++++++++++++ adapter/parser.go | 7 + constant/adapters.go | 3 + constant/metadata.go | 5 + docs/config.yaml | 51 ++++ go.mod | 2 + go.sum | 4 + listener/config/shadowquic.go | 44 ++++ listener/inbound/shadowquic.go | 132 ++++++++++ listener/inbound/shadowquic_test.go | 185 +++++++++++++ listener/inner/udp.go | 194 ++++++++++++++ listener/parse.go | 13 + listener/shadowquic/server.go | 238 +++++++++++++++++ transport/shadowquic/client.go | 106 ++++++++ transport/shadowquic/congestion.go | 162 ++++++++++++ transport/shadowquic/extension.go | 91 +++++++ transport/shadowquic/extension_test.go | 81 ++++++ transport/shadowquic/packet.go | 220 ++++++++++++++++ transport/shadowquic/protocol.go | 186 +++++++++++++ transport/shadowquic/quic_version.go | 284 ++++++++++++++++++++ transport/shadowquic/quic_version_test.go | 268 +++++++++++++++++++ transport/shadowquic/server.go | 206 +++++++++++++++ transport/shadowquic/state.go | 258 ++++++++++++++++++ transport/shadowquic/stream_conn.go | 62 +++++ 24 files changed, 3104 insertions(+) create mode 100644 adapter/outbound/shadowquic.go create mode 100644 listener/config/shadowquic.go create mode 100644 listener/inbound/shadowquic.go create mode 100644 listener/inbound/shadowquic_test.go create mode 100644 listener/inner/udp.go create mode 100644 listener/shadowquic/server.go create mode 100644 transport/shadowquic/client.go create mode 100644 transport/shadowquic/congestion.go create mode 100644 transport/shadowquic/extension.go create mode 100644 transport/shadowquic/extension_test.go create mode 100644 transport/shadowquic/packet.go create mode 100644 transport/shadowquic/protocol.go create mode 100644 transport/shadowquic/quic_version.go create mode 100644 transport/shadowquic/quic_version_test.go create mode 100644 transport/shadowquic/server.go create mode 100644 transport/shadowquic/state.go create mode 100644 transport/shadowquic/stream_conn.go diff --git a/adapter/outbound/shadowquic.go b/adapter/outbound/shadowquic.go new file mode 100644 index 000000000..8208ed665 --- /dev/null +++ b/adapter/outbound/shadowquic.go @@ -0,0 +1,302 @@ +package outbound + +import ( + "context" + "net" + "net/netip" + "strconv" + "time" + + "github.com/metacubex/mihomo/component/ca" + "github.com/metacubex/mihomo/component/dialer" + C "github.com/metacubex/mihomo/constant" + "github.com/metacubex/mihomo/ntp" + "github.com/metacubex/mihomo/transport/shadowquic" + "github.com/metacubex/mihomo/transport/tuic" + + "github.com/metacubex/jls-quic-go" + "github.com/metacubex/jls-tls" +) + +type ShadowQuic struct { + *Base + option *ShadowQuicOption + client *shadowquic.Client + + quicConfig *quic.Config + tlsConfig *tls.Config +} + +type ShadowQuicOption struct { + BasicOption + Name string `proxy:"name"` + Server string `proxy:"server"` + Port int `proxy:"port"` + Username string `proxy:"username,omitempty"` + Password string `proxy:"password,omitempty"` + SNI string `proxy:"sni,omitempty"` + ALPN []string `proxy:"alpn,omitempty"` + QUICVersions []string `proxy:"quic-versions,omitempty"` + UDPOverStream bool `proxy:"udp-over-stream,omitempty"` + ZeroRTT bool `proxy:"zero-rtt,omitempty"` + KeepAliveInterval int `proxy:"keep-alive-interval,omitempty"` + CongestionController string `proxy:"congestion-controller,omitempty"` + CWND int `proxy:"cwnd,omitempty"` + BBRProfile string `proxy:"bbr-profile,omitempty"` + ReceiveWindowConn int `proxy:"recv-window-conn,omitempty"` + ReceiveWindow int `proxy:"recv-window,omitempty"` + DisableMTUDiscovery bool `proxy:"disable-mtu-discovery,omitempty"` + MaxDatagramFrameSize int `proxy:"max-datagram-frame-size,omitempty"` + MaxOpenStreams int `proxy:"max-open-streams,omitempty"` +} + +func (s *ShadowQuic) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) { + conn, err := s.client.DialContext(ctx, metadata) + if err != nil { + return nil, err + } + return NewConn(conn, s), nil +} + +func (s *ShadowQuic) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (C.PacketConn, error) { + if err := s.ResolveUDP(ctx, metadata); err != nil { + return nil, err + } + pc, err := s.client.ListenPacket(ctx, metadata) + if err != nil { + return nil, err + } + return NewPacketConn(pc, s), nil +} + +func (s *ShadowQuic) Close() error { + if s.client != nil { + return s.client.Close() + } + return nil +} + +func (s *ShadowQuic) ProxyInfo() C.ProxyInfo { + info := s.Base.ProxyInfo() + info.DialerProxy = s.option.DialerProxy + return info +} + +func NewShadowQuic(option ShadowQuicOption) (*ShadowQuic, error) { + addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port)) + serverName := option.SNI + if serverName == "" { + serverName = option.Server + } + + tlsConfig := &tls.Config{ + ServerName: serverName, + MinVersion: tls.VersionTLS13, + Time: ntp.Now, + RootCAs: ca.GetCertPool(), + } + if option.ALPN != nil { + tlsConfig.NextProtos = option.ALPN + } else { + tlsConfig.NextProtos = []string{"h3"} + } + tlsConfig.JLSConfig = &tls.JLSConfig{ + Enable: true, + User: tls.JLSUser{ + Username: option.Username, + Password: option.Password, + }, + } + if option.ZeroRTT { + // DialEarly can only send 0-RTT data after TLS has cached a session + // ticket from an earlier connection to this server. + tlsConfig.ClientSessionCache = tls.NewLRUClientSessionCache(1) + } + + if option.MaxDatagramFrameSize == 0 { + option.MaxDatagramFrameSize = 1400 + } + if option.MaxOpenStreams == 0 { + option.MaxOpenStreams = 1024 + } + if option.CWND == 0 { + option.CWND = 32 + } + + quicVersions := shadowquic.DefaultQUICVersions() + if len(option.QUICVersions) > 0 { + parsedVersions, _, err := shadowquic.ParseQUICVersionProfile(option.QUICVersions) + if err != nil { + return nil, err + } + quicVersions = parsedVersions + } + + quicConfig := &quic.Config{ + Versions: quicVersions, + InitialStreamReceiveWindow: uint64(option.ReceiveWindowConn), + MaxStreamReceiveWindow: uint64(option.ReceiveWindowConn), + InitialConnectionReceiveWindow: uint64(option.ReceiveWindow), + MaxConnectionReceiveWindow: uint64(option.ReceiveWindow), + MaxIncomingStreams: int64(option.MaxOpenStreams), + MaxIncomingUniStreams: int64(option.MaxOpenStreams), + DisablePathMTUDiscovery: option.DisableMTUDiscovery, + MaxDatagramFrameSize: int64(option.MaxDatagramFrameSize), + EnableDatagrams: true, + } + if option.KeepAliveInterval > 0 { + quicConfig.KeepAlivePeriod = time.Duration(option.KeepAliveInterval) * time.Millisecond + } + if option.ReceiveWindowConn == 0 { + quicConfig.InitialStreamReceiveWindow = tuic.DefaultStreamReceiveWindow / 10 + quicConfig.MaxStreamReceiveWindow = tuic.DefaultStreamReceiveWindow + } + if option.ReceiveWindow == 0 { + quicConfig.InitialConnectionReceiveWindow = tuic.DefaultConnectionReceiveWindow / 10 + quicConfig.MaxConnectionReceiveWindow = tuic.DefaultConnectionReceiveWindow + } + + outbound := &ShadowQuic{ + Base: NewBase(BaseOption{ + Name: option.Name, + Addr: addr, + Type: C.ShadowQuic, + ProviderName: option.ProviderName, + UDP: true, + Interface: option.Interface, + RoutingMark: option.RoutingMark, + Prefer: option.IPVersion, + }), + option: &option, + quicConfig: quicConfig, + tlsConfig: tlsConfig, + } + outbound.dialer = option.NewDialer(outbound.DialOptions()) + outbound.client = shadowquic.NewClient(&shadowquic.ClientOption{ + UDPOverStream: option.UDPOverStream, + Dial: func(ctx context.Context) (*quic.Conn, error) { + _, quicConn, err := dialShadowQuic(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 + }, + }) + + return outbound, nil +} + +type shadowQuicPacketDialer interface { + ListenPacket(ctx context.Context, network, address string, rAddrPort netip.AddrPort) (net.PacketConn, error) +} + +func dialShadowQuic(ctx context.Context, address string, opts []dialer.Option, pDialer shadowQuicPacketDialer, tlsConf *tls.Config, conf *quic.Config, early bool) (net.PacketConn, *quic.Conn, error) { + monitorAuthEarly := early + if _, err := netip.ParseAddrPort(address); err != nil { + // A hostname can resolve to multiple candidates. Authenticate each one + // before the dialer selects it, so a failed candidate can fall back. + monitorAuthEarly = false + } + d := dialer.NewDialer( + dialer.WithOptions(opts...), + dialer.WithNetDialer(dialer.NetDialerFunc(func(ctx context.Context, network, address string) (net.Conn, error) { + addrPort, err := netip.ParseAddrPort(address) + if err != nil { + return nil, err + } + udpAddr := net.UDPAddrFromAddrPort(addrPort) + packetConn, err := pDialer.ListenPacket(ctx, "udp", "", udpAddr.AddrPort()) + if err != nil { + return nil, err + } + transport := quic.Transport{Conn: packetConn} + transport.SetCreatedConn(true) + transport.SetSingleUse(true) + + var quicConn *quic.Conn + if early { + quicConn, err = transport.DialEarly(ctx, udpAddr, tlsConf, conf) + } else { + quicConn, err = transport.Dial(ctx, udpAddr, tlsConf, conf) + } + if err != nil { + _ = packetConn.Close() + return nil, err + } + if err := monitorShadowQuicJLSAuth(quicConn, packetConn, tlsConf, monitorAuthEarly); err != nil { + return nil, err + } + return shadowQuicNetConn{Conn: quicConn, pc: packetConn}, nil + })), + ) + c, err := d.DialContext(ctx, "udp", address) + if err != nil { + return nil, nil, err + } + nc := c.(shadowQuicNetConn) + return nc.pc, nc.Conn, nil +} + +func monitorShadowQuicJLSAuth(quicConn *quic.Conn, packetConn net.PacketConn, tlsConf *tls.Config, early bool) error { + if tlsConf == nil || tlsConf.JLSConfig == nil || !tlsConf.JLSConfig.Enable { + return nil + } + closeConn := func() { + _ = quicConn.CloseWithError(0, "") + _ = packetConn.Close() + } + checkAuth := func() bool { + return quicConn.ConnectionState().TLS.JLS.Authenticated + } + if !early { + if checkAuth() { + return nil + } + closeConn() + return tls.ErrJLSAuthFailed + } + go func() { + select { + case <-quicConn.HandshakeComplete(): + if !checkAuth() { + closeConn() + } + case <-quicConn.Context().Done(): + } + }() + return nil +} + +type shadowQuicNetConn struct { + *quic.Conn + pc net.PacketConn +} + +func (q shadowQuicNetConn) Close() error { + err := q.Conn.CloseWithError(0, "") + _ = q.pc.Close() + return err +} + +func (q shadowQuicNetConn) Read([]byte) (int, error) { + panic("should not call Read on shadowQuicNetConn") +} + +func (q shadowQuicNetConn) Write([]byte) (int, error) { + panic("should not call Write on shadowQuicNetConn") +} + +func (q shadowQuicNetConn) SetDeadline(time.Time) error { + panic("should not call SetDeadline on shadowQuicNetConn") +} + +func (q shadowQuicNetConn) SetReadDeadline(time.Time) error { + panic("should not call SetReadDeadline on shadowQuicNetConn") +} + +func (q shadowQuicNetConn) SetWriteDeadline(time.Time) error { + panic("should not call SetWriteDeadline on shadowQuicNetConn") +} + +var _ net.Conn = shadowQuicNetConn{} diff --git a/adapter/parser.go b/adapter/parser.go index 651f4cc0b..9599616a1 100644 --- a/adapter/parser.go +++ b/adapter/parser.go @@ -111,6 +111,13 @@ func ParseProxy(mapping map[string]any, options ...ProxyOption) (C.Proxy, error) break } proxy, err = outbound.NewTuic(*tuicOption) + case "shadowquic": + shadowQuicOption := &outbound.ShadowQuicOption{BasicOption: basicOption} + err = decoder.Decode(mapping, shadowQuicOption) + if err != nil { + break + } + proxy, err = outbound.NewShadowQuic(*shadowQuicOption) case "gost-relay": relayOption := &outbound.GostRelayOption{BasicOption: basicOption} err = decoder.Decode(mapping, relayOption) diff --git a/constant/adapters.go b/constant/adapters.go index 5c282b613..ddcdbead1 100644 --- a/constant/adapters.go +++ b/constant/adapters.go @@ -49,6 +49,7 @@ const ( Sudoku Masque TrustTunnel + ShadowQuic OpenVPN Tailscale GostRelay @@ -227,6 +228,8 @@ func (at AdapterType) String() string { return "Masque" case TrustTunnel: return "TrustTunnel" + case ShadowQuic: + return "ShadowQuic" case OpenVPN: return "OpenVPN" case Tailscale: diff --git a/constant/metadata.go b/constant/metadata.go index ea5775366..76d1e0e5c 100644 --- a/constant/metadata.go +++ b/constant/metadata.go @@ -42,6 +42,7 @@ const ( MIERU SUDOKU TRUSTTUNNEL + SHADOWQUIC INNER ) @@ -121,6 +122,8 @@ func (t Type) String() string { return "Sudoku" case TRUSTTUNNEL: return "TrustTunnel" + case SHADOWQUIC: + return "ShadowQuic" case INNER: return "Inner" default: @@ -169,6 +172,8 @@ func ParseType(t string) (*Type, error) { res = SUDOKU case "TRUSTTUNNEL": res = TRUSTTUNNEL + case "SHADOWQUIC": + res = SHADOWQUIC case "INNER": res = INNER default: diff --git a/docs/config.yaml b/docs/config.yaml index 82ef053c7..1c41fb39a 100644 --- a/docs/config.yaml +++ b/docs/config.yaml @@ -1418,6 +1418,28 @@ proxies: # socks5 # udp-over-stream: false # udp-over-stream-version: 1 + # shadowquic + - name: shadowquic + server: www.example.com + port: 10443 + type: shadowquic + username: username + password: password + # sni: example.com + # alpn: [h3] + # quic-versions: [v1] # support v1/v2, default v1 + # udp-over-stream: false # UDP over stream, default false + # 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" + # cwnd: 10 # default: 32 + # bbr-profile: "" # Available: "standard", "conservative", "aggressive". Default: "standard" + # max-datagram-frame-size: 1400 + # max-open-streams: 1024 + # recv-window-conn: 0 + # recv-window: 0 + # disable-mtu-discovery: false + # ShadowsocksR # The supported ciphers (encryption methods): all stream ciphers in ss # The supported obfses: @@ -2092,6 +2114,35 @@ listeners: # - h3 # max-udp-relay-packet-size: 1500 + - name: shadowquic-in-1 + type: shadowquic + port: 10822 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503 + listen: 0.0.0.0 + # routing-mark: 0 # 为监听socket设置routing-mark(仅支持linux) + # rule: sub-rule-name1 # 默认使用 rules,如果未找到 sub-rule 则直接使用 rules + # proxy: proxy # 如果不为空则直接将该入站流量交由指定 proxy 处理 (当 proxy 不为空时,这里的 proxy 名称必须合法,否则会出错) + users: + - username: username + password: password + jls-upstream: + addr: www.example.com:443 # 未通过 JLS 认证的连接将转发到该 QUIC 伪装上游 + # sni: example.com # JLS 伪装目标 SNI,留空时从 addr 推导 + # proxy: proxy # 伪装上游使用的代理 + # rate-limit: 0 # 转发限速,单位 bit/s,0 表示不限速 + # quic-version-probe: false # 在首次连接时探测伪装上游版本 + # alpn: + # - h3 + # quic-versions: [v1] # 本机手动配置及探测失败时的版本;支持 v1/v2 + # zero-rtt: true + # congestion-controller: bbr + # cwnd: 10 # default: 32 + # bbr-profile: "" # Available: "standard", "conservative", "aggressive". Default: "standard" + # max-idle-time: 30000 + # max-datagram-frame-size: 1400 + # recv-window-conn: 0 + # recv-window: 0 + # disable-mtu-discovery: false + - name: tunnel-in-1 type: tunnel port: 10816 # 支持使用ports格式,例如200,302 or 200,204,401-429,501-503 diff --git a/go.mod b/go.mod index 4e345aa1f..81051bf2e 100644 --- a/go.mod +++ b/go.mod @@ -23,6 +23,8 @@ require ( github.com/metacubex/fswatch v0.1.1 github.com/metacubex/gopacket v1.1.20-0.20230608035415-7e2f98a3e759 github.com/metacubex/http v0.1.6 + github.com/metacubex/jls-quic-go v0.0.0-20260712113821-d34e6f9b4c7f + github.com/metacubex/jls-tls v0.0.0-20260712085721-6ea48ea9f069 github.com/metacubex/kcp-go v0.0.0-20260105040817-550693377604 github.com/metacubex/mhurl v0.1.0 github.com/metacubex/mlkem v0.1.0 diff --git a/go.sum b/go.sum index 18ddab854..4b010327d 100644 --- a/go.sum +++ b/go.sum @@ -131,6 +131,10 @@ github.com/metacubex/hpke v0.1.0 h1:gu2jUNhraehWi0P/z5HX2md3d7L1FhPQE6/Q0E9r9xQ= github.com/metacubex/hpke v0.1.0/go.mod h1:vfDm6gfgrwlXUxKDkWbcE44hXtmc1uxLDm2BcR11b3U= github.com/metacubex/http v0.1.6 h1:xvXuvXMCMxCWMF5nEJF4yiKvXL+p2atWMzs37e80m1I= github.com/metacubex/http v0.1.6/go.mod h1:Nxx0zZAo2AhRfanyL+fmmK6ACMtVsfpwIl1aFAik2Eg= +github.com/metacubex/jls-quic-go v0.0.0-20260712113821-d34e6f9b4c7f h1:ywMFrpfRTU6oiRYhn2PGefm/RWdtdwsD13sDFmrJ6+s= +github.com/metacubex/jls-quic-go v0.0.0-20260712113821-d34e6f9b4c7f/go.mod h1:fXVJbX1dv67OpH+jGaecl7DYRj6KDLwOya8OSUPBIxo= +github.com/metacubex/jls-tls v0.0.0-20260712085721-6ea48ea9f069 h1:oZe46oTeFmoVsBSjGJRwSg7sD4k1EU3DnwoukKiu+bY= +github.com/metacubex/jls-tls v0.0.0-20260712085721-6ea48ea9f069/go.mod h1:mmqs889W/TqPlfNRDa2UyJvRiLyiTJIEnWHkcj3SKB8= github.com/metacubex/jsonv2 v0.0.0-20260518173308-f4597c22f1df h1:S0vBzqjXok24VopstOgPd1JdgglW9tXehrqvwpQWbQ8= github.com/metacubex/jsonv2 v0.0.0-20260518173308-f4597c22f1df/go.mod h1:F4sVXat6QjPXkNsKRDyyG3BhSkxPFFnRPEIwmmyCgbg= github.com/metacubex/kcp-go v0.0.0-20260105040817-550693377604 h1:hJwCVlE3ojViC35MGHB+FBr8TuIf3BUFn2EQ1VIamsI= diff --git a/listener/config/shadowquic.go b/listener/config/shadowquic.go new file mode 100644 index 000000000..7ab8fd0e2 --- /dev/null +++ b/listener/config/shadowquic.go @@ -0,0 +1,44 @@ +package config + +import ( + "encoding/json" + + "github.com/metacubex/mihomo/listener/sing" +) + +type ShadowQuicUser struct { + Username string `yaml:"username" json:"username"` + Password string `yaml:"password" json:"password"` +} + +type ShadowQuicJLSUpstream struct { + Addr string `yaml:"addr" json:"addr"` + SNI string `yaml:"sni" json:"sni,omitempty"` + Proxy string `yaml:"proxy" json:"proxy,omitempty"` + RateLimit uint64 `yaml:"rate-limit" json:"rate-limit,omitempty"` + QUICVersionProbe bool `yaml:"quic-version-probe" json:"quic-version-probe,omitempty"` +} + +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"` +} + +func (s ShadowQuicServer) String() string { + b, _ := json.Marshal(s) + return string(b) +} diff --git a/listener/inbound/shadowquic.go b/listener/inbound/shadowquic.go new file mode 100644 index 000000000..63d84960e --- /dev/null +++ b/listener/inbound/shadowquic.go @@ -0,0 +1,132 @@ +package inbound + +import ( + "strings" + + "github.com/metacubex/mihomo/common/utils" + C "github.com/metacubex/mihomo/constant" + LC "github.com/metacubex/mihomo/listener/config" + "github.com/metacubex/mihomo/listener/shadowquic" + "github.com/metacubex/mihomo/log" +) + +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"` +} + +type ShadowQuicUser struct { + Username string `inbound:"username"` + Password string `inbound:"password"` +} + +type ShadowQuicJLSUpstream struct { + Addr string `inbound:"addr"` + SNI string `inbound:"sni,omitempty"` + Proxy string `inbound:"proxy,omitempty"` + RateLimit uint64 `inbound:"rate-limit,omitempty"` + QUICVersionProbe bool `inbound:"quic-version-probe,omitempty"` +} + +func (u ShadowQuicUser) Build() LC.ShadowQuicUser { + return LC.ShadowQuicUser{ + Username: u.Username, + Password: u.Password, + } +} + +func (u ShadowQuicJLSUpstream) Build() LC.ShadowQuicJLSUpstream { + return LC.ShadowQuicJLSUpstream{ + Addr: u.Addr, + SNI: u.SNI, + Proxy: u.Proxy, + RateLimit: u.RateLimit, + QUICVersionProbe: u.QUICVersionProbe, + } +} + +func (o ShadowQuicOption) Equal(config C.InboundConfig) bool { + return optionToString(o) == optionToString(config) +} + +type ShadowQuic struct { + *Base + config *ShadowQuicOption + l *shadowquic.Listener + ss LC.ShadowQuicServer +} + +func NewShadowQuic(options *ShadowQuicOption) (*ShadowQuic, error) { + base, err := NewBase(&options.BaseOption) + if err != nil { + return nil, err + } + return &ShadowQuic{ + 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(), + }, + }, nil +} + +func (s *ShadowQuic) Config() C.InboundConfig { + return s.config +} + +func (s *ShadowQuic) Address() string { + var addrList []string + if s.l != nil { + for _, addr := range s.l.AddrList() { + addrList = append(addrList, addr.String()) + } + } + return strings.Join(addrList, ",") +} + +func (s *ShadowQuic) Listen(tunnel C.Tunnel) error { + var err error + s.l, err = shadowquic.New(s.ss, s.ListenConfig(), tunnel, s.Additions()...) + if err != nil { + return err + } + log.Infoln("ShadowQuic[%s] proxy listening at: %s", s.Name(), s.Address()) + return nil +} + +func (s *ShadowQuic) Close() error { + if s.l != nil { + return s.l.Close() + } + return nil +} + +var _ C.InboundListener = (*ShadowQuic)(nil) diff --git a/listener/inbound/shadowquic_test.go b/listener/inbound/shadowquic_test.go new file mode 100644 index 000000000..baee1fc26 --- /dev/null +++ b/listener/inbound/shadowquic_test.go @@ -0,0 +1,185 @@ +package inbound_test + +import ( + "encoding/binary" + "errors" + "fmt" + "net" + "net/netip" + "testing" + "time" + + "github.com/metacubex/mihomo/adapter/outbound" + C "github.com/metacubex/mihomo/constant" + "github.com/metacubex/mihomo/listener/inbound" + + "github.com/metacubex/jls-quic-go" + "github.com/stretchr/testify/assert" +) + +func TestInboundShadowQuic(t *testing.T) { + for _, test := range []struct { + name string + clientVersion string + serverVersion string + probedVersion quic.Version + }{ + {name: "v1", clientVersion: "v1", serverVersion: "v1"}, + {name: "v2", clientVersion: "v2", serverVersion: "v2"}, + {name: "v1 with server probe", clientVersion: "v1", serverVersion: "v2", probedVersion: quic.Version1}, + {name: "v2 with server probe", clientVersion: "v2", serverVersion: "v1", probedVersion: quic.Version2}, + } { + test := test + t.Run(test.name, func(t *testing.T) { + t.Parallel() + testInboundShadowQuic(t, test.clientVersion, test.serverVersion, test.probedVersion) + }) + } +} + +func testInboundShadowQuic(t *testing.T, clientVersion, serverVersion string, probedVersion quic.Version) { + const username = "shadowquic-user" + const password = "shadowquic-password" + + inboundOptions := inbound.ShadowQuicOption{ + BaseOption: inbound.BaseOption{ + NameStr: "shadowquic_inbound", + Listen: "127.0.0.1", + Port: "0", + }, + ALPN: []string{"h3"}, + QUICVersions: []string{serverVersion}, + ZeroRTT: true, + MaxIdleTime: 30000, + MaxDatagramFrameSize: 1400, + Users: []inbound.ShadowQuicUser{{Username: username, Password: password}}, + JLSUpstream: inbound.ShadowQuicJLSUpstream{Addr: "127.0.0.1:1"}, + } + var probeResult <-chan error + var probeHandler func(C.UDPPacket, *C.Metadata) + if probedVersion != 0 { + upstreamAddr, result, handler := newShadowQuicVersionProbeUpstream(probedVersion) + probeResult = result + probeHandler = handler + inboundOptions.JLSUpstream = inbound.ShadowQuicJLSUpstream{ + Addr: upstreamAddr, + Proxy: "shadowquic-probe-proxy", + QUICVersionProbe: true, + } + } + in, err := inbound.NewShadowQuic(&inboundOptions) + if !assert.NoError(t, err) { + return + } + + tunnel := NewHttpTestTunnel() + defer tunnel.Close() + if probeHandler != nil { + tunnel.HandleUDPPacketFn = probeHandler + } else { + tunnel.HandleUDPPacketFn = func(packet C.UDPPacket, metadata *C.Metadata) { + packet.Drop() + t.Errorf("authenticated ShadowQUIC connection unexpectedly accessed JLS upstream %s", metadata.RemoteAddress()) + } + } + + if !assert.NoError(t, in.Listen(tunnel)) { + return + } + defer in.Close() + + addrPort, err := netip.ParseAddrPort(in.Address()) + if !assert.NoError(t, err) { + return + } + + outboundOptions := outbound.ShadowQuicOption{ + Name: "shadowquic_outbound", + Server: addrPort.Addr().String(), + Port: int(addrPort.Port()), + ALPN: []string{"h3"}, + QUICVersions: []string{clientVersion}, + ZeroRTT: true, + MaxDatagramFrameSize: 1400, + Username: username, + Password: password, + } + outboundOptions.DialerForAPI = tunnel.NewDialer() + outboundOptions.TunnelForAPI = tunnel + out, err := outbound.NewShadowQuic(outboundOptions) + if !assert.NoError(t, err) { + return + } + defer out.Close() + + tunnel.DoTest(t, out) + if probeResult != nil { + select { + case err := <-probeResult: + assert.NoError(t, err) + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for ShadowQUIC version probe") + } + } +} + +func newShadowQuicVersionProbeUpstream(version quic.Version) (string, <-chan error, func(C.UDPPacket, *C.Metadata)) { + result := make(chan error, 1) + handler := func(packet C.UDPPacket, metadata *C.Metadata) { + defer packet.Drop() + var probeErr error + if metadata.Type != C.INNER || metadata.NetWork != C.UDP { + probeErr = fmt.Errorf("version probe type/network = %s/%s, want Inner/udp", metadata.Type, metadata.NetWork) + } else if metadata.RemoteAddress() != "127.0.0.1:443" { + probeErr = fmt.Errorf("version probe destination = %s", metadata.RemoteAddress()) + } else if metadata.SpecialProxy != "shadowquic-probe-proxy" { + probeErr = fmt.Errorf("version probe proxy = %q", metadata.SpecialProxy) + } + response, err := composeShadowQuicVersionNegotiation(packet.Data(), version) + if err == nil { + _, err = packet.WriteBack(response, &net.UDPAddr{IP: net.IPv4(192, 0, 2, 1), Port: 443}) + } + if probeErr == nil { + probeErr = err + } + select { + case result <- probeErr: + default: + } + } + return "127.0.0.1:443", result, handler +} + +func composeShadowQuicVersionNegotiation(probe []byte, version quic.Version) ([]byte, error) { + if len(probe) < 7 { + return nil, errors.New("short QUIC version probe") + } + if probe[0]&0x80 == 0 { + return nil, errors.New("QUIC version probe does not use a long header") + } + probeVersion := quic.Version(binary.BigEndian.Uint32(probe[1:5])) + if probeVersion == 0 || probeVersion == quic.Version1 || probeVersion == quic.Version2 { + return nil, fmt.Errorf("QUIC version probe uses non-probe version %#x", probeVersion) + } + offset := 5 + dcidLen := int(probe[offset]) + offset++ + if offset+dcidLen >= len(probe) { + return nil, errors.New("invalid QUIC version probe destination connection ID") + } + dcid := probe[offset : offset+dcidLen] + offset += dcidLen + scidLen := int(probe[offset]) + offset++ + if offset+scidLen > len(probe) { + return nil, errors.New("invalid QUIC version probe source connection ID") + } + scid := probe[offset : offset+scidLen] + + response := []byte{0x80, 0, 0, 0, 0, byte(len(scid))} + response = append(response, scid...) + response = append(response, byte(len(dcid))) + response = append(response, dcid...) + response = binary.BigEndian.AppendUint32(response, uint32(version)) + return response, nil +} diff --git a/listener/inner/udp.go b/listener/inner/udp.go new file mode 100644 index 000000000..692c2f7ac --- /dev/null +++ b/listener/inner/udp.go @@ -0,0 +1,194 @@ +package inner + +import ( + "errors" + "fmt" + "io" + "net" + "os" + "sync" + "sync/atomic" + "time" + + "github.com/metacubex/mihomo/adapter/inbound" + "github.com/metacubex/mihomo/common/net/deadline" + "github.com/metacubex/mihomo/common/pool" + C "github.com/metacubex/mihomo/constant" + "github.com/metacubex/mihomo/transport/socks5" +) + +const innerUDPQueueSize = 128 + +var innerUDPConnID atomic.Uint64 + +type innerUDPAddr struct { + network string + address string +} + +func (a innerUDPAddr) Network() string { return a.network } +func (a innerUDPAddr) String() string { return a.address } + +type innerUDPDatagram struct { + data []byte + addr net.Addr +} + +type innerUDPPacketConn struct { + tunnel C.Tunnel + proxy string + localAddr net.Addr + readChan chan innerUDPDatagram + done chan struct{} + closeOnce sync.Once + mu sync.Mutex + closed bool + + readDeadline deadline.PipeDeadline + writeDeadline deadline.PipeDeadline +} + +func HandleUdp(tunnel C.Tunnel, network, address, proxy string) (net.PacketConn, net.Addr, error) { + if tunnel == nil { + return nil, nil, fmt.Errorf("tunnel uninitialized") + } + switch network { + case "udp", "udp4", "udp6": + default: + return nil, nil, fmt.Errorf("unsupported network %s", network) + } + if socks5.ParseAddr(address) == nil { + return nil, nil, fmt.Errorf("invalid target address %s", address) + } + + id := innerUDPConnID.Add(1) + conn := &innerUDPPacketConn{ + tunnel: tunnel, + proxy: proxy, + localAddr: innerUDPAddr{network: network, address: fmt.Sprintf("inner-udp-%d", id)}, + readChan: make(chan innerUDPDatagram, innerUDPQueueSize), + done: make(chan struct{}), + readDeadline: deadline.MakePipeDeadline(), + writeDeadline: deadline.MakePipeDeadline(), + } + return conn, innerUDPAddr{network: network, address: address}, nil +} + +func (c *innerUDPPacketConn) ReadFrom(p []byte) (int, net.Addr, error) { + select { + case <-c.done: + return 0, nil, net.ErrClosed + case <-c.readDeadline.Wait(): + return 0, nil, os.ErrDeadlineExceeded + case datagram := <-c.readChan: + n := copy(p, datagram.data) + _ = pool.Put(datagram.data) + if n < len(datagram.data) { + return n, datagram.addr, io.ErrShortBuffer + } + return n, datagram.addr, nil + } +} + +func (c *innerUDPPacketConn) WriteTo(p []byte, addr net.Addr) (int, error) { + if addr == nil { + return 0, errors.New("missing target address") + } + select { + case <-c.done: + return 0, net.ErrClosed + case <-c.writeDeadline.Wait(): + return 0, os.ErrDeadlineExceeded + default: + } + + target := socks5.ParseAddr(addr.String()) + if target == nil { + return 0, fmt.Errorf("invalid target address %s", addr) + } + data := pool.Get(len(p)) + copy(data, p) + udpPacket := &innerUDPPacket{conn: c, data: data} + packet, metadata := inbound.NewPacket(target, udpPacket, C.INNER) + metadata.DNSMode = C.DNSNormal + metadata.Process = C.MihomoName + metadata.SpecialProxy = c.proxy + c.tunnel.HandleUDPPacket(packet, metadata) + return len(p), nil +} + +func (c *innerUDPPacketConn) Close() error { + c.closeOnce.Do(func() { + c.mu.Lock() + c.closed = true + close(c.done) + for { + select { + case datagram := <-c.readChan: + _ = pool.Put(datagram.data) + default: + c.mu.Unlock() + return + } + } + }) + return nil +} + +func (c *innerUDPPacketConn) LocalAddr() net.Addr { return c.localAddr } + +func (c *innerUDPPacketConn) SetDeadline(t time.Time) error { + c.readDeadline.Set(t) + c.writeDeadline.Set(t) + return nil +} + +func (c *innerUDPPacketConn) SetReadDeadline(t time.Time) error { + c.readDeadline.Set(t) + return nil +} + +func (c *innerUDPPacketConn) SetWriteDeadline(t time.Time) error { + c.writeDeadline.Set(t) + return nil +} + +func (c *innerUDPPacketConn) writeBack(data []byte, addr net.Addr) (int, error) { + payload := pool.Get(len(data)) + copy(payload, data) + + c.mu.Lock() + defer c.mu.Unlock() + if c.closed { + _ = pool.Put(payload) + return 0, net.ErrClosed + } + select { + case c.readChan <- innerUDPDatagram{data: payload, addr: addr}: + default: + _ = pool.Put(payload) + } + return len(data), nil +} + +type innerUDPPacket struct { + conn *innerUDPPacketConn + data []byte +} + +func (p *innerUDPPacket) Data() []byte { return p.data } + +func (p *innerUDPPacket) WriteBack(data []byte, addr net.Addr) (int, error) { + return p.conn.writeBack(data, addr) +} + +func (p *innerUDPPacket) LocalAddr() net.Addr { return p.conn.localAddr } +func (p *innerUDPPacket) InAddr() net.Addr { return p.conn.localAddr } + +func (p *innerUDPPacket) Drop() { + _ = pool.Put(p.data) + p.data = nil +} + +var _ net.PacketConn = (*innerUDPPacketConn)(nil) +var _ C.UDPPacketInAddr = (*innerUDPPacket)(nil) diff --git a/listener/parse.go b/listener/parse.go index 65b6ea004..1e155c62d 100644 --- a/listener/parse.go +++ b/listener/parse.go @@ -134,6 +134,19 @@ func ParseListener(mapping map[string]any) (C.InboundListener, error) { return nil, err } listener, err = IN.NewTuic(tuicOption) + case "shadowquic": + shadowQuicOption := &IN.ShadowQuicOption{ + MaxIdleTime: 30000, + ALPN: []string{"h3"}, + MaxDatagramFrameSize: 1400, + CongestionController: "bbr", + ZeroRTT: true, + } + err = decoder.Decode(mapping, shadowQuicOption) + if err != nil { + return nil, err + } + listener, err = IN.NewShadowQuic(shadowQuicOption) case "anytls": anytlsOption := &IN.AnyTLSOption{} err = decoder.Decode(mapping, anytlsOption) diff --git a/listener/shadowquic/server.go b/listener/shadowquic/server.go new file mode 100644 index 000000000..49afb9d36 --- /dev/null +++ b/listener/shadowquic/server.go @@ -0,0 +1,238 @@ +package shadowquic + +import ( + "context" + "errors" + "net" + "net/netip" + "strings" + "time" + + "github.com/metacubex/mihomo/adapter/inbound" + "github.com/metacubex/mihomo/common/sockopt" + "github.com/metacubex/mihomo/component/ca" + C "github.com/metacubex/mihomo/constant" + LC "github.com/metacubex/mihomo/listener/config" + "github.com/metacubex/mihomo/listener/inner" + "github.com/metacubex/mihomo/listener/sing" + "github.com/metacubex/mihomo/log" + "github.com/metacubex/mihomo/ntp" + "github.com/metacubex/mihomo/transport/shadowquic" + "github.com/metacubex/mihomo/transport/socks5" + "github.com/metacubex/mihomo/transport/tuic" + + "github.com/metacubex/jls-quic-go" + "github.com/metacubex/jls-tls" +) + +const ServerMaxIncomingStreams = (1 << 32) - 1 + +type Listener struct { + closed bool + config LC.ShadowQuicServer + udpListeners []net.PacketConn + servers []*shadowquic.Server +} + +func New(config LC.ShadowQuicServer, lc C.InboundListenConfig, tunnel C.Tunnel, additions ...inbound.Addition) (*Listener, error) { + if strings.TrimSpace(config.JLSUpstream.Addr) == "" { + return nil, errors.New("shadowquic: jls-upstream.addr is required") + } + if len(additions) == 0 { + additions = []inbound.Addition{ + inbound.WithInName("DEFAULT-SHADOWQUIC"), + inbound.WithSpecialRules(""), + } + } + h, err := sing.NewListenerHandler(sing.ListenerConfig{ + Tunnel: tunnel, + Type: C.SHADOWQUIC, + Additions: additions, + MuxOption: config.MuxOption, + }) + if err != nil { + return nil, err + } + + tlsConfig := &tls.Config{ + Time: ntp.Now, + MinVersion: tls.VersionTLS13, + } + // JLS authenticates the peer, so this generated certificate only carries the TLS handshake. + certificate, privateKey, _, err := ca.NewRandomTLSKeyPair(ca.KeyPairTypeP256) + if err != nil { + return nil, err + } + cert, err := tls.X509KeyPair([]byte(certificate), []byte(privateKey)) + if err != nil { + return nil, err + } + tlsConfig.Certificates = []tls.Certificate{cert} + if len(config.ALPN) > 0 { + tlsConfig.NextProtos = config.ALPN + } else { + tlsConfig.NextProtos = []string{"h3"} + } + users := make([]tls.JLSUser, 0, len(config.Users)) + for _, user := range config.Users { + users = append(users, tls.JLSUser{ + Username: user.Username, + Password: user.Password, + }) + } + serverName := config.JLSUpstream.SNI + if serverName == "" { + serverName = defaultJLSServerName(config.JLSUpstream.Addr) + } + tlsConfig.JLSConfig = &tls.JLSConfig{ + Enable: true, + Users: users, + ServerName: serverName, + } + + if config.MaxIdleTime == 0 { + config.MaxIdleTime = 30000 + } + if config.MaxDatagramFrameSize == 0 { + config.MaxDatagramFrameSize = 1400 + } + if config.CWND == 0 { + config.CWND = 32 + } + jlsPacketDialer := func(_ context.Context, network, address string) (net.PacketConn, net.Addr, error) { + return inner.HandleUdp(tunnel, network, address, config.JLSUpstream.Proxy) + } + quicVersions, versionNegotiationVersions, getVersionNegotiationProfile, err := shadowquic.ResolveQUICVersionProfile( + config.QUICVersions, + config.JLSUpstream.Addr, + config.JLSUpstream.QUICVersionProbe, + jlsPacketDialer, + log.Warnln, + ) + if err != nil { + return nil, err + } + + quicConfig := &quic.Config{ + Versions: quicVersions, + JLSConfig: &quic.JLSConfig{ + UpstreamAddr: config.JLSUpstream.Addr, + RateLimit: config.JLSUpstream.RateLimit, + PacketDialer: jlsPacketDialer, + VersionNegotiationVersions: versionNegotiationVersions, + GetVersionNegotiationProfile: getVersionNegotiationProfile, + }, + MaxIdleTimeout: time.Duration(config.MaxIdleTime) * time.Millisecond, + MaxIncomingStreams: ServerMaxIncomingStreams, + MaxIncomingUniStreams: ServerMaxIncomingStreams, + InitialStreamReceiveWindow: uint64(config.ReceiveWindowConn), + MaxStreamReceiveWindow: uint64(config.ReceiveWindowConn), + InitialConnectionReceiveWindow: uint64(config.ReceiveWindow), + MaxConnectionReceiveWindow: uint64(config.ReceiveWindow), + MaxDatagramFrameSize: int64(config.MaxDatagramFrameSize), + EnableDatagrams: true, + Allow0RTT: config.ZeroRTT, + DisablePathMTUDiscovery: config.DisableMTUDiscovery, + } + if config.ReceiveWindowConn == 0 { + quicConfig.InitialStreamReceiveWindow = tuic.DefaultStreamReceiveWindow / 10 + quicConfig.MaxStreamReceiveWindow = tuic.DefaultStreamReceiveWindow + } + if config.ReceiveWindow == 0 { + quicConfig.InitialConnectionReceiveWindow = tuic.DefaultConnectionReceiveWindow / 10 + quicConfig.MaxConnectionReceiveWindow = tuic.DefaultConnectionReceiveWindow + } + handleTcpFn := func(conn net.Conn, addr socks5.Addr, _additions ...inbound.Addition) error { + go h.HandleSocket(addr, conn, _additions...) + return nil + } + handleUdpFn := func(addr socks5.Addr, packet C.UDPPacket, _additions ...inbound.Addition) error { + newAdditions := additions + if len(_additions) > 0 { + newAdditions = append(append([]inbound.Addition{}, additions...), _additions...) + } + tunnel.HandleUDPPacket(inbound.NewPacket(addr, packet, C.SHADOWQUIC, newAdditions...)) + return nil + } + + option := &shadowquic.ServerOption{ + HandleTcpFn: handleTcpFn, + HandleUdpFn: handleUdpFn, + TLSConfig: tlsConfig, + QUICConfig: quicConfig, + CongestionController: config.CongestionController, + CWND: config.CWND, + BBRProfile: config.BBRProfile, + } + + sl := &Listener{config: config} + for _, addr := range strings.Split(config.Listen, ",") { + addr = strings.TrimSpace(addr) + if addr == "" { + continue + } + ul, err := lc.ListenPacket(context.Background(), "udp", addr) + if err != nil { + return nil, err + } + if err := sockopt.UDPReuseaddr(ul); err != nil { + log.Warnln("Failed to Reuse UDP Address: %s", err) + } + sl.udpListeners = append(sl.udpListeners, ul) + + server, err := shadowquic.NewServer(option, ul) + if err != nil { + return nil, err + } + sl.servers = append(sl.servers, server) + + go func() { + err := server.Serve() + if err != nil && !sl.closed { + log.Warnln("ShadowQuic server closed: %s", err) + } + }() + } + return sl, nil +} + +func defaultJLSServerName(upstreamAddr string) string { + host, _, err := net.SplitHostPort(upstreamAddr) + if err != nil { + host = upstreamAddr + } + if _, err := netip.ParseAddr(host); err == nil { + return "" + } + if strings.Contains(host, ":") { + return "" + } + return host +} + +func (l *Listener) Close() error { + l.closed = true + var retErr error + for _, server := range l.servers { + if err := server.Close(); err != nil { + retErr = err + } + } + for _, lis := range l.udpListeners { + if err := lis.Close(); err != nil { + retErr = err + } + } + return retErr +} + +func (l *Listener) Config() LC.ShadowQuicServer { + return l.config +} + +func (l *Listener) AddrList() (addrList []net.Addr) { + for _, lis := range l.udpListeners { + addrList = append(addrList, lis.LocalAddr()) + } + return +} diff --git a/transport/shadowquic/client.go b/transport/shadowquic/client.go new file mode 100644 index 000000000..0f55ff5f0 --- /dev/null +++ b/transport/shadowquic/client.go @@ -0,0 +1,106 @@ +package shadowquic + +import ( + "context" + "errors" + "net" + "sync" + + C "github.com/metacubex/mihomo/constant" + + "github.com/metacubex/jls-quic-go" +) + +type DialFunc func(ctx context.Context) (*quic.Conn, error) + +type ClientOption struct { + Dial DialFunc + UDPOverStream bool +} + +type Client struct { + option *ClientOption + + mu sync.Mutex + conn *connState + closed bool +} + +func NewClient(option *ClientOption) *Client { + return &Client{option: option} +} + +func (c *Client) getConn(ctx context.Context) (*connState, error) { + c.mu.Lock() + defer c.mu.Unlock() + + if c.closed { + return nil, net.ErrClosed + } + if c.conn != nil && !c.conn.closed() { + return c.conn, nil + } + if c.option == nil || c.option.Dial == nil { + return nil, errors.New("shadowquic: dial function is nil") + } + quicConn, err := c.option.Dial(ctx) + if err != nil { + return nil, err + } + c.conn = newConnState(quicConn) + return c.conn, nil +} + +func (c *Client) DialContext(ctx context.Context, metadata *C.Metadata) (net.Conn, error) { + state, err := c.getConn(ctx) + if err != nil { + return nil, err + } + target, err := MetadataAddr(metadata) + if err != nil { + return nil, err + } + stream, err := state.quicConn.OpenStreamSync(ctx) + if err != nil { + return nil, err + } + conn := NewQuicStreamConn(stream, state.quicConn.LocalAddr(), state.quicConn.RemoteAddr(), nil) + if err = WriteRequest(conn, CommandConnect, target); err != nil { + _ = conn.Close() + return nil, err + } + return conn, nil +} + +func (c *Client) ListenPacket(ctx context.Context, metadata *C.Metadata) (net.PacketConn, error) { + state, err := c.getConn(ctx) + if err != nil { + return nil, err + } + stream, err := state.quicConn.OpenStreamSync(ctx) + if err != nil { + return nil, err + } + mode := udpModeDatagram + command := CommandAssociateDatagram + if c.option != nil && c.option.UDPOverStream { + mode = udpModeStream + command = CommandAssociateStream + } + if err = WriteRequest(stream, command, UnspecifiedAddr()); err != nil { + _ = stream.Close() + return nil, err + } + return newAssociation(state, stream, mode), nil +} + +func (c *Client) Close() error { + c.mu.Lock() + defer c.mu.Unlock() + + c.closed = true + if c.conn != nil { + return c.conn.closeWithError(0, "client closed") + } + return nil +} diff --git a/transport/shadowquic/congestion.go b/transport/shadowquic/congestion.go new file mode 100644 index 000000000..42ed97fa7 --- /dev/null +++ b/transport/shadowquic/congestion.go @@ -0,0 +1,162 @@ +package shadowquic + +import ( + "time" + + "github.com/metacubex/mihomo/transport/tuic/congestion" + congestionv2 "github.com/metacubex/mihomo/transport/tuic/congestion_v2" + + "github.com/metacubex/jls-quic-go" + jcongestion "github.com/metacubex/jls-quic-go/congestion" + jmonotime "github.com/metacubex/jls-quic-go/monotime" + oldcongestion "github.com/metacubex/quic-go/congestion" + oldmonotime "github.com/metacubex/quic-go/monotime" +) + +func SetCongestionController(quicConn *quic.Conn, cc string, cwnd int, profile string) { + if cwnd == 0 { + cwnd = 32 + } + initialPacketSize := oldcongestion.ByteCount(quicConn.Config().InitialPacketSize) + switch cc { + case "cubic": + quicConn.SetCongestionControl(newCongestionAdapter( + congestion.NewCubicSender(initialPacketSize, false), + )) + case "new_reno": + quicConn.SetCongestionControl(newCongestionAdapter( + congestion.NewCubicSender(initialPacketSize, true), + )) + case "bbr_meta_v1": + quicConn.SetCongestionControl(newCongestionAdapter( + congestion.NewBBRSender( + initialPacketSize, + oldcongestion.ByteCount(cwnd)*congestion.InitialMaxDatagramSize, + congestion.DefaultBBRMaxCongestionWindow*congestion.InitialMaxDatagramSize, + ), + )) + case "bbr_meta_v2", "bbr": + quicConn.SetCongestionControl(newCongestionAdapter( + congestionv2.NewBbrSender( + initialPacketSize, + oldcongestion.ByteCount(cwnd), + congestionv2.Profile(profile), + ), + )) + } +} + +func newCongestionAdapter(cc oldcongestion.CongestionControl) jcongestion.CongestionControl { + return &congestionAdapter{cc: cc} +} + +type congestionAdapter struct { + cc oldcongestion.CongestionControl +} + +func (a *congestionAdapter) SetRTTStatsProvider(provider jcongestion.RTTStatsProvider) { + a.cc.SetRTTStatsProvider(rttStatsProviderAdapter{provider: provider}) +} + +func (a *congestionAdapter) TimeUntilSend(bytesInFlight jcongestion.ByteCount) jmonotime.Time { + return jmonotime.Time(a.cc.TimeUntilSend(oldcongestion.ByteCount(bytesInFlight))) +} + +func (a *congestionAdapter) HasPacingBudget(now jmonotime.Time) bool { + return a.cc.HasPacingBudget(oldmonotime.Time(now)) +} + +func (a *congestionAdapter) OnPacketSent(sentTime jmonotime.Time, bytesInFlight jcongestion.ByteCount, packetNumber jcongestion.PacketNumber, bytes jcongestion.ByteCount, isRetransmittable bool) { + a.cc.OnPacketSent( + oldmonotime.Time(sentTime), + oldcongestion.ByteCount(bytesInFlight), + oldcongestion.PacketNumber(packetNumber), + oldcongestion.ByteCount(bytes), + isRetransmittable, + ) +} + +func (a *congestionAdapter) CanSend(bytesInFlight jcongestion.ByteCount) bool { + return a.cc.CanSend(oldcongestion.ByteCount(bytesInFlight)) +} + +func (a *congestionAdapter) MaybeExitSlowStart() { + a.cc.MaybeExitSlowStart() +} + +func (a *congestionAdapter) OnPacketAcked(number jcongestion.PacketNumber, ackedBytes jcongestion.ByteCount, priorInFlight jcongestion.ByteCount, eventTime jmonotime.Time) { + a.cc.OnPacketAcked( + oldcongestion.PacketNumber(number), + oldcongestion.ByteCount(ackedBytes), + oldcongestion.ByteCount(priorInFlight), + oldmonotime.Time(eventTime), + ) +} + +func (a *congestionAdapter) OnCongestionEvent(number jcongestion.PacketNumber, lostBytes jcongestion.ByteCount, priorInFlight jcongestion.ByteCount) { + a.cc.OnCongestionEvent( + oldcongestion.PacketNumber(number), + oldcongestion.ByteCount(lostBytes), + oldcongestion.ByteCount(priorInFlight), + ) +} + +func (a *congestionAdapter) OnRetransmissionTimeout(packetsRetransmitted bool) { + a.cc.OnRetransmissionTimeout(packetsRetransmitted) +} + +func (a *congestionAdapter) SetMaxDatagramSize(size jcongestion.ByteCount) { + a.cc.SetMaxDatagramSize(oldcongestion.ByteCount(size)) +} + +func (a *congestionAdapter) InSlowStart() bool { + return a.cc.InSlowStart() +} + +func (a *congestionAdapter) InRecovery() bool { + return a.cc.InRecovery() +} + +func (a *congestionAdapter) GetCongestionWindow() jcongestion.ByteCount { + return jcongestion.ByteCount(a.cc.GetCongestionWindow()) +} + +type rttStatsProviderAdapter struct { + provider jcongestion.RTTStatsProvider +} + +func (a rttStatsProviderAdapter) MinRTT() time.Duration { + return a.provider.MinRTT() +} + +func (a rttStatsProviderAdapter) LatestRTT() time.Duration { + return a.provider.LatestRTT() +} + +func (a rttStatsProviderAdapter) SmoothedRTT() time.Duration { + return a.provider.SmoothedRTT() +} + +func (a rttStatsProviderAdapter) MeanDeviation() time.Duration { + return a.provider.MeanDeviation() +} + +func (a rttStatsProviderAdapter) MaxAckDelay() time.Duration { + return a.provider.MaxAckDelay() +} + +func (a rttStatsProviderAdapter) PTO(includeMaxAckDelay bool) time.Duration { + return a.provider.PTO(includeMaxAckDelay) +} + +func (a rttStatsProviderAdapter) UpdateRTT(sendDelta, ackDelay time.Duration) { + a.provider.UpdateRTT(sendDelta, ackDelay) +} + +func (a rttStatsProviderAdapter) SetMaxAckDelay(mad time.Duration) { + a.provider.SetMaxAckDelay(mad) +} + +func (a rttStatsProviderAdapter) SetInitialRTT(t time.Duration) { + a.provider.SetInitialRTT(t) +} diff --git a/transport/shadowquic/extension.go b/transport/shadowquic/extension.go new file mode 100644 index 000000000..e57853098 --- /dev/null +++ b/transport/shadowquic/extension.go @@ -0,0 +1,91 @@ +package shadowquic + +import ( + "encoding/binary" + "io" + "math" + "time" + + "github.com/metacubex/jls-quic-go" +) + +const ( + extensionOpcodeConn uint64 = 0x01 + extensionOpcodeUser uint64 = 0x02 + + extensionConnGetStats byte = 0x00 + + extensionResultOK byte = 0x00 + extensionResultErr byte = 0x01 + + extensionErrNotAvailable byte = 0x00 + extensionErrPermissionDenied byte = 0x01 + extensionErrNotFound byte = 0x02 + extensionErrOther byte = 0xff + + extensionConnStatsLen uint32 = 8 + 8 + 8 + 2 +) + +type ExtensionConnStats struct { + LostPackets uint64 + SentPackets uint64 + RTT float64 + CurrentMTU uint16 +} + +func ReadExtensionOpcode(r io.Reader) (uint64, error) { + var buf [8]byte + if _, err := io.ReadFull(r, buf[:]); err != nil { + return 0, err + } + return binary.BigEndian.Uint64(buf[:]), nil +} + +func readExtensionSubcommand(r io.Reader) (byte, error) { + var buf [1]byte + if _, err := io.ReadFull(r, buf[:]); err != nil { + return 0, err + } + return buf[0], nil +} + +func WriteExtensionConnStatsResult(w io.Writer, stats ExtensionConnStats) error { + var buf [1 + 4 + extensionConnStatsLen]byte + buf[0] = extensionResultOK + binary.BigEndian.PutUint32(buf[1:5], extensionConnStatsLen) + binary.BigEndian.PutUint64(buf[5:13], stats.LostPackets) + binary.BigEndian.PutUint64(buf[13:21], stats.SentPackets) + binary.BigEndian.PutUint64(buf[21:29], math.Float64bits(stats.RTT)) + binary.BigEndian.PutUint16(buf[29:31], stats.CurrentMTU) + return writeFull(w, buf[:]) +} + +func WriteExtensionErrorResult(w io.Writer, code byte, message string) error { + if err := writeFull(w, []byte{extensionResultErr, code}); err != nil { + return err + } + if code != extensionErrOther { + return nil + } + msg := []byte(message) + var lenBuf [4]byte + binary.BigEndian.PutUint32(lenBuf[:], uint32(len(msg))) + if err := writeFull(w, lenBuf[:]); err != nil { + return err + } + return writeFull(w, msg) +} + +func shadowQUICConnStats(conn *quic.Conn) ExtensionConnStats { + stats := conn.ConnectionStats() + rtt := stats.SmoothedRTT + if rtt == 0 { + rtt = stats.LatestRTT + } + return ExtensionConnStats{ + LostPackets: stats.PacketsLost, + SentPackets: stats.PacketsSent, + RTT: float64(rtt) / float64(time.Millisecond), + CurrentMTU: stats.CurrentMTU, + } +} diff --git a/transport/shadowquic/extension_test.go b/transport/shadowquic/extension_test.go new file mode 100644 index 000000000..3e32ebfbf --- /dev/null +++ b/transport/shadowquic/extension_test.go @@ -0,0 +1,81 @@ +package shadowquic + +import ( + "bytes" + "encoding/binary" + "io" + "math" + "net" + "testing" +) + +func TestWriteExtensionConnStatsResult(t *testing.T) { + var buf bytes.Buffer + err := WriteExtensionConnStatsResult(&buf, ExtensionConnStats{ + LostPackets: 3, + SentPackets: 5, + RTT: 12.5, + CurrentMTU: 1400, + }) + if err != nil { + t.Fatal(err) + } + + data := buf.Bytes() + if len(data) != 31 { + t.Fatalf("encoded length = %d, want 31", len(data)) + } + if data[0] != extensionResultOK { + t.Fatalf("result tag = %#x, want OK", data[0]) + } + if got := binary.BigEndian.Uint32(data[1:5]); got != extensionConnStatsLen { + t.Fatalf("stats length = %d, want %d", got, extensionConnStatsLen) + } + if got := binary.BigEndian.Uint64(data[5:13]); got != 3 { + t.Fatalf("lost packets = %d, want 3", got) + } + if got := binary.BigEndian.Uint64(data[13:21]); got != 5 { + t.Fatalf("sent packets = %d, want 5", got) + } + if got := math.Float64frombits(binary.BigEndian.Uint64(data[21:29])); got != 12.5 { + t.Fatalf("rtt = %f, want 12.5", got) + } + if got := binary.BigEndian.Uint16(data[29:31]); got != 1400 { + t.Fatalf("mtu = %d, want 1400", got) + } +} + +func TestWriteExtensionErrorResult(t *testing.T) { + var buf bytes.Buffer + err := WriteExtensionErrorResult(&buf, extensionErrPermissionDenied, "") + if err != nil { + t.Fatal(err) + } + if got, want := buf.Bytes(), []byte{extensionResultErr, extensionErrPermissionDenied}; !bytes.Equal(got, want) { + t.Fatalf("encoded error = %v, want %v", got, want) + } +} + +func TestUserExtensionIsUnavailable(t *testing.T) { + client, server := net.Pipe() + done := make(chan struct{}) + go func() { + (&Server{}).handleExtension(nil, server) + close(done) + }() + + var request [9]byte + binary.BigEndian.PutUint64(request[:8], extensionOpcodeUser) + if _, err := client.Write(request[:]); err != nil { + t.Fatal(err) + } + var response [2]byte + if _, err := io.ReadFull(client, response[:]); err != nil { + t.Fatal(err) + } + if want := [2]byte{extensionResultErr, extensionErrNotAvailable}; response != want { + t.Fatalf("response = %v, want %v", response, want) + } + _ = client.Close() + <-done +} diff --git a/transport/shadowquic/packet.go b/transport/shadowquic/packet.go new file mode 100644 index 000000000..38ffcebc5 --- /dev/null +++ b/transport/shadowquic/packet.go @@ -0,0 +1,220 @@ +package shadowquic + +import ( + "net" + "os" + "sync" + "time" + + "github.com/metacubex/mihomo/common/net/deadline" + + "github.com/metacubex/jls-quic-go" +) + +const packetInputQueue = 128 + +type association struct { + parent *connState + mode udpMode + control *quic.Stream + + input chan receivedPacket + + mu sync.Mutex + sendIDs map[string]uint16 + sendIDSet map[uint16]struct{} + recvIDSet map[uint16]struct{} + uniStreams map[string]*quic.SendStream + + closed chan struct{} + closeOnce sync.Once + closeErr error + + readDeadline deadline.PipeDeadline + writeDeadline deadline.PipeDeadline +} + +func newAssociation(parent *connState, control *quic.Stream, mode udpMode) *association { + a := &association{ + parent: parent, + mode: mode, + control: control, + input: make(chan receivedPacket, packetInputQueue), + sendIDs: make(map[string]uint16), + sendIDSet: make(map[uint16]struct{}), + recvIDSet: make(map[uint16]struct{}), + uniStreams: make(map[string]*quic.SendStream), + closed: make(chan struct{}), + readDeadline: deadline.MakePipeDeadline(), + writeDeadline: deadline.MakePipeDeadline(), + } + go a.readControl() + go func() { + <-parent.ctx.Done() + _ = a.Close() + }() + return a +} + +func (a *association) readControl() { + defer a.Close() + + for { + addr, id, err := ReadUDPControl(a.control) + if err != nil { + return + } + a.mu.Lock() + a.recvIDSet[id] = struct{}{} + a.mu.Unlock() + a.parent.storeRecv(id, a, addr) + } +} + +func (a *association) deliver(packet receivedPacket) { + select { + case a.input <- packet: + case <-a.closed: + default: + } +} + +func (a *association) ReadFrom(p []byte) (int, net.Addr, error) { + select { + case packet := <-a.input: + return copy(p, packet.data), packet.addr, nil + case <-a.closed: + return 0, nil, net.ErrClosed + case <-a.readDeadline.Wait(): + return 0, nil, os.ErrDeadlineExceeded + } +} + +func (a *association) WaitReadFrom() ([]byte, func(), net.Addr, error) { + select { + case packet := <-a.input: + return packet.data, nil, packet.addr, nil + case <-a.closed: + return nil, nil, nil, net.ErrClosed + case <-a.readDeadline.Wait(): + return nil, nil, nil, os.ErrDeadlineExceeded + } +} + +func (a *association) WriteTo(p []byte, addr net.Addr) (n int, err error) { + if len(p) > maxUDPPacketSize { + return 0, errPacketTooLarge + } + select { + case <-a.closed: + return 0, net.ErrClosed + case <-a.writeDeadline.Wait(): + return 0, os.ErrDeadlineExceeded + default: + } + + socksAddr, err := AddrFromNetAddr(addr) + if err != nil { + return 0, err + } + key := string(socksAddr) + + a.mu.Lock() + defer a.mu.Unlock() + + id, exists := a.sendIDs[key] + if !exists { + id, err = a.parent.allocSendID() + if err != nil { + return 0, err + } + if err = WriteUDPControl(a.control, socksAddr, id); err != nil { + a.parent.releaseSendIDs(map[uint16]struct{}{id: struct{}{}}) + return 0, err + } + a.sendIDs[key] = id + a.sendIDSet[id] = struct{}{} + } + + switch a.mode { + case udpModeStream: + stream := a.uniStreams[key] + if stream == nil { + stream, err = a.parent.quicConn.OpenUniStreamSync(a.parent.ctx) + if err != nil { + return 0, err + } + if err = WritePacketStreamHeader(stream, id); err != nil { + _ = stream.Close() + return 0, err + } + a.uniStreams[key] = stream + } + if err = WritePacketStreamPayload(stream, p); err != nil { + return 0, err + } + default: + packet, err := EncodeDatagram(id, p) + if err != nil { + return 0, err + } + if err = a.parent.quicConn.SendDatagram(packet); err != nil { + return 0, err + } + } + + return len(p), nil +} + +func (a *association) Close() error { + a.closeOnce.Do(func() { + close(a.closed) + a.closeErr = a.close() + }) + return a.closeErr +} + +func (a *association) close() error { + a.control.CancelRead(0) + _ = a.control.SetWriteDeadline(time.Now()) + + a.mu.Lock() + sendIDSet := make(map[uint16]struct{}, len(a.sendIDSet)) + for id := range a.sendIDSet { + sendIDSet[id] = struct{}{} + } + recvIDSet := make(map[uint16]struct{}, len(a.recvIDSet)) + for id := range a.recvIDSet { + recvIDSet[id] = struct{}{} + } + for _, stream := range a.uniStreams { + _ = stream.Close() + } + a.mu.Unlock() + + a.parent.releaseSendIDs(sendIDSet) + a.parent.removeRecvIDs(a, recvIDSet) + return a.control.Close() +} + +func (a *association) LocalAddr() net.Addr { + return a.parent.quicConn.LocalAddr() +} + +func (a *association) SetDeadline(t time.Time) error { + a.readDeadline.Set(t) + a.writeDeadline.Set(t) + return nil +} + +func (a *association) SetReadDeadline(t time.Time) error { + a.readDeadline.Set(t) + return nil +} + +func (a *association) SetWriteDeadline(t time.Time) error { + a.writeDeadline.Set(t) + return nil +} + +var _ net.PacketConn = (*association)(nil) diff --git a/transport/shadowquic/protocol.go b/transport/shadowquic/protocol.go new file mode 100644 index 000000000..d3e0d3fe7 --- /dev/null +++ b/transport/shadowquic/protocol.go @@ -0,0 +1,186 @@ +package shadowquic + +import ( + "encoding/binary" + "errors" + "fmt" + "io" + "net" + "net/netip" + + C "github.com/metacubex/mihomo/constant" + "github.com/metacubex/mihomo/transport/socks5" +) + +const ( + CommandConnect byte = 0x01 + CommandBind byte = 0x02 + CommandAssociateDatagram byte = 0x03 + CommandAssociateStream byte = 0x04 + CommandAuthenticate byte = 0x05 + CommandExtension byte = 0xff +) + +const maxUDPPacketSize = 0xffff + +var ( + errInvalidAddress = errors.New("shadowquic: invalid address") + errInvalidDatagram = errors.New("shadowquic: invalid datagram") + errPacketTooLarge = errors.New("shadowquic: packet too large") +) + +func MetadataAddr(metadata *C.Metadata) (socks5.Addr, error) { + addr := socks5.ParseAddr(metadata.RemoteAddress()) + if addr == nil { + return nil, fmt.Errorf("%w: %s", errInvalidAddress, metadata.RemoteAddress()) + } + return addr, nil +} + +func UnspecifiedAddr() socks5.Addr { + return socks5.AddrFromStdAddrPort(netip.AddrPortFrom(netip.IPv4Unspecified(), 0)) +} + +func AddrFromNetAddr(addr net.Addr) (socks5.Addr, error) { + if addr == nil { + return nil, errInvalidAddress + } + socksAddr := socks5.ParseAddrToSocksAddr(addr) + if socksAddr == nil { + socksAddr = socks5.ParseAddr(addr.String()) + } + if socksAddr == nil { + return nil, fmt.Errorf("%w: %s", errInvalidAddress, addr.String()) + } + return socksAddr, nil +} + +func AddrToNetAddr(addr socks5.Addr) net.Addr { + if udpAddr := addr.UDPAddr(); udpAddr != nil { + return udpAddr + } + return socksNetAddr{addr: addr} +} + +func WriteRequest(w io.Writer, command byte, addr socks5.Addr) error { + if addr == nil { + return errInvalidAddress + } + if err := writeFull(w, []byte{command}); err != nil { + return err + } + return writeFull(w, addr) +} + +func ReadCommand(r io.Reader) (byte, error) { + return socks5.ReadByte(r) +} + +func ReadRequestAddr(r io.Reader) (socks5.Addr, error) { + return socks5.ReadAddr0(r) +} + +func ReadRequest(r io.Reader) (byte, socks5.Addr, error) { + command, err := ReadCommand(r) + if err != nil { + return 0, nil, err + } + addr, err := ReadRequestAddr(r) + if err != nil { + return 0, nil, err + } + return command, addr, nil +} + +func WriteUDPControl(w io.Writer, addr socks5.Addr, id uint16) error { + if addr == nil { + return errInvalidAddress + } + if err := writeFull(w, addr); err != nil { + return err + } + var buf [2]byte + binary.BigEndian.PutUint16(buf[:], id) + return writeFull(w, buf[:]) +} + +func ReadUDPControl(r io.Reader) (socks5.Addr, uint16, error) { + addr, err := socks5.ReadAddr0(r) + if err != nil { + return nil, 0, err + } + id, err := ReadUint16(r) + if err != nil { + return nil, 0, err + } + return addr, id, nil +} + +func EncodeDatagram(id uint16, payload []byte) ([]byte, error) { + if len(payload) > maxUDPPacketSize { + return nil, errPacketTooLarge + } + packet := make([]byte, 2+len(payload)) + binary.BigEndian.PutUint16(packet[:2], id) + copy(packet[2:], payload) + return packet, nil +} + +func DecodeDatagram(packet []byte) (uint16, []byte, error) { + if len(packet) < 2 { + return 0, nil, errInvalidDatagram + } + return binary.BigEndian.Uint16(packet[:2]), packet[2:], nil +} + +func WritePacketStreamHeader(w io.Writer, id uint16) error { + var buf [2]byte + binary.BigEndian.PutUint16(buf[:], id) + return writeFull(w, buf[:]) +} + +func WritePacketStreamPayload(w io.Writer, payload []byte) error { + if len(payload) > maxUDPPacketSize { + return errPacketTooLarge + } + var buf [2]byte + binary.BigEndian.PutUint16(buf[:], uint16(len(payload))) + if err := writeFull(w, buf[:]); err != nil { + return err + } + return writeFull(w, payload) +} + +func ReadUint16(r io.Reader) (uint16, error) { + var buf [2]byte + if _, err := io.ReadFull(r, buf[:]); err != nil { + return 0, err + } + return binary.BigEndian.Uint16(buf[:]), nil +} + +func writeFull(w io.Writer, p []byte) error { + for len(p) > 0 { + n, err := w.Write(p) + if err != nil { + return err + } + if n == 0 { + return io.ErrShortWrite + } + p = p[n:] + } + return nil +} + +type socksNetAddr struct { + addr socks5.Addr +} + +func (a socksNetAddr) Network() string { + return "udp" +} + +func (a socksNetAddr) String() string { + return a.addr.String() +} diff --git a/transport/shadowquic/quic_version.go b/transport/shadowquic/quic_version.go new file mode 100644 index 000000000..038efa0dd --- /dev/null +++ b/transport/shadowquic/quic_version.go @@ -0,0 +1,284 @@ +package shadowquic + +import ( + "context" + "crypto/rand" + "encoding/binary" + "errors" + "fmt" + "io" + "strings" + "sync" + "time" + + "github.com/metacubex/jls-quic-go" +) + +const ( + quicVersionProbeTimeout = time.Second + quicVersionProbeSize = 1200 + quicVersionProbeVersion = quic.Version(0x0a0a0a0a) // reserved version used to elicit Version Negotiation + quicVersionGrease = quic.Version(0x0a1a2a3a) + quicVersionDraft29 = quic.Version(0xff00001d) + quicVersionDraft30 = quic.Version(0xff00001e) + quicVersionDraft31 = quic.Version(0xff00001f) + quicVersionDraft32 = quic.Version(0xff000020) + quicVersionDraft33 = quic.Version(0xff000021) + quicVersionDraft34 = quic.Version(0xff000022) +) + +var defaultQUICVersionNegotiationVersions = []quic.Version{ + quicVersionGrease, + quic.Version1, + quicVersionDraft29, + quicVersionDraft30, + quicVersionDraft31, + quicVersionDraft32, + quicVersionDraft33, + quicVersionDraft34, +} + +type QUICVersionProfileProvider func() ([]quic.Version, []quic.Version) + +func DefaultQUICVersions() []quic.Version { + return []quic.Version{quic.Version1} +} + +func DefaultQUICVersionNegotiationVersions() []quic.Version { + return CloneQUICVersions(defaultQUICVersionNegotiationVersions) +} + +func ResolveQUICVersionProfile(versions []string, upstreamAddr string, upstreamProbe bool, dialer quic.JLSPacketDialer, logf func(string, ...any)) ([]quic.Version, []quic.Version, QUICVersionProfileProvider, error) { + supported := DefaultQUICVersions() + versionNegotiation := DefaultQUICVersionNegotiationVersions() + + if len(versions) > 0 { + var err error + supported, versionNegotiation, err = ParseQUICVersionProfile(versions) + if err != nil { + return nil, nil, nil, err + } + } + + if upstreamAddr == "" { + return supported, versionNegotiation, nil, nil + } + if !upstreamProbe { + return supported, versionNegotiation, nil, nil + } + if dialer == nil { + return nil, nil, nil, errors.New("shadowquic: QUIC version probe dialer is nil") + } + + provider := NewLazyQUICVersionProfile(upstreamAddr, dialer, supported, versionNegotiation, func(err error) { + if logf != nil { + logf("ShadowQuic JLS upstream QUIC version probe failed: %s", err) + } + }) + return supported, versionNegotiation, provider, nil +} + +func ParseQUICVersionProfile(values []string) ([]quic.Version, []quic.Version, error) { + versions := make([]quic.Version, 0, len(values)) + for _, value := range values { + version, err := ParseQUICVersion(value) + if err != nil { + return nil, nil, err + } + versions = append(versions, version) + } + supported, versionNegotiation := NormalizeQUICVersionProfile(versions) + return supported, versionNegotiation, nil +} + +func NewLazyQUICVersionProfile(address string, dialer quic.JLSPacketDialer, fallbackSupported, fallbackVersionNegotiation []quic.Version, onProbeError func(error)) QUICVersionProfileProvider { + var once sync.Once + supported := CloneQUICVersions(fallbackSupported) + versionNegotiation := CloneQUICVersions(fallbackVersionNegotiation) + return func() ([]quic.Version, []quic.Version) { + once.Do(func() { + ctx, cancel := context.WithTimeout(context.Background(), quicVersionProbeTimeout) + defer cancel() + advertised, err := ProbeQUICVersionNegotiation(ctx, address, dialer) + if err != nil { + if onProbeError != nil { + onProbeError(err) + } + return + } + normalizedSupported := supportedQUICVersions(advertised) + if len(normalizedSupported) == 0 { + if onProbeError != nil { + onProbeError(errors.New("shadowquic: upstream advertised no supported QUIC versions")) + } + return + } + supported = normalizedSupported + versionNegotiation = advertisedQUICVersions(advertised) + }) + return CloneQUICVersions(supported), CloneQUICVersions(versionNegotiation) + } +} + +func advertisedQUICVersions(versions []quic.Version) []quic.Version { + advertised := make([]quic.Version, 0, len(versions)) + for _, version := range versions { + if version == 0 || containsQUICVersion(advertised, version) { + continue + } + advertised = append(advertised, version) + } + return advertised +} + +func CloneQUICVersions(versions []quic.Version) []quic.Version { + if len(versions) == 0 { + return nil + } + cloned := make([]quic.Version, len(versions)) + copy(cloned, versions) + return cloned +} + +func ProbeQUICVersionNegotiation(ctx context.Context, address string, dialer quic.JLSPacketDialer) ([]quic.Version, error) { + if dialer == nil { + return nil, errors.New("shadowquic: QUIC version probe dialer is nil") + } + pc, upstreamAddr, err := dialer(ctx, "udp", address) + if err != nil { + return nil, err + } + defer pc.Close() + + deadline := time.Now().Add(quicVersionProbeTimeout) + if ctxDeadline, ok := ctx.Deadline(); ok && ctxDeadline.Before(deadline) { + deadline = ctxDeadline + } + if err := pc.SetDeadline(deadline); err != nil { + return nil, err + } + + probe, err := composeQUICVersionProbe() + if err != nil { + return nil, err + } + if _, err := pc.WriteTo(probe, upstreamAddr); err != nil { + return nil, err + } + + buf := make([]byte, quicVersionProbeSize) + n, _, err := pc.ReadFrom(buf) + if err != nil { + return nil, err + } + return parseQUICVersionNegotiation(buf[:n]) +} + +func NormalizeQUICVersionProfile(versions []quic.Version) ([]quic.Version, []quic.Version) { + supported := supportedQUICVersions(versions) + if len(supported) == 0 { + supported = DefaultQUICVersions() + } + return supported, CloneQUICVersions(supported) +} + +func supportedQUICVersions(versions []quic.Version) []quic.Version { + var supported []quic.Version + for _, version := range versions { + if !isSupportedQUICVersion(version) { + continue + } + if !containsQUICVersion(supported, version) { + supported = append(supported, version) + } + } + return supported +} + +func composeQUICVersionProbe() ([]byte, error) { + var dcid [8]byte + var scid [8]byte + if _, err := io.ReadFull(rand.Reader, dcid[:]); err != nil { + return nil, err + } + if _, err := io.ReadFull(rand.Reader, scid[:]); err != nil { + return nil, err + } + + packet := make([]byte, 0, quicVersionProbeSize) + packet = append(packet, 0xc3) + packet = binary.BigEndian.AppendUint32(packet, uint32(quicVersionProbeVersion)) + packet = append(packet, byte(len(dcid))) + packet = append(packet, dcid[:]...) + packet = append(packet, byte(len(scid))) + packet = append(packet, scid[:]...) + for len(packet) < quicVersionProbeSize { + packet = append(packet, 0) + } + return packet, nil +} + +func parseQUICVersionNegotiation(packet []byte) ([]quic.Version, error) { + if len(packet) < 7 || packet[0]&0x80 == 0 { + return nil, errors.New("not a QUIC Version Negotiation packet") + } + if binary.BigEndian.Uint32(packet[1:5]) != 0 { + return nil, errors.New("not a QUIC Version Negotiation packet") + } + + offset := 5 + if offset >= len(packet) { + return nil, io.ErrUnexpectedEOF + } + dcidLen := int(packet[offset]) + offset++ + if offset+dcidLen > len(packet) { + return nil, io.ErrUnexpectedEOF + } + offset += dcidLen + + if offset >= len(packet) { + return nil, io.ErrUnexpectedEOF + } + scidLen := int(packet[offset]) + offset++ + if offset+scidLen > len(packet) { + return nil, io.ErrUnexpectedEOF + } + offset += scidLen + + if len(packet)-offset < 4 { + return nil, errors.New("QUIC Version Negotiation packet has no versions") + } + versions := make([]quic.Version, 0, (len(packet)-offset)/4) + for offset+4 <= len(packet) { + versions = append(versions, quic.Version(binary.BigEndian.Uint32(packet[offset:offset+4]))) + offset += 4 + } + return versions, nil +} + +func ParseQUICVersion(value string) (quic.Version, error) { + normalized := strings.ToLower(strings.TrimSpace(value)) + normalized = strings.ReplaceAll(normalized, "_", "-") + switch normalized { + case "v1", "1", "rfc9000", "rfc-9000": + return quic.Version1, nil + case "v2", "2", "rfc9369", "rfc-9369": + return quic.Version2, nil + } + return 0, fmt.Errorf("unsupported QUIC version %q (supported: v1, v2)", value) +} + +func isSupportedQUICVersion(version quic.Version) bool { + return version == quic.Version1 || version == quic.Version2 +} + +func containsQUICVersion(versions []quic.Version, version quic.Version) bool { + for _, v := range versions { + if v == version { + return true + } + } + return false +} diff --git a/transport/shadowquic/quic_version_test.go b/transport/shadowquic/quic_version_test.go new file mode 100644 index 000000000..1da180347 --- /dev/null +++ b/transport/shadowquic/quic_version_test.go @@ -0,0 +1,268 @@ +package shadowquic + +import ( + "context" + "encoding/binary" + "net" + "testing" + "time" + + "github.com/metacubex/jls-quic-go" +) + +func TestParseQUICVersionProfile(t *testing.T) { + supported, versionNegotiation, err := ParseQUICVersionProfile([]string{ + "v1", + "v2", + "rfc9000", + "rfc-9369", + "v1", + }) + if err != nil { + t.Fatal(err) + } + + wantSupported := []quic.Version{quic.Version1, quic.Version2} + if !equalQUICVersions(supported, wantSupported) { + t.Fatalf("supported versions = %v, want %v", supported, wantSupported) + } + + wantVN := []quic.Version{quic.Version1, quic.Version2} + if !equalQUICVersions(versionNegotiation, wantVN) { + t.Fatalf("VN versions = %v, want %v", versionNegotiation, wantVN) + } +} + +func TestParseQUICVersionProfileRejectsUnsupportedVersions(t *testing.T) { + for _, version := range []string{"draft-29", "0xabcd0000", "v3"} { + t.Run(version, func(t *testing.T) { + if _, _, err := ParseQUICVersionProfile([]string{version}); err == nil { + t.Fatalf("ParseQUICVersionProfile(%q) succeeded", version) + } + }) + } +} + +func TestNormalizeQUICVersionProfileFallsBackToV1Support(t *testing.T) { + supported, versionNegotiation := NormalizeQUICVersionProfile([]quic.Version{0xff00001d, 0xabcd0000}) + wantSupported := []quic.Version{quic.Version1} + if !equalQUICVersions(supported, wantSupported) { + t.Fatalf("supported versions = %v, want %v", supported, wantSupported) + } + wantVN := []quic.Version{quic.Version1} + if !equalQUICVersions(versionNegotiation, wantVN) { + t.Fatalf("VN versions = %v, want %v", versionNegotiation, wantVN) + } +} + +func TestResolveQUICVersionProfileUsesConfiguredProfile(t *testing.T) { + supported, versionNegotiation, provider, err := ResolveQUICVersionProfile( + []string{"v2", "v1"}, + "127.0.0.1:443", + false, + nil, + nil, + ) + if err != nil { + t.Fatal(err) + } + if provider != nil { + t.Fatal("static profile should not install a lazy probe") + } + if !equalQUICVersions(supported, []quic.Version{quic.Version2, quic.Version1}) { + t.Fatalf("supported versions = %v", supported) + } + if !equalQUICVersions(versionNegotiation, []quic.Version{quic.Version2, quic.Version1}) { + t.Fatalf("VN versions = %v", versionNegotiation) + } +} + +func TestResolveQUICVersionProfileDefersProbe(t *testing.T) { + upstream, err := net.ListenPacket("udp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer upstream.Close() + + supported, versionNegotiation, provider, err := ResolveQUICVersionProfile( + nil, + upstream.LocalAddr().String(), + true, + testJLSPacketDialer(t), + nil, + ) + if err != nil { + t.Fatal(err) + } + if provider == nil { + t.Fatal("probe-enabled upstream did not install a lazy profile") + } + if !equalQUICVersions(supported, []quic.Version{quic.Version1}) { + t.Fatalf("fallback supported versions = %v", supported) + } + if !equalQUICVersions(versionNegotiation, DefaultQUICVersionNegotiationVersions()) { + t.Fatalf("fallback VN versions = %v", versionNegotiation) + } + + if err := upstream.SetReadDeadline(time.Now().Add(50 * time.Millisecond)); err != nil { + t.Fatal(err) + } + buf := make([]byte, 1500) + _, _, err = upstream.ReadFrom(buf) + if netErr, ok := err.(net.Error); !ok || !netErr.Timeout() { + t.Fatalf("probe ran before the lazy profile was used: %v", err) + } + + wantVersions := []quic.Version{quic.Version2, 0xff00001d, quic.Version1, 0xabcd0000} + done := make(chan struct{}) + go func() { + defer close(done) + if err := upstream.SetReadDeadline(time.Now().Add(time.Second)); err != nil { + return + } + _, addr, err := upstream.ReadFrom(buf) + if err != nil { + return + } + _, _ = upstream.WriteTo(composeVNResponse(wantVersions), addr) + }() + + gotSupported, gotVN := provider() + <-done + if !equalQUICVersions(gotSupported, []quic.Version{quic.Version2, quic.Version1}) { + t.Fatalf("lazy supported versions = %v", gotSupported) + } + wantNormalized := wantVersions + if !equalQUICVersions(gotVN, wantNormalized) { + t.Fatalf("lazy VN versions = %v, want %v", gotVN, wantNormalized) + } +} + +func TestLazyQUICVersionProfileKeepsFallbackForUnsupportedProbe(t *testing.T) { + upstream, err := net.ListenPacket("udp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer upstream.Close() + + done := make(chan struct{}) + go func() { + defer close(done) + buf := make([]byte, 1500) + if err := upstream.SetReadDeadline(time.Now().Add(time.Second)); err != nil { + return + } + _, addr, err := upstream.ReadFrom(buf) + if err != nil { + return + } + _, _ = upstream.WriteTo(composeVNResponse([]quic.Version{0xff00001d, 0xabcd0000}), addr) + }() + + probeErr := make(chan error, 1) + fallback := []quic.Version{quic.Version2} + provider := NewLazyQUICVersionProfile( + upstream.LocalAddr().String(), + testJLSPacketDialer(t), + fallback, + fallback, + func(err error) { probeErr <- err }, + ) + supported, versionNegotiation := provider() + <-done + if !equalQUICVersions(supported, fallback) || !equalQUICVersions(versionNegotiation, fallback) { + t.Fatalf("profile after unsupported probe: supported=%v VN=%v, want %v", supported, versionNegotiation, fallback) + } + select { + case err := <-probeErr: + if err == nil { + t.Fatal("unsupported probe reported a nil error") + } + default: + t.Fatal("unsupported probe did not report an error") + } +} + +func TestProbeQUICVersionNegotiation(t *testing.T) { + upstream, err := net.ListenPacket("udp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer upstream.Close() + + wantVersions := []quic.Version{quic.Version1, quic.Version2, 0xff00001d} + done := make(chan struct{}) + go func() { + defer close(done) + buf := make([]byte, 1500) + if err := upstream.SetReadDeadline(time.Now().Add(time.Second)); err != nil { + return + } + _, addr, err := upstream.ReadFrom(buf) + if err != nil { + return + } + _, _ = upstream.WriteTo(composeVNResponse(wantVersions), addr) + }() + + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + gotVersions, err := ProbeQUICVersionNegotiation(ctx, upstream.LocalAddr().String(), testJLSPacketDialer(t)) + if err != nil { + t.Fatal(err) + } + <-done + if !equalQUICVersions(gotVersions, wantVersions) { + t.Fatalf("probed versions = %v, want %v", gotVersions, wantVersions) + } +} + +func TestComposeQUICVersionProbeUsesUnsupportedVersion(t *testing.T) { + probe, err := composeQUICVersionProbe() + if err != nil { + t.Fatal(err) + } + version := quic.Version(binary.BigEndian.Uint32(probe[1:5])) + if version == 0 || isSupportedQUICVersion(version) { + t.Fatalf("probe version = %#x, want a non-zero unsupported version", version) + } +} + +func testJLSPacketDialer(t *testing.T) quic.JLSPacketDialer { + t.Helper() + return func(ctx context.Context, network, address string) (net.PacketConn, net.Addr, error) { + if err := ctx.Err(); err != nil { + return nil, nil, err + } + pc, err := net.ListenPacket(network, "127.0.0.1:0") + if err != nil { + return nil, nil, err + } + addr, err := net.ResolveUDPAddr(network, address) + if err != nil { + _ = pc.Close() + return nil, nil, err + } + return pc, addr, nil + } +} + +func composeVNResponse(versions []quic.Version) []byte { + response := []byte{0x80, 0, 0, 0, 0, 0, 0} + for _, version := range versions { + response = binary.BigEndian.AppendUint32(response, uint32(version)) + } + return response +} + +func equalQUICVersions(a, b []quic.Version) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} diff --git a/transport/shadowquic/server.go b/transport/shadowquic/server.go new file mode 100644 index 000000000..8e75e53cc --- /dev/null +++ b/transport/shadowquic/server.go @@ -0,0 +1,206 @@ +package shadowquic + +import ( + "context" + "fmt" + "net" + + "github.com/metacubex/mihomo/adapter/inbound" + N "github.com/metacubex/mihomo/common/net" + C "github.com/metacubex/mihomo/constant" + "github.com/metacubex/mihomo/transport/socks5" + + "github.com/metacubex/jls-quic-go" + "github.com/metacubex/jls-tls" +) + +type ServerOption struct { + HandleTcpFn func(conn net.Conn, addr socks5.Addr, additions ...inbound.Addition) error + HandleUdpFn func(addr socks5.Addr, packet C.UDPPacket, additions ...inbound.Addition) error + + TLSConfig *tls.Config + QUICConfig *quic.Config + + CongestionController string + CWND int + BBRProfile string +} + +type Server struct { + option *ServerOption + listener *quic.EarlyListener +} + +func NewServer(option *ServerOption, pc net.PacketConn) (*Server, error) { + listener, err := quic.ListenEarly(pc, option.TLSConfig, option.QUICConfig) + if err != nil { + return nil, err + } + return &Server{option: option, listener: listener}, nil +} + +func (s *Server) Serve() error { + for { + conn, err := s.listener.Accept(context.Background()) + if err != nil { + return err + } + SetCongestionController(conn, s.option.CongestionController, s.option.CWND, s.option.BBRProfile) + state := newConnState(conn) + go s.handleConnection(state) + } +} + +func (s *Server) Close() error { + return s.listener.Close() +} + +func (s *Server) handleConnection(state *connState) { + for { + stream, err := state.quicConn.AcceptStream(state.ctx) + if err != nil { + state.cancel() + return + } + go s.handleStream(state, stream) + } +} + +func (s *Server) handleStream(state *connState, stream *quic.Stream) { + conn := NewQuicStreamConn(stream, state.quicConn.LocalAddr(), state.quicConn.RemoteAddr(), nil) + command, err := ReadCommand(conn) + if err != nil { + _ = conn.Close() + return + } + + switch command { + case CommandConnect: + target, err := ReadRequestAddr(conn) + if err != nil { + _ = conn.Close() + return + } + if s.option.HandleTcpFn == nil { + _ = conn.Close() + return + } + if err = s.option.HandleTcpFn(conn, target, s.jlsAdditions(state)...); err != nil { + _ = conn.Close() + } + case CommandAssociateDatagram, CommandAssociateStream: + if _, err := ReadRequestAddr(conn); err != nil { + _ = conn.Close() + return + } + if s.option.HandleUdpFn == nil { + _ = conn.Close() + return + } + mode := udpModeDatagram + if command == CommandAssociateStream { + mode = udpModeStream + } + assoc := newAssociation(state, stream, mode) + go s.handleAssociation(assoc) + case CommandExtension: + s.handleExtension(state, conn) + case CommandBind, CommandAuthenticate: + fallthrough + default: + _ = conn.Close() + } +} + +func (s *Server) handleExtension(state *connState, conn net.Conn) { + defer conn.Close() + + opcode, err := ReadExtensionOpcode(conn) + if err != nil { + return + } + switch opcode { + case extensionOpcodeConn: + subcommand, err := readExtensionSubcommand(conn) + if err != nil { + return + } + if subcommand != extensionConnGetStats { + _ = WriteExtensionErrorResult(conn, extensionErrNotAvailable, "") + return + } + _ = WriteExtensionConnStatsResult(conn, shadowQUICConnStats(state.quicConn)) + case extensionOpcodeUser: + // Intentionally unsupported: the reference implementation grants remote + // management to every username prefixed with "admin". Without an explicit + // opt-in and persistence model, that would be a surprising control plane. + // Keep returning NotAvailable unless such a model is deliberately added. + if _, err := readExtensionSubcommand(conn); err != nil { + return + } + _ = WriteExtensionErrorResult(conn, extensionErrNotAvailable, "") + default: + _ = WriteExtensionErrorResult(conn, extensionErrNotAvailable, "") + } +} + +func (s *Server) handleAssociation(assoc *association) { + rAddr := N.NewCustomAddr("shadowquic", fmt.Sprintf("shadowquic-%p", assoc), assoc.parent.quicConn.RemoteAddr()) + additions := s.jlsAdditions(assoc.parent) + for { + select { + case packet := <-assoc.input: + s.option.HandleUdpFn(packet.socksAddr, &serverUDPPacket{ + assoc: assoc, + data: packet.data, + rAddr: rAddr, + }, additions...) + case <-assoc.closed: + return + } + } +} + +func (s *Server) jlsAdditions(state *connState) []inbound.Addition { + if user := s.jlsUser(state); user != "" { + return []inbound.Addition{inbound.WithInUser(user)} + } + return nil +} + +func (s *Server) jlsUser(state *connState) string { + tlsState := state.quicConn.ConnectionState().TLS + if tlsState.JLS.Authenticated { + return tlsState.JLS.User + } + return "" +} + +type serverUDPPacket struct { + assoc *association + data []byte + rAddr net.Addr +} + +func (p *serverUDPPacket) Data() []byte { + return p.data +} + +func (p *serverUDPPacket) WriteBack(b []byte, addr net.Addr) (int, error) { + return p.assoc.WriteTo(b, addr) +} + +func (p *serverUDPPacket) Drop() { + p.data = nil +} + +func (p *serverUDPPacket) LocalAddr() net.Addr { + return p.rAddr +} + +func (p *serverUDPPacket) InAddr() net.Addr { + return p.assoc.LocalAddr() +} + +var _ C.UDPPacket = (*serverUDPPacket)(nil) +var _ C.UDPPacketInAddr = (*serverUDPPacket)(nil) diff --git a/transport/shadowquic/state.go b/transport/shadowquic/state.go new file mode 100644 index 000000000..dc2a3b64c --- /dev/null +++ b/transport/shadowquic/state.go @@ -0,0 +1,258 @@ +package shadowquic + +import ( + "context" + "io" + "net" + "sync" + + "github.com/metacubex/mihomo/transport/socks5" + + "github.com/metacubex/jls-quic-go" +) + +const maxPendingPacketsPerID = 32 + +type udpMode uint8 + +const ( + udpModeDatagram udpMode = iota + udpModeStream +) + +type receivedPacket struct { + data []byte + addr net.Addr + socksAddr socks5.Addr +} + +type connState struct { + quicConn *quic.Conn + ctx context.Context + cancel context.CancelFunc + + mu sync.Mutex + nextID uint16 + activeSend map[uint16]struct{} + recv map[uint16]*recvSlot +} + +type recvSlot struct { + ready chan struct{} + target *recvTarget + pending [][]byte +} + +type recvTarget struct { + assoc *association + addr socks5.Addr + net net.Addr +} + +func newConnState(quicConn *quic.Conn) *connState { + ctx, cancel := context.WithCancel(quicConn.Context()) + state := &connState{ + quicConn: quicConn, + ctx: ctx, + cancel: cancel, + activeSend: make(map[uint16]struct{}), + recv: make(map[uint16]*recvSlot), + } + go state.handleDatagrams() + go state.handleUniStreams() + go func() { + <-quicConn.Context().Done() + cancel() + }() + return state +} + +func (s *connState) closed() bool { + select { + case <-s.ctx.Done(): + return true + default: + return false + } +} + +func (s *connState) closeWithError(code quic.ApplicationErrorCode, message string) error { + s.cancel() + return s.quicConn.CloseWithError(code, message) +} + +func (s *connState) handleDatagrams() { + for { + message, err := s.quicConn.ReceiveDatagram(s.ctx) + if err != nil { + s.cancel() + return + } + id, payload, err := DecodeDatagram(message) + if err != nil { + continue + } + s.feedDatagram(id, payload) + } +} + +func (s *connState) handleUniStreams() { + for { + stream, err := s.quicConn.AcceptUniStream(s.ctx) + if err != nil { + s.cancel() + return + } + go s.handleUniStream(stream) + } +} + +func (s *connState) handleUniStream(stream *quic.ReceiveStream) { + defer stream.CancelRead(0) + + id, err := ReadUint16(stream) + if err != nil { + return + } + target, err := s.waitRecvTarget(id) + if err != nil { + return + } + + for { + length, err := ReadUint16(stream) + if err != nil { + return + } + payload := make([]byte, int(length)) + if _, err = io.ReadFull(stream, payload); err != nil { + return + } + target.assoc.deliver(receivedPacket{ + data: payload, + addr: target.net, + socksAddr: target.addr, + }) + } +} + +func (s *connState) feedDatagram(id uint16, payload []byte) { + s.mu.Lock() + slot := s.recv[id] + if slot != nil && slot.target != nil { + target := slot.target + s.mu.Unlock() + target.assoc.deliver(receivedPacket{ + data: payload, + addr: target.net, + socksAddr: target.addr, + }) + return + } + if slot == nil { + slot = &recvSlot{ready: make(chan struct{})} + s.recv[id] = slot + } + if len(slot.pending) < maxPendingPacketsPerID { + packet := make([]byte, len(payload)) + copy(packet, payload) + slot.pending = append(slot.pending, packet) + } + s.mu.Unlock() +} + +func (s *connState) waitRecvTarget(id uint16) (*recvTarget, error) { + for { + s.mu.Lock() + slot := s.recv[id] + if slot == nil { + slot = &recvSlot{ready: make(chan struct{})} + s.recv[id] = slot + } + if slot.target != nil { + target := slot.target + s.mu.Unlock() + return target, nil + } + ready := slot.ready + s.mu.Unlock() + + select { + case <-ready: + case <-s.ctx.Done(): + return nil, net.ErrClosed + } + } +} + +func (s *connState) storeRecv(id uint16, assoc *association, addr socks5.Addr) { + netAddr := AddrToNetAddr(addr) + + s.mu.Lock() + slot := s.recv[id] + if slot == nil { + slot = &recvSlot{ready: make(chan struct{})} + s.recv[id] = slot + } + wasPending := slot.target == nil + slot.target = &recvTarget{assoc: assoc, addr: addr, net: netAddr} + pending := slot.pending + slot.pending = nil + if wasPending { + close(slot.ready) + } + s.mu.Unlock() + + for _, packet := range pending { + assoc.deliver(receivedPacket{ + data: packet, + addr: netAddr, + socksAddr: addr, + }) + } +} + +func (s *connState) removeRecvIDs(assoc *association, ids map[uint16]struct{}) { + s.mu.Lock() + defer s.mu.Unlock() + + for id := range ids { + slot := s.recv[id] + if slot != nil && slot.target != nil && slot.target.assoc == assoc { + delete(s.recv, id) + } + } +} + +func (s *connState) allocSendID() (uint16, error) { + s.mu.Lock() + defer s.mu.Unlock() + + start := s.nextID + for { + id := s.nextID + s.nextID++ + if _, exists := s.activeSend[id]; !exists { + s.activeSend[id] = struct{}{} + return id, nil + } + if s.nextID == start { + return 0, errorsTooManyUDPContexts{} + } + } +} + +func (s *connState) releaseSendIDs(ids map[uint16]struct{}) { + s.mu.Lock() + defer s.mu.Unlock() + + for id := range ids { + delete(s.activeSend, id) + } +} + +type errorsTooManyUDPContexts struct{} + +func (errorsTooManyUDPContexts) Error() string { + return "shadowquic: too many udp contexts" +} diff --git a/transport/shadowquic/stream_conn.go b/transport/shadowquic/stream_conn.go new file mode 100644 index 000000000..f74a26a61 --- /dev/null +++ b/transport/shadowquic/stream_conn.go @@ -0,0 +1,62 @@ +package shadowquic + +import ( + "net" + "sync" + "time" + + "github.com/metacubex/jls-quic-go" +) + +type quicStreamConn struct { + *quic.Stream + lock sync.Mutex + lAddr net.Addr + rAddr net.Addr + + closeDeferFn func() + + closeOnce sync.Once + closeErr error +} + +func (q *quicStreamConn) Write(p []byte) (n int, err error) { + q.lock.Lock() + defer q.lock.Unlock() + return q.Stream.Write(p) +} + +func (q *quicStreamConn) Close() error { + q.closeOnce.Do(func() { + q.closeErr = q.close() + }) + return q.closeErr +} + +func (q *quicStreamConn) close() error { + if q.closeDeferFn != nil { + defer q.closeDeferFn() + } + + _ = q.Stream.SetWriteDeadline(time.Now()) + + q.lock.Lock() + defer q.lock.Unlock() + + q.Stream.CancelRead(0) + return q.Stream.Close() +} + +func (q *quicStreamConn) LocalAddr() net.Addr { + return q.lAddr +} + +func (q *quicStreamConn) RemoteAddr() net.Addr { + return q.rAddr +} + +func NewQuicStreamConn(stream *quic.Stream, lAddr, rAddr net.Addr, closeDeferFn func()) net.Conn { + return &quicStreamConn{Stream: stream, lAddr: lAddr, rAddr: rAddr, closeDeferFn: closeDeferFn} +} + +var _ net.Conn = (*quicStreamConn)(nil)