From a2f7952a4f8093838e52670441fb5514d057768e Mon Sep 17 00:00:00 2001 From: Markson GuGa Beyond Date: Tue, 29 Sep 2026 18:54:02 +0800 Subject: [PATCH] fix: juicity and tuic dial, and a QUIC-only node gets a latency Every core the service starts has outbound traffic counters on, and with them on xray wraps the underlay connection of a native QUIC outbound in a *stat.CounterConnection. That wrapper embeds net.Conn alone, so ReadFrom and WriteTo are hidden and hint/proxy/juicity and hint/proxy/tuic failed their net.PacketConn assertion before a single QUIC packet left: the node imported, and then every connection through it died on the spot. Unwrap the stats connection before the assertion. A QUIC server listens on UDP only, so the TCP dial the ping made to its port said nothing and every juicity, tuic and hysteria2 node read TIMEOUT. Keep the TCP attempt, and when it fails ask the same port over UDP with a QUIC long header carrying a reserved greased version: a QUIC server answers that with a Version Negotiation packet (RFC 9000 section 6), and the round trip of that answer is the latency. A node that answers neither probe is still TIMEOUT; the troubleshooting pages in the six locales describe that. --- core/hint/proxy/juicity/outbound.go | 11 ++-- core/hint/proxy/tuic/outbound.go | 11 ++-- gui/src/docs/en/troubleshooting.md | 2 +- gui/src/docs/fa/troubleshooting.md | 2 +- gui/src/docs/ko/troubleshooting.md | 2 +- gui/src/docs/pt/troubleshooting.md | 2 +- gui/src/docs/ru/troubleshooting.md | 2 +- gui/src/docs/zh/troubleshooting.md | 2 +- service/db/configure/quicping.go | 79 +++++++++++++++++++++++++++++ service/db/configure/which.go | 17 +++++-- 10 files changed, 114 insertions(+), 16 deletions(-) create mode 100644 service/db/configure/quicping.go diff --git a/core/hint/proxy/juicity/outbound.go b/core/hint/proxy/juicity/outbound.go index 28c0faee..afe4b2df 100644 --- a/core/hint/proxy/juicity/outbound.go +++ b/core/hint/proxy/juicity/outbound.go @@ -23,6 +23,7 @@ import ( "github.com/xtls/xray-core/common/task" "github.com/xtls/xray-core/transport" "github.com/xtls/xray-core/transport/internet" + "github.com/xtls/xray-core/transport/internet/stat" "github.com/v2rayA/v2raya-core/hint/tlsutil" ) @@ -108,13 +109,17 @@ func (d xrayDialer) DialContext(ctx context.Context, network, addr string) (outb } // QUIC-based protocols assert the underlay conn to netproxy.PacketConn, // whose ReadFrom/WriteTo signatures differ from net.PacketConn. xray's UDP - // dial returns *internet.PacketConnWrapper, so adapt it here. + // dial returns *internet.PacketConnWrapper, so adapt it here. With outbound + // traffic counters on, xray hands back a *stat.CounterConnection around it, + // which embeds net.Conn and therefore hides ReadFrom and WriteTo; unwrap it + // or the QUIC stack below never sees a packet conn. if destination.Network == xray_net.Network_UDP { - if pc, ok := conn.(net.PacketConn); ok { + underlay := stat.TryUnwrapStatsConn(conn) + if pc, ok := underlay.(net.PacketConn); ok { return &packetConnAdapter{conn: conn, pc: pc}, nil } conn.Close() - return nil, fmt.Errorf("juicity: UDP dial returned %T, which is not a net.PacketConn", conn) + return nil, fmt.Errorf("juicity: UDP dial returned %T, which is not a net.PacketConn", underlay) } return conn, nil } diff --git a/core/hint/proxy/tuic/outbound.go b/core/hint/proxy/tuic/outbound.go index 1cd3d0d1..fbcca8a7 100644 --- a/core/hint/proxy/tuic/outbound.go +++ b/core/hint/proxy/tuic/outbound.go @@ -24,6 +24,7 @@ import ( "github.com/xtls/xray-core/common/task" "github.com/xtls/xray-core/transport" "github.com/xtls/xray-core/transport/internet" + "github.com/xtls/xray-core/transport/internet/stat" "github.com/v2rayA/v2raya-core/hint/tlsutil" ) @@ -117,13 +118,17 @@ func (d xrayDialer) DialContext(ctx context.Context, network, addr string) (outb } // QUIC-based protocols assert the underlay conn to netproxy.PacketConn, // whose ReadFrom/WriteTo signatures differ from net.PacketConn. xray's UDP - // dial returns *internet.PacketConnWrapper, so adapt it here. + // dial returns *internet.PacketConnWrapper, so adapt it here. With outbound + // traffic counters on, xray hands back a *stat.CounterConnection around it, + // which embeds net.Conn and therefore hides ReadFrom and WriteTo; unwrap it + // or the QUIC stack below never sees a packet conn. if destination.Network == xray_net.Network_UDP { - if pc, ok := conn.(net.PacketConn); ok { + underlay := stat.TryUnwrapStatsConn(conn) + if pc, ok := underlay.(net.PacketConn); ok { return &packetConnAdapter{conn: conn, pc: pc}, nil } conn.Close() - return nil, fmt.Errorf("tuic: UDP dial returned %T, which is not a net.PacketConn", conn) + return nil, fmt.Errorf("tuic: UDP dial returned %T, which is not a net.PacketConn", underlay) } return conn, nil } diff --git a/gui/src/docs/en/troubleshooting.md b/gui/src/docs/en/troubleshooting.md index 01792b95..5454931b 100644 --- a/gui/src/docs/en/troubleshooting.md +++ b/gui/src/docs/en/troubleshooting.md @@ -13,7 +13,7 @@ The service log is the first place to look: `/var/log/v2raya/v2raya.log` under t ## Nothing connects -- The dashboard shows the group and its members' latency. `TIMEOUT` means the TCP connection to the server failed from this machine; try another node or check the subscription. +- The dashboard shows the group and its members' latency. Nodes are probed over TCP, and over UDP with a QUIC packet when TCP fails, so servers that listen on UDP only (juicity, tuic, hysteria2) are measured too; `TIMEOUT` means neither probe reached the server from this machine. Try another node or check the subscription. - Test one inbound directly: `curl -x socks5h://127.0.0.1:20170 https://example.com`. If that works and the transparent proxy does not, look at the transparent proxy setup, the DNS rules and the group the transparent proxy routes to before blaming the node. - With `redirect` or `tproxy`, Docker or a firewall may have replaced the iptables rules; stop and start the core to reinstall them. - On Windows and macOS, an application that asks a LAN resolver directly for DNS bypasses the TUN. diff --git a/gui/src/docs/fa/troubleshooting.md b/gui/src/docs/fa/troubleshooting.md index 72297032..da773c23 100644 --- a/gui/src/docs/fa/troubleshooting.md +++ b/gui/src/docs/fa/troubleshooting.md @@ -13,7 +13,7 @@ ## هیچ اتصالی برقرار نمی‌شود -- داشبورد، گروه و تأخیر اعضای آن را نشان می‌دهد. `TIMEOUT` یعنی اتصال TCP از این دستگاه به سرور ناموفق بوده است؛ گره دیگری را امتحان کنید یا اشتراک را بررسی کنید. +- داشبورد، گروه و تأخیر اعضای آن را نشان می‌دهد. هر گره نخست با TCP و در صورت ناکامی با یک بستهٔ QUIC روی UDP کاوش می‌شود، پس سرورهایی که فقط UDP را می‌شنوند (juicity، tuic، hysteria2) هم اندازه‌گیری می‌شوند؛ `TIMEOUT` یعنی هیچ‌یک از این دو کاوش از این دستگاه به سرور نرسیده است؛ گره دیگری را امتحان کنید یا اشتراک را بررسی کنید. - یک ورودی را مستقیم آزمایش کنید: `curl -x socks5h://127.0.0.1:20170 https://example.com`. اگر کار کرد ولی پروکسی شفاف کار نکرد، پیش از نسبت دادن مشکل به گره، تنظیمات پروکسی شفاف، قوانین DNS و گروهی را که پروکسی شفاف ترافیک را به آن می‌فرستد بررسی کنید. - در حالت `redirect` یا `tproxy`، ممکن است Docker یا دیوار آتش قوانین iptables را جایگزین کرده باشد؛ هسته را متوقف و دوباره راه‌اندازی کنید تا قوانین دوباره نصب شوند. - در Windows و macOS، برنامه‌ای که مستقیماً از حل‌کنندهٔ نام شبکهٔ محلی درخواست DNS می‌کند، از TUN عبور نمی‌کند. diff --git a/gui/src/docs/ko/troubleshooting.md b/gui/src/docs/ko/troubleshooting.md index 54c34bb6..6938fb43 100644 --- a/gui/src/docs/ko/troubleshooting.md +++ b/gui/src/docs/ko/troubleshooting.md @@ -13,7 +13,7 @@ ## 아무것도 연결되지 않음 -- 대시보드는 그룹과 구성원의 지연 시간을 표시합니다. `TIMEOUT`은 이 컴퓨터에서 서버로 TCP 연결을 맺지 못했다는 뜻입니다. 다른 노드를 사용하거나 구독을 확인하세요. +- 대시보드는 그룹과 구성원의 지연 시간을 표시합니다. 노드는 먼저 TCP로, 실패하면 UDP의 QUIC 패킷으로 확인하므로 UDP만 수신하는 서버(juicity, tuic, hysteria2)도 측정됩니다. `TIMEOUT`은 두 확인 모두 이 컴퓨터에서 서버에 도달하지 못했다는 뜻입니다. 다른 노드를 사용하거나 구독을 확인하세요. - 인바운드 하나를 직접 테스트하세요: `curl -x socks5h://127.0.0.1:20170 https://example.com`. 이 명령은 성공하지만 투명 프록시가 작동하지 않으면, 노드 문제로 판단하기 전에 투명 프록시 설정, DNS 규칙, 투명 프록시가 트래픽을 보내는 그룹을 확인하세요. - `redirect`나 `tproxy`를 사용한다면 Docker 또는 방화벽이 iptables 규칙을 덮어썼을 수 있습니다. 코어를 중지했다가 시작해 규칙을 다시 적용하세요. - Windows와 macOS에서 LAN 리졸버에 직접 DNS를 질의하는 애플리케이션은 TUN을 우회합니다. diff --git a/gui/src/docs/pt/troubleshooting.md b/gui/src/docs/pt/troubleshooting.md index 45626f9e..a91222ff 100644 --- a/gui/src/docs/pt/troubleshooting.md +++ b/gui/src/docs/pt/troubleshooting.md @@ -13,7 +13,7 @@ Consulte primeiro o registro do serviço: `/var/log/v2raya/v2raya.log` quando ex ## Nada se conecta -- O painel mostra o grupo e a latência de seus membros. `TIMEOUT` significa que a conexão TCP desta máquina com o servidor falhou; tente outro nó ou verifique a assinatura. +- O painel mostra o grupo e a latência de seus membros. Cada nó é sondado primeiro por TCP e, se falhar, por um pacote QUIC sobre UDP, de modo que servidores que só escutam UDP (juicity, tuic, hysteria2) também são medidos; `TIMEOUT` significa que nenhuma das sondagens alcançou o servidor desta máquina; tente outro nó ou verifique a assinatura. - Teste uma entrada diretamente: `curl -x socks5h://127.0.0.1:20170 https://example.com`. Se funcionar, mas o proxy transparente não, verifique a configuração do proxy transparente, as regras de DNS e o grupo para o qual o proxy transparente roteia antes de atribuir o problema ao nó. - Com `redirect` ou `tproxy`, o Docker ou um firewall pode ter substituído as regras do iptables; pare e inicie o núcleo para reinstalá-las. - No Windows e no macOS, um aplicativo que consulta DNS diretamente em um resolvedor da rede local não passa pelo TUN. diff --git a/gui/src/docs/ru/troubleshooting.md b/gui/src/docs/ru/troubleshooting.md index 12acd866..e9a22d44 100644 --- a/gui/src/docs/ru/troubleshooting.md +++ b/gui/src/docs/ru/troubleshooting.md @@ -13,7 +13,7 @@ ## Нет соединения -- Панель показывает группу и задержку её участников. `TIMEOUT` означает, что с этого компьютера не удалось установить TCP-соединение с сервером; попробуйте другой узел или проверьте подписку. +- Панель показывает группу и задержку её участников. Узел сначала проверяется по TCP, а при неудаче — QUIC-пакетом по UDP, поэтому серверы, слушающие только UDP (juicity, tuic, hysteria2), тоже измеряются; `TIMEOUT` означает, что ни одна из проверок не достигла сервера с этого компьютера; попробуйте другой узел или проверьте подписку. - Проверьте один входящий порт напрямую: `curl -x socks5h://127.0.0.1:20170 https://example.com`. Если он работает, а прозрачный прокси — нет, прежде чем искать причину в узле, проверьте настройку прозрачного прокси, правила DNS и группу, в которую прозрачный прокси направляет трафик. - При использовании `redirect` или `tproxy` Docker или межсетевой экран могли заменить правила iptables; остановите и запустите ядро, чтобы установить их заново. - В Windows и macOS приложение, напрямую запрашивающее DNS-сервер локальной сети, обходит TUN. diff --git a/gui/src/docs/zh/troubleshooting.md b/gui/src/docs/zh/troubleshooting.md index b16f060e..237240c0 100644 --- a/gui/src/docs/zh/troubleshooting.md +++ b/gui/src/docs/zh/troubleshooting.md @@ -13,7 +13,7 @@ ## 无法连接 -- 仪表板显示分组及成员延迟。`TIMEOUT` 表示本机到该服务器的 TCP 连接失败;换一个节点或检查订阅。 +- 仪表板显示分组及成员延迟。节点先按 TCP 探测,TCP 不通时再用 QUIC 报文按 UDP 探测,因此只监听 UDP 的服务器(juicity、tuic、hysteria2)也能测出延迟;`TIMEOUT` 表示两种探测都没能到达该服务器;换一个节点或检查订阅。 - 直接测试一个入站:`curl -x socks5h://127.0.0.1:20170 https://example.com`。入站可用而透明代理不可用时,先查透明代理的配置、DNS 规则和透明代理所走的分组,再怀疑节点。 - 使用 `redirect` 或 `tproxy` 时,Docker 或防火墙可能改写了 iptables 规则;停止再启动内核可重新安装。 - Windows 与 macOS 上直接向局域网 DNS 查询的应用会绕过 TUN。 diff --git a/service/db/configure/quicping.go b/service/db/configure/quicping.go new file mode 100644 index 00000000..61b6d3d6 --- /dev/null +++ b/service/db/configure/quicping.go @@ -0,0 +1,79 @@ +package configure + +import ( + "encoding/binary" + "net" + "strconv" + "time" +) + +// A node whose server speaks QUIC (juicity, tuic, hysteria2) listens on UDP +// only, so the TCP dial in Ping fails for a server that is there. A QUIC server +// answers a long header packet carrying a version it does not implement with a +// Version Negotiation packet (RFC 9000 section 6), and that answer is a round +// trip to the node. +const ( + // quicProbeVersion is one of the reserved "grease" versions (0x?a?a?a?a): + // no implementation implements it, which is what makes a server answer + // instead of dropping the packet. + quicProbeVersion = 0x1a2a3a4a + // quicProbeSize is the smallest datagram a QUIC server accepts a packet + // with an unknown version to have. + quicProbeSize = 1200 + // quicProbeConnIDLen is the destination connection ID length the probe + // carries. Its bytes are left zero: the server only echoes them. + quicProbeConnIDLen = 8 +) + +// pingUDP measures a round trip to a QUIC server at host:port. It fails when no +// Version Negotiation comes back within timeout, which is also what a server +// that is not there, or is not QUIC, does. +func pingUDP(host string, port int, timeout time.Duration) (time.Duration, error) { + addr, err := net.ResolveUDPAddr("udp", net.JoinHostPort(host, strconv.Itoa(port))) + if err != nil { + return 0, err + } + conn, err := net.DialUDP("udp", nil, addr) + if err != nil { + return 0, err + } + defer conn.Close() + if err = conn.SetDeadline(time.Now().Add(timeout)); err != nil { + return 0, err + } + started := time.Now() + if _, err = conn.Write(quicProbePacket()); err != nil { + return 0, err + } + reply := make([]byte, 512) + for { + n, err := conn.Read(reply) + if err != nil { + return 0, err + } + if isVersionNegotiation(reply[:n]) { + return time.Since(started), nil + } + // The socket is connected, so anything else comes from the server's + // port too but is not the answer; keep the deadline and read again. + } +} + +// quicProbePacket builds the long header probe. A packet carrying a version we +// do not implement carries only the fields RFC 8999 section 5.1 fixes: the +// header form and the fixed bit, the version, the connection ID lengths and the +// IDs. The rest is padding to quicProbeSize. +func quicProbePacket() []byte { + packet := make([]byte, quicProbeSize) + packet[0] = 0xc0 // long header, fixed bit, Initial type + binary.BigEndian.PutUint32(packet[1:5], quicProbeVersion) + packet[5] = quicProbeConnIDLen + packet[6+quicProbeConnIDLen] = 0 // source connection ID length + return packet +} + +// isVersionNegotiation reports a packet in the Version Negotiation format: a +// long header whose version field is zero. +func isVersionNegotiation(packet []byte) bool { + return len(packet) >= 5 && packet[0]&0x80 != 0 && binary.BigEndian.Uint32(packet[1:5]) == 0 +} diff --git a/service/db/configure/which.go b/service/db/configure/which.go index 44efd0d6..5ae380e3 100644 --- a/service/db/configure/which.go +++ b/service/db/configure/which.go @@ -259,15 +259,24 @@ func (w *Which) Ping(loc *Locator, timeout time.Duration) (err error) { } host = hosts[0] } + addr := net.JoinHostPort(host, strconv.Itoa(tsr.ServerObj.GetPort())) t := time.Now() - conn, e := net.DialTimeout("tcp", net.JoinHostPort(host, strconv.Itoa(tsr.ServerObj.GetPort())), timeout) + conn, e := net.DialTimeout("tcp", addr, timeout) if e == nil { _ = conn.Close() w.Latency = fmt.Sprintf("%.0fms", time.Since(t).Seconds()*1000) - } else { - log.Debug("Ping: %v", e) - w.Latency = "TIMEOUT" + return } + // A node whose server speaks QUIC listens on UDP only, and the refused TCP + // dial says nothing about it: ask its UDP port before calling it unreachable. + roundTrip, probeErr := pingUDP(host, tsr.ServerObj.GetPort(), timeout) + if probeErr == nil { + log.Debug("Ping: TCP to %v failed (%v), QUIC round trip %v", addr, e, roundTrip) + w.Latency = fmt.Sprintf("%.0fms", roundTrip.Seconds()*1000) + return + } + log.Debug("Ping: %v", e) + w.Latency = "TIMEOUT" return }