mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-10-03 20:53:41 +03:00
0054e671f8
* feat(tuic): implement native in-process Go TUIC v5 server - Implement native TUIC v5 protocol server on pure Go using quic-go - Bridge decrypted TCP/UDP traffic into Xray-core via loopback SOCKS5 inbound - Support full Xray routing rules (geosite/geoip) and cascading outbounds - Implement atomic per-client traffic accounting with TotalGB and ExpiryTime - Add automatic legacy cleanup for older Rust tuic-server binaries, configs, and orphaned processes - Eliminate external Rust tuic-server downloads from install/CI scripts * fix(tuic): address traffic accounting, client reload, and socket lifecycle issues * fix(service): update checkTuicSocksReverseConflict to use bindAddr for listenOverlaps * fix(tuic): resolve traffic double-accounting, UDP fragmentation, and socket lifecycle issues * feat(tuic): complete native Go integration and address audit findings - Integrate an isolated QUIC fork pinned to a specific commit - Preserve original QUIC dependencies for Xray, Hysteria and Gin - Apply BBR, CUBIC and Reno to server connections and exported client profiles - Bridge Xray BBR with correct monotonic time and congestion type conversions - Handle congestion sender recreation after PMTU changes - Update congestion control for new connections without restarting the listener - Preserve existing connections and their selected congestion controller - Apply per-inbound log levels through the shared panel logger - Add lifecycle, authentication and TCP/UDP relay events without exposing secrets - Rate-limit repeated authentication and relay warnings - Support native and QUIC UDP relay modes on the same listener - Recover UDP associations after relay worker failures - Fix TCP relay cancellation, idle shutdown and half-close handling - Close active sessions when client credentials are revoked or disabled - Track traffic by immutable client statistics IDs across email and UUID changes - Prevent ambiguous accounting and duplicate UUIDs within TUIC inbounds - Persist pending traffic in a durable shutdown journal - Replay journal batches transactionally without duplicate accounting - Report server shutdown failures through the shared logger - Preserve legacy flat and nested TUIC settings compatibility - Normalize congestion controller values consistently across backend and frontend - Preserve controller, UDP mode and SNI in client links and subscriptions - Separate client profile options from server settings in the TUIC form - Keep certificate path autofill explicit when changing client SNI - Align UDP packet size validation with protocol limits - Simplify and localize TUIC field hints and certificate autofill messages - Add controller, TCP/UDP, logging and live settings update tests - Add accounting identity, journal replay and shutdown regression tests - Add relay recovery, session revocation and legacy frontend form tests * fix(service): alias the TUIC duplicate-UUID subquery for PostgreSQL < 16 syncInboundClients runs a COUNT(*) FROM (subquery) for every client sync, whatever the protocol. PostgreSQL before 16 rejects a FROM subquery with no alias, so on the distro PostgreSQL install.sh provisions (14 on Ubuntu 22.04, 15 on Debian 12) every client add or edit failed with SQLSTATE 42601. Reproduced against postgres:15 with the new env-gated test. * fix(database): create tuic_traffic_receipts through the model migration AddTuicTrafficBatch issued CREATE TABLE IF NOT EXISTS at runtime, a schema change outside db.go. The table was invisible to allModels and migrationModels, so x-ui migrate-db dropped the receipts and a retained journal could be counted twice after a SQLite to PostgreSQL move. It is now a GORM model in both lists, and the insert uses OnConflict DoNothing. * chore(tuic): skip the ICMP-dependent relay test on Windows, drop dead collectors Go disables SIO_UDP_CONNRESET on Windows, so a dead UDP bridge never fails a read there and TestAudit3UDPAssociationMustRecoverAfterBridgeReadFailure was red on every Windows run. Server.CollectTotalTraffic and Manager.CollectTraffic had no caller. * refactor(tuic): serve TUIC on apernet/quic-go instead of a personal fork The native server depended on github.com/poise52/quic-go, a personal fork of apernet/quic-go patched only to pick the congestion controller before the handshake. That put a second QUIC/TLS stack in the binary that no upstream security fix reaches. apernet/quic-go is already in the graph through xray-core and exposes SetCongestionControl, so BBR is now installed on each accepted connection with Xray's own congestion.UseBBR; the cross-module BBR adapter is gone. apernet ships New Reno as its only built-in sender, so a cubic setting is served as new_reno server-side (clients still get cubic in their profile). The test inspectors now read the sender under congestionMutex, which the post-handshake install writes under. Linux loopback, single stream through Xray: 2428 -> 3383 Mbit/s (bbr). --------- Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
274 lines
8.0 KiB
Go
274 lines
8.0 KiB
Go
package tuic
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net"
|
|
"os"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
|
)
|
|
|
|
type TuicServerSettings struct {
|
|
Certificate string `json:"certificate"`
|
|
PrivateKey string `json:"private_key"`
|
|
CongestionControl string `json:"congestion_control"`
|
|
ALPN []string `json:"alpn"`
|
|
UDPRelayMode string `json:"udp_relay_mode"`
|
|
ZeroRTTHandshake bool `json:"zero_rtt_handshake"`
|
|
LogLevel string `json:"log_level"`
|
|
MaxIdleTime int `json:"max_idle_time"`
|
|
AuthenticationTimeout int `json:"authentication_timeout"`
|
|
MaxUdpRelayPacketSize int `json:"max_udp_relay_packet_size"`
|
|
SNI string `json:"sni,omitempty"`
|
|
}
|
|
|
|
type TuicClientSettings struct {
|
|
TrafficID int `json:"-"`
|
|
UUID string `json:"uuid"`
|
|
Password string `json:"password"`
|
|
Email string `json:"email"`
|
|
}
|
|
|
|
type Instance struct {
|
|
Id int
|
|
Tag string
|
|
Listen string
|
|
Port int
|
|
Certificate string
|
|
PrivateKey string
|
|
CongestionControl string // Applied to new native QUIC connections and exported to client profiles.
|
|
ALPN []string
|
|
UDPRelayMode string // Default mode exported to client links; the listener accepts both modes.
|
|
ZeroRTTHandshake bool
|
|
LogLevel string
|
|
MaxIdleTime int
|
|
AuthenticationTimeout int
|
|
MaxUdpRelayPacketSize int
|
|
SNI string // Exported to client links; it doesn't change the native listener certificate.
|
|
Clients []TuicClientSettings
|
|
}
|
|
|
|
func (inst Instance) BindTo() string {
|
|
return net.JoinHostPort(inst.Listen, strconv.Itoa(inst.Port))
|
|
}
|
|
|
|
func (inst Instance) StructuralFingerprint() string {
|
|
parts := []string{
|
|
inst.BindTo(),
|
|
fingerprintMaterial(inst.Certificate),
|
|
fingerprintMaterial(inst.PrivateKey),
|
|
strings.Join(inst.ALPN, ","),
|
|
strconv.FormatBool(inst.ZeroRTTHandshake),
|
|
strconv.Itoa(inst.MaxIdleTime),
|
|
strconv.Itoa(inst.AuthenticationTimeout),
|
|
strconv.Itoa(inst.MaxUdpRelayPacketSize),
|
|
}
|
|
return strings.Join(parts, "|")
|
|
}
|
|
|
|
func fingerprintMaterial(value string) string {
|
|
material := []byte(value)
|
|
if value != "" && !strings.Contains(value, "-----BEGIN ") {
|
|
if file, err := os.ReadFile(value); err == nil {
|
|
material = file
|
|
}
|
|
}
|
|
return fmt.Sprintf("%x", sha256.Sum256(material))
|
|
}
|
|
|
|
func (inst Instance) UsersFingerprint() string {
|
|
pairs := make([]string, 0, len(inst.Clients))
|
|
for _, c := range inst.Clients {
|
|
pairs = append(pairs, fmt.Sprintf("%d:%s=%s:%s", c.TrafficID, c.Email, c.UUID, c.Password))
|
|
}
|
|
slices.Sort(pairs)
|
|
return strings.Join(pairs, "|")
|
|
}
|
|
|
|
func (inst Instance) FullFingerprint() string {
|
|
return inst.StructuralFingerprint() + "#" + inst.UsersFingerprint()
|
|
}
|
|
|
|
func InstanceFromInbound(ib *model.Inbound) (Instance, bool) {
|
|
if ib == nil || ib.Protocol != model.TUIC {
|
|
return Instance{}, false
|
|
}
|
|
|
|
var parsed struct {
|
|
Certificate string `json:"certificate"`
|
|
PrivateKey string `json:"private_key"`
|
|
CongestionControl string `json:"congestion_control"`
|
|
ALPN []string `json:"alpn"`
|
|
UDPRelayMode string `json:"udp_relay_mode"`
|
|
ZeroRTTHandshake *bool `json:"zero_rtt_handshake"`
|
|
LogLevel string `json:"log_level"`
|
|
MaxIdleTime int `json:"max_idle_time"`
|
|
AuthenticationTimeout int `json:"authentication_timeout"`
|
|
MaxUdpRelayPacketSize int `json:"max_udp_relay_packet_size"`
|
|
SNI string `json:"sni"`
|
|
Server *struct {
|
|
Certificate string `json:"certificate"`
|
|
PrivateKey string `json:"private_key"`
|
|
CongestionControl string `json:"congestion_control"`
|
|
ALPN []string `json:"alpn"`
|
|
UDPRelayMode string `json:"udp_relay_mode"`
|
|
ZeroRTTHandshake *bool `json:"zero_rtt_handshake"`
|
|
LogLevel string `json:"log_level"`
|
|
MaxIdleTime int `json:"max_idle_time"`
|
|
AuthenticationTimeout int `json:"authentication_timeout"`
|
|
MaxUdpRelayPacketSize int `json:"max_udp_relay_packet_size"`
|
|
SNI string `json:"sni"`
|
|
} `json:"server"`
|
|
Clients []struct {
|
|
TrafficID int `json:"traffic_id"`
|
|
UUID string `json:"uuid"`
|
|
ID string `json:"id"`
|
|
Password string `json:"password"`
|
|
Email string `json:"email"`
|
|
Enable *bool `json:"enable"`
|
|
TotalGB int64 `json:"totalGB"`
|
|
ExpiryTime int64 `json:"expiryTime"`
|
|
} `json:"clients"`
|
|
}
|
|
|
|
if ib.Settings != "" {
|
|
if err := json.Unmarshal([]byte(ib.Settings), &parsed); err != nil {
|
|
return Instance{}, false
|
|
}
|
|
}
|
|
|
|
cert := parsed.Certificate
|
|
key := parsed.PrivateKey
|
|
cc := parsed.CongestionControl
|
|
alpn := parsed.ALPN
|
|
udpRelayMode := parsed.UDPRelayMode
|
|
zeroRtt := true
|
|
if parsed.ZeroRTTHandshake != nil {
|
|
zeroRtt = *parsed.ZeroRTTHandshake
|
|
}
|
|
logLevel := parsed.LogLevel
|
|
maxIdle := parsed.MaxIdleTime
|
|
authTimeout := parsed.AuthenticationTimeout
|
|
maxPacketSize := parsed.MaxUdpRelayPacketSize
|
|
sni := parsed.SNI
|
|
|
|
if parsed.Server != nil {
|
|
if parsed.Server.Certificate != "" {
|
|
cert = parsed.Server.Certificate
|
|
}
|
|
if parsed.Server.PrivateKey != "" {
|
|
key = parsed.Server.PrivateKey
|
|
}
|
|
if parsed.Server.CongestionControl != "" {
|
|
cc = parsed.Server.CongestionControl
|
|
}
|
|
if len(parsed.Server.ALPN) > 0 {
|
|
alpn = parsed.Server.ALPN
|
|
}
|
|
if parsed.Server.UDPRelayMode != "" {
|
|
udpRelayMode = parsed.Server.UDPRelayMode
|
|
}
|
|
if parsed.Server.ZeroRTTHandshake != nil {
|
|
zeroRtt = *parsed.Server.ZeroRTTHandshake
|
|
}
|
|
if parsed.Server.LogLevel != "" {
|
|
logLevel = parsed.Server.LogLevel
|
|
}
|
|
if parsed.Server.MaxIdleTime > 0 {
|
|
maxIdle = parsed.Server.MaxIdleTime
|
|
}
|
|
if parsed.Server.AuthenticationTimeout > 0 {
|
|
authTimeout = parsed.Server.AuthenticationTimeout
|
|
}
|
|
if parsed.Server.MaxUdpRelayPacketSize > 0 {
|
|
maxPacketSize = parsed.Server.MaxUdpRelayPacketSize
|
|
}
|
|
if parsed.Server.SNI != "" {
|
|
sni = parsed.Server.SNI
|
|
}
|
|
}
|
|
|
|
if normalized, err := NormalizeCongestionControl(cc); err == nil {
|
|
cc = normalized
|
|
} else {
|
|
cc = "new_reno"
|
|
}
|
|
if len(alpn) == 0 {
|
|
alpn = []string{"h3", "spdy/3.1"}
|
|
}
|
|
if udpRelayMode == "" {
|
|
udpRelayMode = "native"
|
|
}
|
|
if logLevel == "" {
|
|
logLevel = "info"
|
|
}
|
|
if maxIdle <= 0 {
|
|
maxIdle = 15
|
|
}
|
|
if authTimeout <= 0 {
|
|
authTimeout = 3
|
|
}
|
|
if maxPacketSize <= 0 {
|
|
maxPacketSize = 1500
|
|
} else if maxPacketSize > maxSafeUdpRelayPacketSize && maxPacketSize <= maxLegacyUdpRelayPacketSize {
|
|
maxPacketSize = maxSafeUdpRelayPacketSize
|
|
}
|
|
|
|
clients := make([]TuicClientSettings, 0, len(parsed.Clients))
|
|
for _, c := range parsed.Clients {
|
|
if c.Enable != nil && !*c.Enable {
|
|
continue
|
|
}
|
|
uuidVal := strings.ToLower(strings.TrimSpace(c.UUID))
|
|
if uuidVal == "" {
|
|
uuidVal = strings.ToLower(strings.TrimSpace(c.ID))
|
|
}
|
|
if uuidVal == "" || c.Password == "" {
|
|
continue
|
|
}
|
|
clients = append(clients, TuicClientSettings{
|
|
TrafficID: c.TrafficID,
|
|
UUID: uuidVal,
|
|
Password: c.Password,
|
|
Email: c.Email,
|
|
})
|
|
}
|
|
|
|
return Instance{
|
|
Id: ib.Id,
|
|
Tag: ib.Tag,
|
|
Listen: ib.Listen,
|
|
Port: ib.Port,
|
|
Certificate: cert,
|
|
PrivateKey: key,
|
|
CongestionControl: cc,
|
|
ALPN: alpn,
|
|
UDPRelayMode: udpRelayMode,
|
|
ZeroRTTHandshake: zeroRtt,
|
|
LogLevel: logLevel,
|
|
MaxIdleTime: maxIdle,
|
|
AuthenticationTimeout: authTimeout,
|
|
MaxUdpRelayPacketSize: maxPacketSize,
|
|
SNI: sni,
|
|
Clients: clients,
|
|
}, true
|
|
}
|
|
|
|
func NormalizeCongestionControl(value string) (string, error) {
|
|
switch strings.ToLower(strings.TrimSpace(value)) {
|
|
case "", "bbr":
|
|
return "bbr", nil
|
|
case "cubic":
|
|
return "cubic", nil
|
|
case "new_reno", "reno":
|
|
return "new_reno", nil
|
|
default:
|
|
return "", fmt.Errorf("tuic: unsupported congestion controller %q", value)
|
|
}
|
|
}
|